| 1 |
#cython: language_level=3 |
| 2 |
#cython: boundscheck=False |
| 3 |
#cython: wraparound=False |
| 4 |
#cython: cdivision=True |
| 5 |
|
| 6 |
""" |
| 7 |
cython_simulated_annealing.pyx |
| 8 |
|
| 9 |
cython implementation of a simulated annealing algorithm to find the optimal |
| 10 |
spike train order |
| 11 |
|
| 12 |
Note: using cython memoryviews (e.g. double[:]) instead of ndarray objects |
| 13 |
improves the performance of spike_distance by a factor of 10! |
| 14 |
|
| 15 |
Copyright 2015, Mario Mulansky <[email protected]> |
| 16 |
|
| 17 |
Distributed under the BSD License |
| 18 |
|
| 19 |
""" |
| 20 |
|
| 21 |
""" |
| 22 |
To test whether things can be optimized: remove all yellow stuff |
| 23 |
in the html output:: |
| 24 |
|
| 25 |
cython -a cython_simulated_annealing.pyx |
| 26 |
|
| 27 |
which gives: |
| 28 |
|
| 29 |
cython_simulated_annealing.html |
| 30 |
|
| 31 |
""" |
| 32 |
|
| 33 |
import numpy as np |
| 34 |
cimport numpy as np |
| 35 |
|
| 36 |
from libc.math cimport exp |
| 37 |
from libc.math cimport fmod |
| 38 |
from libc.stdlib cimport rand |
| 39 |
from libc.stdlib cimport RAND_MAX |
| 40 |
|
| 41 |
#DTYPE = float |
| 42 |
#ctypedef np.float_t DTYPE_t |
| 43 |
|
| 44 |
def sim_ann_cython(double[:, :] D, double T_start, double T_end, double alpha): |
| 45 |
|
| 46 |
cdef long N = len(D) |
| 47 |
cdef double A = np.sum(np.triu(D, 0)) |
| 48 |
cdef long[:] p = np.arange(N) |
| 49 |
cdef double T = T_start |
| 50 |
cdef long iterations |
| 51 |
cdef long succ_iter |
| 52 |
cdef long total_iter = 0 |
| 53 |
cdef double delta_A |
| 54 |
cdef long ind1 |
| 55 |
cdef long ind2 |
| 56 |
|
| 57 |
while T > T_end: |
| 58 |
iterations = 0 |
| 59 |
succ_iter = 0 |
| 60 |
# equilibrate for 100*N steps or 10*N successful steps |
| 61 |
while iterations < 100*N and succ_iter < 10*N: |
| 62 |
# exchange two rows and cols |
| 63 |
# ind1 = np.random.randint(N-1) |
| 64 |
ind1 = rand() % (N-1) |
| 65 |
if ind1 < N-1: |
| 66 |
ind2 = ind1+1 |
| 67 |
else: # this can never happen! |
| 68 |
ind2 = 0 |
| 69 |
delta_A = -2*D[p[ind1], p[ind2]] |
| 70 |
if delta_A > 0.0 or exp(delta_A/T) > ((1.0*rand()) / RAND_MAX): |
| 71 |
# swap indices |
| 72 |
p[ind1], p[ind2] = p[ind2], p[ind1] |
| 73 |
A += delta_A |
| 74 |
succ_iter += 1 |
| 75 |
iterations += 1 |
| 76 |
total_iter += iterations |
| 77 |
T *= alpha # cool down |
| 78 |
if succ_iter == 0: |
| 79 |
# no successful step -> we believe we have converged |
| 80 |
break |
| 81 |
|
| 82 |
return p, A, total_iter |