tsp.pyx 8.44 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
# -*- coding: utf-8 -*-
"""
GEPARD - Gepard-Enabled PARticle Detection
Copyright (C) 2018  Lars Bittrich and Josef Brandt, Leibniz-Institut für 
Polymerforschung Dresden e. V. <bittrich-lars@ipfdd.de>    

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 <https://www.gnu.org/licenses/>.
"""
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]<n[1]
                nn = (n0+nct -n1-1) % nct  # number of cities not on the segment n[0]..n[1]
                if nn>=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