# -*- coding: utf-8 -*- """ GEPARD - Gepard-Enabled PARticle Detection Copyright (C) 2018 Lars Bittrich and Josef Brandt, Leibniz-Institut für Polymerforschung Dresden e. V. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program, see COPYING. If not, see . """ import numpy as np from numpy.linalg import norm from libc.math cimport exp, sqrt from libc.stdlib cimport rand, RAND_MAX cimport numpy as np cimport cython DTYPE = np.float ctypedef np.float_t DTYPE_t ctypedef np.int32_t INT32_t ctypedef np.int64_t INT64_t @cython.cdivision(True) cdef double pyrand(): return rand()/float(RAND_MAX) @cython.cdivision(True) cdef int randint(int N): return rand()%N @cython.boundscheck(False) # assume: no index larger than N-1 @cython.wraparound(False) # assume: no neg. index cdef double getdist(int n1, int n2, np.ndarray[DTYPE_t, ndim=2] points): cdef double dx, dy cdef int N=points.shape[0] if n1==N or n2==N: return 0.0 dx = points[n1,0]-points[n2,0] dy = points[n1,1]-points[n2,1] return sqrt(dx*dx + dy*dy) cpdef TotalDistance(city, R): dist = np.sum(np.sqrt(np.sum(np.diff(R[city[:-1],:],axis=0)**2,axis=1))) return dist # use this only after debugging! @cython.boundscheck(False) # assume: no index larger than N-1 @cython.wraparound(False) # assume: no neg. index cdef reverse(np.ndarray[INT32_t, ndim=1] city, int n0, int n1): cdef int nct, nn, j, k, l nct = city.shape[0] nn = cython.cdiv((1+ ((n1-n0) % nct)),2) # half the lenght of the segment to be reversed # the segment is reversed in the following way n[0]<->n[1], n[0]+1<->n[1]-1, n[0]+2<->n[1]-2,... # Start at the ends of the segment and swap pairs of cities, moving towards the center. for j in range(nn): k = (n0+j) % nct l = (n1-j) % nct city[k], city[l] = city[l], city[k] # swap # use this only after debugging! @cython.boundscheck(False) # assume: no index larger than N-1 @cython.wraparound(False) # assume: no neg. index cdef np.ndarray[INT32_t, ndim=1] transpt(np.ndarray[INT32_t, ndim=1] city, int n0, int n1, int n2, int n3, int n4, int n5): cdef int nct, j, i cdef np.ndarray[INT32_t, ndim=1] newcity = np.empty_like(city) nct = city.shape[0] i = 0 # Segment in the range n[0]...n[1] for j in range( (n1-n0)%nct + 1): newcity[i] = city[ (j+n0)%nct ] i += 1 # is followed by segment n[5]...n[2] for j in range( (n2-n5)%nct + 1): newcity[i] = city[ (j+n5)%nct ] i += 1 # is followed by segment n[3]...n[4] for j in range( (n4-n3)%nct + 1): newcity[i] = city[ (j+n3)%nct ] i += 1 return newcity # use this only after debugging! @cython.boundscheck(False) # assume: no index larger than N-1 @cython.wraparound(False) # assume: no neg. index def tspcomp(np.ndarray[DTYPE_t, ndim=2] points, np.ndarray[INT32_t, ndim=1] city=None, int maxTsteps=100, double Tstart=0.2, double fCool=0.9, int usemat=1): """ maxTsteps = 50 # Temperature is lowered not more than maxTsteps Tstart = 0.2 # Starting temperature - has to be high enough fCool = 0.9 # Factor to multiply temperature at each cooling step """ cdef int ncity, maxSteps, maxAccepted, nct, t, i, accepted, n0, n1, n2, n3, n4, n5, nn, nc cdef double Preverse, T, de, dist cdef np.ndarray[INT32_t, ndim=1] ind cdef np.ndarray[DTYPE_t, ndim=1] d cdef np.ndarray[DTYPE_t, ndim=2] distmat ncity = points.shape[0] maxSteps = 100*ncity # Number of steps at constant temperature maxAccepted = 10*ncity # Number of accepted steps at constant temperature Preverse = 0.5 # How often to choose reverse/transpose trial move # Choosing city coordinates if usemat: distmat = np.zeros((ncity+1,ncity+1)) for i in range(ncity): ind = np.arange(i+1,ncity, dtype=np.int32) d = norm(points[ind,:]-points[i,:][np.newaxis,:],axis=1) distmat[i,i+1:-1] = d distmat[i+1:-1,i] = d # The index table -- the order the cities are visited. if city is None: city = np.arange(ncity+1, dtype=np.int32) else: assert city.shape[0]==ncity city = np.concatenate((city,np.int32([ncity]))) # Distance of the travel at the beginning dist = TotalDistance(city, points) # Stores points of a move nct = ncity+1 # number of cities T = Tstart # temperature for t in range(maxTsteps): # Over temperature accepted = 0 for i in range(maxSteps): # At each temperature, many Monte Carlo steps while True: # Will find two random cities sufficiently close by # Two cities n[0] and n[1] are choosen at random n0 = randint((nct)) # select one city n1 = randint((nct-1)) # select another city, but not the same if (n1 >= n0): n1 += 1 # elif (n1 < n0): n0, n1 = n1, n0 # swap, because it must be: n[0]=3: break # We want to have one index before and one after the two cities # The order hence is [n2,n0,n1,n3] n2 = (n0-1) % nct # index before n0 -- see figure in the lecture notes n3 = (n1+1) % nct # index after n2 -- see figure in the lecture notes if Preverse > pyrand(): # Here we reverse a segment # What would be the cost to reverse the path between city[n[0]]-city[n[1]]? if usemat: de = distmat[city[n2],city[n1]] + distmat[city[n3], city[n0]] - \ distmat[city[n2],city[n0]] - distmat[city[n3], city[n1]] else: de = getdist(city[n2],city[n1], points) + getdist(city[n3],city[n0], points) - \ getdist(city[n2],city[n0], points) - getdist(city[n3],city[n1], points) if de<0 or exp(-cython.cdiv(de,T))>pyrand(): # Metropolis accepted += 1 dist += de reverse(city, n0, n1) else: # Here we transpose a segment nc = (n1+1+ randint((nn-1)))%nct # Another point outside n[0],n[1] segment. See picture in lecture nodes! n4 = nc n5 = (nc+1) % nct # Cost to transpose a segment if usemat: de = -distmat[city[n1],city[n3]] - \ distmat[city[n0],city[n2]] - \ distmat[city[n4],city[n5]] de += distmat[city[n0],city[n4]] + \ distmat[city[n1],city[n5]] + \ distmat[city[n2],city[n3]] else: de = -getdist(city[n1],city[n3], points) - \ getdist(city[n0],city[n2], points) - \ getdist(city[n4],city[n5], points) + \ getdist(city[n0],city[n4], points) + \ getdist(city[n1],city[n5], points) + \ getdist(city[n2],city[n3], points) if de<0 or exp(-cython.cdiv(de,T))>pyrand(): # Metropolis accepted += 1 dist += de city = transpt(city, n0, n1, n2, n3, n4, n5) if accepted > maxAccepted: break print("T=%10.5f , distance= %10.5f , accepted steps= %d" %(T, dist, accepted)) T *= fCool # The system is cooled down if accepted == 0: break # If the path does not want to change any more, we can stop for i in range(nct): if city[i]==ncity: break c = np.concatenate((city[i+1:], city[:i])) return c, T