-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswarmpi.py
1596 lines (1524 loc) · 66.3 KB
/
swarmpi.py
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
import numpy as np
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from pycbc.waveform import get_fd_waveform
from pycbc.waveform import get_td_waveform
from pycbc.filter import highpass, lowpass_fir
import pycbc.filter
from pycbc.psd import aLIGOZeroDetHighPower, AdvVirgo, KAGRA, from_txt
from pycbc.detector import Detector, get_available_detectors
from pycbc.noise.gaussian import frequency_noise_from_psd
from pycbc.noise.gaussian import noise_from_psd
from pycbc import frame
from pycbc import waveform
from pycbc.types import TimeSeries, FrequencySeries, Array, float32, float64, complex_same_precision_as, real_same_precision_as
## Unix Don't know how it works on other systems!
import time
from datetime import datetime
import sys
import os
import shutil
#from mpi4py import MPI # if needed in the futre
import pickle
from scipy import fft
from glue.ligolw import ligolw
from glue.ligolw import table
from glue.ligolw import lsctables
from glue.ligolw import utils as ligolw_utils
import glob
from astropy.coordinates import cartesian_to_spherical, spherical_to_cartesian
from astropy.coordinates import SkyCoord
from astropy import units as u
import seaborn as sns
from multiprocessing import Pool
##
##
###############################################################################
## Class swarm
## definition
###############################################################################
class inj_par :
m1min=15.0 ## Ms
m1max=40.0 ## Ms
m2min=15.0 ## Ms
m2max=40.0 ## Ms
s1zmin=-0.8
s1zmax=0.8
s2zmin=-0.8
s2zmax=0.8
dmin=300.0 ## Mpc
dmax=1000.0 ## Mpc
seed=None
def __init__(self, waveform,flow=20, enable_spin=0,
inj_seed=None, ifo='I1', search_dim=2,
sps=4096, tmax=10.0, noise_seed=None) :
if (inj_seed != None):
self.seed=inj_seed
np.random.seed(self.seed)
self.noise_seed=noise_seed
self.mass1=np.random.uniform(self.m1min, self.m1max)
self.mass2=np.random.uniform(self.m2min, self.mass1)
self.coa_phase=np.random.uniform(0, 2*np.pi)
self.ra=np.random.uniform(0,np.pi)
self.dec=np.random.uniform(0, 2*np.pi)
self.pol=np.random.uniform(0, 2*np.pi)
## uniform over distance
## self.distance=np.random.uniform(self.dmin, self.dmax)
## But uniform over volume is what we need
x=np.random.uniform(self.dmin, self.dmax)
y=np.random.uniform(self.dmin, self.dmax)
z=np.random.uniform(self.dmin, self.dmax)
self.distance=np.sqrt(x*x+y*y+z*z) ## would be slightly off with
## upper limit should be fine
self.f_lower=flow
self.search_dim=search_dim
self.waveform=waveform
self.sps=sps
self.tmax=tmax
self.ifo=ifo
if enable_spin !=0 :
self.enable_spin=1
self.spin1z=np.random.uniform(self.s1zmin, self.s1zmax)
self.spin2z=np.random.uniform(self.s2zmin, self.s2zmax)
else :
self.spin1z=0.0
self.spin2z=0.0
self.signal_stat=3
#------------------Initialisation for swarm class --------------------------------
class swarm :
'''
class to simulate partcile swarm optimisation
Variables
f_low =20.0 -> lower frequency limit, used in matched filtering
min = [10.0, 10.0] -> lower limit on search parameters, it should be an
array of dimension of parameter space and sets
the lower limit along each dimension
max = [10.0, 10.0] -> upper limit on search parameters, it should be an
array of dimension of parameter space and sets
the upper limit along each dimension
vmin =[-1.0, -1.0] -> lower limit on velovity parameters, it should be an
array of dimension of parameter space and sets
the lower limit along each dimension
vmax =[1.0, 1.0] -> upper limit on velocity parameters, it should be an
array of dimension of parameter space and sets
the upper limit along each dimension
dim = 2 -> dimension of search parameter space
sps = 4*1024 -> sampling rate for the signal
T_max = 5.0 -> length of data segment in sec
delta_f -> frequency resolution
Np -> Number of particles in the swarm
Nsteps -> Maximum number of steps taken by the swarm
curr_step -> Number of steps already taken by the swarm
tlen -> Number of samples in time domain
flen -> Number of samples in the fequency domain
alpha=0.4 -> Alpha parameter of PSO, couple to inertia
beta=0.3 -> Beta parameter of PSO, couple to p_best
gamma=0.4 -> Gamma parameter of PSO, couple to g_best
p_best -> Np x dim array
g_best -> dim array
pbest_corr -> Np array
gbest_corr -> real
x -> position Np x dim array
v -> velocity Np x dim array
distance -> distance im tamplate m Mpc
waveform='IMRPhenomC' -> trivial
snr -> function value at x, Np array
radius -> mean distance from g_best array of size steps
DEBUG -> can be False or True
'''
##########################################################################
def __init__(self,sps, tmax, ifo='I1',flow=20, particles=200, steps=30, dim=2, waveform='IMRPhenomC'):
'''
particles -> number of particle in the swarm
steps -> maximum number of steps taken by the swarm
'''
self.f_low = flow # For template
self.f_upper=1000.0
self.sps= sps # 2 K sps
self.dim = dim #search dimensions
self.T_max = tmax #time duration of wave
self.delta_f = 1.0/self.T_max #frequency resolution
self.Np=particles
self.Nsteps=steps
self.curr_step=0
self.tlen=int(self.sps*self.T_max)
self.flen=int(self.tlen/2)+1
self.alpha=0.4
self.beta=0.3
self.gamma=0.35
self.distance=1.0 ## MPC
self.trigger_time=0.0
self.waveform=waveform
self.ifo=ifo
self.norm=1.0
self.DEBUG = False
self.run_pll=False
self.nof_process=5
if self.dim ==2 :
self.parameters_names=["Mass1", "Mass2"]
self.min = [10.0, 10.0] #minimum value of mass being scanned
self.max = [90.0, 90] #maximum value of mass being scanned
self.vmin =[-1.0, -1.0] ## Velocity limits
self.vmax=[1.0, 1.0] ## Velocity limits
if self.dim == 3 :
self.parameters_names=["Mass1", "Mass2", "S1z"]
self.min = [10.0, 10.0, -0.9]#minimum value of mass being scanned
self.max = [90.0, 90, 0.9] #maximum value of mass being scanned
self.vmin =[-1.0, -1.0, -0.1] ## Velocity limits
self.vmax=[1.0, 1.0, 0.1] ## Velocity limits
if self.dim == 4 :
self.parameters_names=["Mass1", "Mass2", "S1z", "S2z"]
self.min = [10.0, 10.0, -0.9, -0.9]#minimum value of mass being scanned
self.max = [90.0, 90, 0.9, 0.9]#maximum value of mass being scanned
self.vmin =[-1.0, -1.0, -0.1, -0.1] ## Velocity limits
self.vmax=[1.0, 1.0, 0.1, 0.1] ## Velocity limits
self.x=np.zeros((self.Np,self.dim))
self.x[:,0] = np.random.uniform(self.min[0], self.max[0], self.Np)#initial position of each particle in terms of mass 1 and mass 2
self.x[:,1] = np.random.uniform(self.min[1], self.x[:,0], self.Np)#initial position of each particle in terms of mass 1
for kk in range(2, self.dim):
self.x[:,kk] = np.random.uniform(self.min[kk], self.max[kk], self.Np)
#self.p_best = np.zeros((self.Np,self.dim)) #array that stores best position for each particle
self.v = np.random.uniform(self.vmin, self.vmax, (self.Np,self.dim))#initial velocity of each particle
self.pbest = np.copy(self.x)#initialise personal best to initial position for each particle
self.pbest_snr= np.zeros(self.Np)#to store old correlation
self.pbest_toa=np.zeros(self.Np)
self.pbest_phs=np.zeros(self.Np)
self.gbest=np.zeros(self.dim)
self.gbest_snr = 0.0#variable to store best match
self.gbest_toa = 0.0
self.gbest_phs = 0.0
self.snr = np.zeros(self.Np)
self.toa = np.zeros(self.Np)
self.phs = np.zeros(self.Np)
self.radius=np.zeros(self.Nsteps)
self.gbest_snr_step=np.zeros(self.Nsteps)
self.gbest_toa_step=np.zeros(self.Nsteps)
self.gbest_phs_step=np.zeros(self.Nsteps)
#self.sim_insp_par=sim_insp_par
self.evolve=self.evolve_standard_pso
self.evolve_option=0
if self.ifo == 'L1' or self.ifo == 'H1' or self.ifo == 'I1' :
self.psd = aLIGOZeroDetHighPower(self.flen, self.delta_f, self.f_low)
elif self.ifo == 'V1' :
self.psd = AdvVirgo(self.flen, self.delta_f, self.f_low)
elif self.ifo == 'K1' :
self.psd = KAGRA(self.flen, self.delta_f, self.f_low)
else :
raise Exception('Unknown IFO :'+self.ifo)
##end of __init__
##########################################################################
def __del__(self):
'''
cleanup if this might not be needed, but then why not
'''
del self.x, self.v, self.psd, self.radius, self.snr
del self.gbest_snr, self.gbest, self.pbest_snr, self.pbest
del self.min, self.max, self.vmin, self.vmax
del self.f_low, self.sps, self.dim,self.T_max,
del self.delta_f,self.Np,self.Nsteps,self.curr_step,self.tlen
del self.flen, self.alpha, self.beta,self.gamma,self.distance
del self.trigger_time, self.waveform, self.ifo
del self.gbest_snr_step
##########################################################################
def compute_fitness(self, segment):
'''
This is the function which is optmised!
'''
if not self.run_pll :
for jj in range (self.Np):#Correlation foreach point
temp0, temp1=self.generate_template_strain_freqdomain(jj)
csnr0=pycbc.filter.matched_filter(temp0, segment, psd=self.psd, low_frequency_cutoff=self.f_low,high_frequency_cutoff=self.f_upper)
csnr1=pycbc.filter.matched_filter(temp1,segment , psd=self.psd, low_frequency_cutoff=self.f_low,high_frequency_cutoff=self.f_upper)
snr0,idx0=csnr0.abs_max_loc()
snr1,idx1=csnr1.abs_max_loc()
#csnr0=csnr0*np.conj(csnr0)
#csnr1=csnr1*np.conj(csnr1)
#idx0=np.argmax(csnr0)
#idx1=np.argmax(csnr1)
#snr0=csnr0[idx0]
#snr1=csnr1[idx1]
mp=0.5*np.sqrt(snr0**2+snr1**2)
self.snr[jj] = np.real(mp) # v1_norm=None, v2_norm=None
self.toa[jj] = idx0
phase = 2*np.pi - np.angle(csnr0[idx0])
self.phs[jj] = phase % (2*np.pi)
else :
p_pool=Pool(self.nof_process)
res=[]
for jj in range (0,self.Np,self.nof_process):#Correlation foreach point
for kk in range(jj, min(jj+self.nof_process, self.Np)) :
res.append(p_pool.apply_async( self.generate_template_strain_freqdomain, (kk,)))
kk=0
flag=True
while flag:
try :
pp=res.pop(0)
temp0, temp1=pp.get()
csnr0=pycbc.filter.matched_filter(temp0,
segment,
psd=self.psd,
low_frequency_cutoff=self.f_low,
high_frequency_cutoff=self.f_upper)
csnr1=pycbc.filter.matched_filter(temp1,segment,
psd=self.psd,
low_frequency_cutoff=self.f_low,
high_frequency_cutoff=self.f_upper)
csnr0=csnr0*np.conj(csnr0)
csnr1=csnr1*np.conj(csnr1)
idx0=np.argmax(csnr0)
idx1=np.argmax(csnr1)
snr0=csnr0[idx0]
snr1=csnr1[idx1]
mp=0.5*np.sqrt(snr0+snr1)
self.snr[jj+kk] = np.real(mp) # v1_norm=None, v2_norm=None
self.toa[jj+kk] =idx0
kk+=1
except IndexError :
flag=False
## end of compute_fitness
##########################################################################
def compute_pbest(self):
'''
This function find the best postion for a given particle
called p_best
'''
for jj in range (self.Np): ## Finds pbest
if (self.snr[jj]>self.pbest_snr[jj]):
self.pbest[jj,:] = self.x[jj,:]
self.pbest_snr[jj] = self.snr[jj]
self.pbest_toa[jj]=self.toa[jj]
self.pbest_phs[jj]=self.phs[jj]
#updating best match values obtained for each particle
## end of compute_pbest
##########################################################################
def compute_gbest(self):
'''
This function find the global best position found by all particles
'''
idbest= np.argmax(self.pbest_snr)
if self.pbest_snr[idbest] > self.gbest_snr :
self.gbest[:]=self.pbest[idbest,:]
self.gbest_snr=self.pbest_snr[idbest]
self.gbest_toa=self.pbest_toa[idbest]
self.gbest_phs=self.pbest_phs[idbest]
## end of compute_gbest
##########################################################################
def evolve_velocity(self):
'''
This function evolve the velocity as per standard PSO rule
'''
r0 = np.random.rand()
r1 = np.random.rand()
r2 = np.random.rand()
for jj in range (self.Np):
self.v[jj,:] = self.alpha*r0*self.v[jj,:] +\
self.beta*r1*(self.pbest[jj,:]-self.x[jj,:]) +\
self.gamma*r2*(self.gbest-self.x[jj,:])
## end of evolve_velocity
##########################################################################
def evolve_position(self):
'''
This evolves the position of the particle for a given velocity
This function also updates the current step a variable keeps
track of number of steps taken
'''
for jj in range(self.Np):
self.x[jj,:]=self.x[jj,:]+self.v[jj,:]
## Any boundary condition can be explicitly applied
self.curr_step+=1
## end of evolve_position
##########################################################################
def store_gbest(self) :
'''
This function stores gbest for that perticluar step
'''
self.gbest_snr_step[self.curr_step]=self.gbest_snr
self.gbest_toa_step[self.curr_step]=self.gbest_toa
self.gbest_phs_step[self.curr_step]=self.gbest_phs
##########################################################################
def compute_radius(self):
'''
This function computes the mean size, i.e. distance from the gbest of
swarm
'''
if self.DEBUG :
print("This is function compute_radius", self.curr_step)
rad=np.zeros(self.Np)
for jj in range(self.Np):
rad[jj]=np.sqrt(np.sum(np.square(self.x[jj,:]-self.gbest)))
self.radius[self.curr_step]=np.mean(rad)
## end of compute_radius
##########################################################################
def apply_reflecting_boundary(self):
'''
This function put the reflecting boundary at the wall, this might
inprove the convergence if the peak is close to boundary!
'''
## Hope this reflextion about minimum mass for m1 is done
for ii in range(self.dim) :
idx=np.where(self.x[:,ii] < self.min[ii])
self.x[idx,ii]=2*self.min[ii]-self.x[idx,ii]
self.v[idx,ii]=-self.v[idx,ii]
idx=np.where(self.x[:,ii] > self.max[ii])
self.x[idx,ii]=2*self.max[ii]-self.x[idx,ii]
self.v[idx,ii]=-self.v[idx,ii]
idx=np.where(self.x[:,0] < self.x[:,1])
for jj in idx :
tmp=self.x[jj,0]
tmpv=self.v[jj,0]
self.x[jj,0]=self.x[jj,1]
self.v[jj,0]=self.v[jj,1]
self.x[jj,1]=tmp
self.v[jj,1]=tmpv
#self.x[idx,1]=2*self.x[idx,0]-self.x[idx,1]
#self.v[idx,0:2]=-self.v[idx,0:2]
#self.apply_velocity_condition()
for jj in range(2):
idx=np.where(self.x[:,jj] <= 0)
self.x[idx,jj]=self.min[jj]
self.v[idx,jj]=-self.v[idx,jj]
'''
for ii in range (self.Np):#keeping direction same
if (np.linalg.norm(self.v[ii,0:2])>15.0):
self.v[ii,0:2] = np.random.uniform(0.0,1.0)*self.v[ii,0:2]/np.linalg.norm(self.v[ii,0:2])
if self.dim == 4:
for ii in range (self.Np):
if (np.linalg.norm(self.v[ii,2:4])>0.25):
self.v[ii,2:4] = np.random.uniform(0.0,0.1)*self.v[ii,2:4]/np.linalg.norm(self.v[ii,2:4])
'''
'''
if ii < 2:#velocity is kept between -15 and +15 in mass-mass plane
idx = np.where(self.v[:,ii]<-15.0)
self.v[idx,ii] = np.random.uniform(self.vmin[ii],0.0)#reset to number between -1 and 0
idx = np.where(self.v[:,ii]>15.0)
self.v[idx,ii] = np.random.uniform(0.0,self.vmax[ii])#reset to number between 0 and +1
if ii >= 2:#velocity is kept between -0.25 and +0.25 in spin-spin plane
idx = np.where(self.v[:,ii]<-0.25)
self.v[idx,ii] = np.random.uniform(self.vmin[ii],0.0)
idx = np.where(self.v[:,ii]>0.25)
self.v[idx,ii] = np.random.uniform(0.0,self.vmax[ii])
'''
##########################################################################
##########################################################################
def apply_velocity_condition(self):
'''
This function put the reflecting boundary at the wall, this might
inprove the convergence if the peak is close to boundary!
'''
###############
x1=self.x[:,0]
y1=self.x[:,1]
dx=np.abs(x1-y1)
dv=self.v[:,0]+self.v[:,1]
idx=np.where(dv > dx)
scale=0.9
#print idx
self.v[idx,0]=self.v[idx,0]/dv[idx]*dx[idx]*scale
self.v[idx,1]=self.v[idx,1]/dv[idx]*dx[idx]*scale
dx=np.abs(self.x[:,0]-self.max[0])
dv=self.v[:,0]
idx=np.where(dv > dx)
self.v[idx,0]=self.v[idx,0]/dv[idx]*dx[idx]*scale
dy=np.abs(self.x[:,1]-self.max[1])
dv=self.v[:,1]
idx=np.where(dv > dx)
self.v[idx,1]=self.v[idx,1]/dv[idx]*dx[idx]*scale
dx=np.abs(self.min[0]-self.x[:,0])
dv=self.v[:,0]
idx=np.where(dv > dx)
self.v[idx,0]=self.v[idx,0]/dv[idx]*dx[idx]*scale
dy=np.abs(self.min[1]-self.x[:,1])
dv=self.v[:,1]
idx=np.where(dv > dx)
self.v[idx,1]=self.v[idx,1]/dv[idx]*dx[idx]*scale
##########################################################################
def evolve_standard_pso(self, segment) :
'''
This function takes all it needed to take one step as per standard
PSO
'''
#self.compute_radius()
self.compute_fitness(segment)
self.compute_pbest()
self.compute_gbest()
self.store_gbest()
self.evolve_velocity()
self.evolve_position()
self.apply_reflecting_boundary()
## end of evolve_standard_pso
##########################################################################
def evolve_along_mass_eigen_direction(self, segment) :
'''
This function takes a step along one of the eigen value of
the correlation matrix,
drxn -> x takes step along 'x' eigen-direction
## God's comment! This needs some thought on extending
## higher dimension
## direction will be removed in the future version
drxn = 0 means along both eigen vectors
drxn = 1 along eignen vector with larger eigen value
drxn = 2 along eignen vector with smaller eigen value
'''
drxn=self.evolve_option
corr_mat=np.zeros((2,2))
self.compute_radius()
self.compute_fitness(segment)
self.compute_pbest()
self.compute_gbest()
x0=np.copy(self.x)
v0=np.copy(self.v)
f0=np.copy(self.snr)
self.evolve_velocity()
self.evolve_position()
self.apply_reflecting_boundary()
self.compute_fitness(segment)
self.compute_pbest()
self.compute_gbest()
ev=np.zeros(2)
for ii in range(self.Np) :
corr_mat[0,0]=f0[ii]
corr_mat[1,1]=self.snr[ii]
m1=x0[ii,0]; m2=self.x[ii,1]
hptilde, hctilde = get_fd_waveform(approximant=self.waveform,
mass1=m1,
mass2=m2,
distance=self.distance,
f_lower=self.f_low,
delta_f=self.delta_f)
hptilde.resize(self.flen)
#psd = aLIGOZeroDetHighPower(self.flen, self.delta_f, self.f_low)
mp, i = filter.match(segment, hptilde, psd=self.psd,
low_frequency_cutoff=self.f_low,
v1_norm=self.norm, v2_norm=None)
corr_mat[0,1]=mp
if mp > self.gbest_snr :
self.gbest_snr=mp
self.gbest[:]=self.x[ii,:]
self.gbest[0]=m1
self.gbest[1]=m2
m1=self.x[ii,0]; m2=x0[ii,1]
hptilde, hctilde = get_fd_waveform(approximant=self.waveform,
mass1=m1,
mass2=m2,
distance=self.distance,
f_lower=self.f_low,
delta_f=self.delta_f)
hptilde.resize(self.flen)
# Generate the aLIGO ZDHP PSD
mp, i = filter.match(segment, hptilde, psd=self.psd,
low_frequency_cutoff=self.f_low,
v1_norm=self.norm, v2_norm=None)
corr_mat[1,0]=mp
if mp > self.gbest_snr :
self.gbest_snr=mp
self.gbest[:]=self.x[ii,:]
self.gbest[0]=m1
self.gbest[1]=m2
#print corr_mat
wa, va = np.linalg.eig(corr_mat)
drxn1 = np.argmax(wa) #larger eigenvalue
drxn2 = (drxn1+1)%2 # Smaller eigenvalue :)
ev0=va[:,drxn1] #larger eigenvector
ev1=va[:,drxn2] #smaller eigenvector
disp = self.x[ii,:]-x0[ii,:] #difference in position
vel = self.v[ii,:]-v0[ii,:] #difference in velocity
proj_disp0 = np.dot(disp, ev0)*ev0 #projection of displacement on larger e.v
proj_disp1 = np.dot(disp, ev1)*ev1 #projection on smaller e.v
proj_vel0 = np.dot(vel, ev0)*ev0 #projection of velocity difference on larger e.v
proj_vel1 = np.dot(vel, ev1)*ev1 #projection on smaller e.v
dm1=self.x[ii,0]-x0[ii,0]
dm2=self.x[ii,1]-x0[ii,1]
dv1=self.v[ii,0]-v0[ii,0]
dv2=self.v[ii,1]-v0[ii,1]
if drxn ==0 :
self.x[ii,:] = self.x[ii,:] + proj_disp0 + proj_disp1
#self.v[ii,:] = self.v[ii,:] + proj_vel0 + proj_vel1
## This combination seems to converge!
if drxn ==1 :
self.x[ii,:] = self.x[ii,:] + proj_disp0
#self.v[ii,:] = self.v[ii,:] + proj_vel0
## This combination seems to converge too!
if drxn ==2 :
self.x[ii,:] = self.x[ii,:] + proj_disp1
#self.v[ii,:] = self.v[ii,:] + proj_vel1
#self.v[ii,:] = self.v[ii,:] - proj_vel0
## This combination seems to converge too!
if drxn ==2 :
self.x[ii,:] = self.x[ii,:] + proj_disp1
#self.v[ii,:] = self.v[ii,:] - proj_vel1
## This combination seems to converge too!
if drxn == 3:
self.x[ii,0]=self.x[ii,0]-(dm1*va[0,0]+dm2*va[0,1])
self.x[ii,1]=self.x[ii,1]-(dm1*va[1,0]+dm2*va[1,1])
self.apply_reflecting_boundary()
#print wa
#print wa[drxn]*va[:,drxn]
#self.v[ii,:]=self.v[ii,:]+wa[drxn]*va[:,drxn]
## end of evolve_along_eigen_direction
## end of evolve_along_eigen_direction
##########################################################################
##########################################################################
def evolve_along_spin_eigen_direction(self, segment) :
'''
needs clean up, might not work correctly
This function takes a step along one of the eigen value of
the correlation matrix,
drxn -> x takes step along 'x' eigen-direction
## God's comment! This needs some thought on extending
## higher dimension
## direction will be removed in the future version
'''
drxn=self.evolve_option
corr_mat=np.zeros((2,2))
self.compute_radius()
self.compute_fitness(segment)
self.compute_pbest()
self.compute_gbest()
x0=np.copy(self.x)
v0=np.copy(self.v)
f0=np.copy(self.snr)
self.evolve_velocity()
self.evolve_position()
self.apply_reflecting_boundary()
self.compute_fitness(segment)
ev=np.zeros(2)
for ii in range(self.Np) :
#print x0[ii,:], self.x[ii,:], x0[ii,:]-self.x[ii,:]
corr_mat[0,0]=f0[ii]
corr_mat[1,1]=self.snr[ii]
s1z=x0[ii,2]; s2z=self.x[ii,3]
ds=self.x[ii,2:4]-x0[ii,2:4]
dv=self.v[ii,2:4]-v0[ii,2:4]
hptilde, hctilde = get_fd_waveform(approximant=self.waveform,
mass1=self.x[ii,0],
mass2=self.x[ii,1],
spin1z=s1z,
spin2z=s2z,
distance=self.distance,
f_lower=self.f_low,
delta_f=self.delta_f)
hptilde.resize(self.flen)
psd = aLIGOZeroDetHighPower(self.flen, self.delta_f, self.f_low)
mp, i = filter.match(segment, hptilde, psd=psd, low_frequency_cutoff=self.f_low)
corr_mat[0,1]=mp
s1z=x0[ii,3]; s2z=self.x[ii,2]
hptilde, hctilde = get_fd_waveform(approximant=self.waveform,
mass1=self.x[ii,0],
mass2=self.x[ii,1],
spin1z=s1z,
spin2z=s2z,
distance=self.distance,
f_lower=self.f_low,
delta_f=self.delta_f)
hptilde.resize(self.flen)
# Generate the aLIGO ZDHP PSD
psd = aLIGOZeroDetHighPower(self.flen, self.delta_f, self.f_low)
mp, i = filter.match(segment, hptilde, psd=psd, low_frequency_cutoff=self.f_low)
corr_mat[1,0]=mp
#print corr_mat
wa, va = np.linalg.eig(corr_mat)
drxn1 = np.argmax(wa) #larger eigenvalue
drxn2 = np.argmin(wa) # Smaller eigenvalue
self.x[ii,2:4]=self.x[ii,2:4]+np.dot(ds,va[:,drxn1])*va[:,drxn1]+np.dot(ds,va[:,drxn2])*va[:,drxn2]
# self.v[ii,2:4]=self.v[ii,2:4]+np.dot(dv,va[:,drxn1])*va[:,drxn1]+np.dot(dv,va[:,drxn2])*va[:,drxn2]
# ev=wa[drxn]*va[:,drxn]
# self.x[ii,2]=x0[ii,2]-(ds1*va[0,0]+ds2*va[0,1])
# self.x[ii,3]=x0[ii,3]-(ds1*va[1,0]+ds2*va[1,1])
# self.v[ii,2]=v0[ii,2]-(dv1*va[0,1]+dv2*va[0,1])
# self.v[ii,3]=v0[ii,3]-(dv1*va[1,1]+dv2*va[1,1])
self.apply_reflecting_boundary()
#print wa
#print wa[drxn]*va[:,drxn]
###########################################################################
def set_alpha(self, a) :
'''
changes the value of parameter alpha
'''
self.alpha=a
## end of set_alpha
##########################################################################
def set_beta(self, b) :
'''
changes the value of parameter beta
'''
self.beta=b
## end of set_beta
##########################################################################
def set_gamma(self, g) :
'''
changes the value of parameter gamma
'''
self.gamma=g
## end of set_gamma
##########################################################################
#def print_pos_variables(self, fid=sys.stdout) :
'''
This is to print the complete state of PSO
'''
# print >> fid, "function: swarm.print_pos_variables"
# print >> fid, "Not implemented yet"
# pass
##############################################################################
def generate_template_strain_freqdomain(self, Pjj):
ifo=self.ifo
d=Detector(ifo)
pol=np.random.uniform(0,2*np.pi)
ra, dec= d.optimal_orientation(self.trigger_time)
Fp, Fc = d.antenna_pattern(ra,dec,pol,self.trigger_time)
dim=self.dim
if dim ==2 :
hp0, hc0 = get_fd_waveform(approximant=self.waveform,
mass1=self.x[Pjj,0],
mass2=self.x[Pjj,1],
f_lower=self.f_low,
coa_phase=0.0,
distance=self.distance,
delta_f=self.delta_f)
hp1, hc1 = get_fd_waveform(approximant=self.waveform,
mass1=self.x[Pjj,0],
mass2=self.x[Pjj,1],
f_lower=self.f_low,
coa_phase=np.pi/2,
distance=self.distance,
delta_f=self.delta_f)
if dim ==3 :
hp0, hc0 = get_fd_waveform(approximant=self.waveform,
mass1=self.x[Pjj,0],
mass2=self.x[Pjj,1],
spin1z=self.x[Pjj,2],
f_lower=self.f_low,
coa_phase=0.0,
distance=self.distance,
delta_f=self.delta_f)
hp1, hc1 = get_fd_waveform(approximant=self.waveform,
mass1=self.x[Pjj,0],
mass2=self.x[Pjj,1],
spin1z=self.x[Pjj,2],
f_lower=self.f_low,
coa_phase=np.pi/2,
distance=self.distance,
delta_f=self.delta_f)
if dim ==4 :
hp0, hc0 = get_fd_waveform(approximant=self.waveform,
mass1=self.x[Pjj,0],
mass2=self.x[Pjj,1],
spin1z=self.x[Pjj,2],
spin2z=self.x[Pjj,3],
f_lower=self.f_low,
coa_phase=0.0,
distance=self.distance,
delta_f=self.delta_f)
hp1, hc1 = get_fd_waveform(approximant=self.waveform,
mass1=self.x[Pjj,0],
mass2=self.x[Pjj,1],
spin1z=self.x[Pjj,2],
spin2z=self.x[Pjj,3],
f_lower=self.f_low,
coa_phase=np.pi/2,
distance=self.distance,
delta_f=self.delta_f)
hp0.resize(self.flen)
hc0.resize(self.flen)
hp1.resize(self.flen)
hc1.resize(self.flen)
#ht0=hp0*Fp+hc0*Fc
#ht1=hp1*Fp+hc1*Fc
ht0=hp0 # Let us test with this
ht1=hp1
return ht0, ht1
##############################################################################
##############################################################################
## End of class
##############################################################################
##############################################################################
## Some useful plotting function may be added here, as it is getting complecated
## to write them in differrent code
def plot_mean_distance(sw_list, file_name ):
'''
sw_list should be list of swarms
file_name is where figure saved
'''
n_swarms=len(sw_list)
s_dim=sw_list[0].dim
plt.figure(figsize=(8, 6))
for kk in range(n_swarms) :
plt.plot(sw_list[kk].radius, '-ok',markerfacecolor='r')
plt.xlabel('Steps')
plt.ylabel('Mean Radius')
plt.title('Swarm size for '+str(n_swarms)+' Number of swarms')
plt.grid()
plt.savefig(file_name)
plt.close()
##############################################################################
def plot_swarm_gbest_snr(sw_list, file_name ):
'''
sw_list should be list of swarms
file_name is where figure saved
'''
n_swarms=len(sw_list)
s_dim=sw_list[0].dim
plt.figure(figsize=(8, 6))
for kk in range(n_swarms) :
plt.plot(sw_list[kk].gbest_snr_step, '-ok',markerfacecolor='r')
plt.xlabel('Steps')
plt.ylabel('Gbest')
plt.title('Swarm size for '+str(n_swarms)+' Number of swarms')
plt.grid()
plt.savefig(file_name)
plt.close()
##############################################################################
def save_swarm_poistion(sw_list, file_name ):
try :
fd=open(file_name,'w')
pickle.dump(sw_list,fd)
fd.close()
except OSError :
print('unable to write to data file '+file_name)
##############################################################################
##############################################################################
class double_swarm:
'''
This is two swarm class for evolving two swarms exchaning information and
optimising thier path
'''
def __init__(self,sps, tmax, sim_insp_par, ifo='L1',flow=20, particles=200, steps=30, dim=2):
self.sw1=swarm(particles=particles, steps=particles, dim=dim)
self.sw2=swarm(particles=particles, steps=particles, dim=dim)
self.x10=np.zeros(self.sw1.x.shape)
self.x20=np.zeros(self.sw1.x.shape)
## Why below variables are needed!
self.corr00=np.zeros(self.sw1.Np)
self.corr01=np.zeros(self.sw1.Np)
#self.corr10=np.zeros(self.sw1.Np)
#self.corr11=np.zeros(self.sw1.Np)
self.curr_step=0
self.corr_mat=np.zeros((2,2))
self.gbest=np.zeros(self.dim)
self.gbest_snr = 0.0
def evolve_two_swarm_eigen_direction(self,segment, drxn=0 ) :
'''
This funtion veloves two swarm as standard PSO and moves along eigen direction
segment -> signal segment
drxn -> 0 means, standard PSO do nothing
-> 1 means , {m1, m2} eigen direction
-> 3 means, {s1z, s2z} eigen direction
-> 4 means both {m1, m2} and {s1z, s2z}
'''
self.sw1.compute_fitness(segment)
self.sw1.compute_pbest()
self.sw1.compute_gbest()
self.sw2.compute_fitness(segment)
self.sw2.compute_pbest()
self.sw2.compute_gbest()
self.x10[:]=self.sw1.x[:]
self.x20[:]=self.sw2.x[:]
self.corr00[:]=self.sw1.snr[:]
self.corr01[:]=self.sw2.snr[:]
self.sw1.evolve_velocity()
self.sw1.evolve_position()
self.sw1.apply_reflecting_boundary()
self.sw2.evolve_velocity()
self.sw2.evolve_position()
self.sw2.apply_reflecting_boundary()
self.sw1.compute_fitness(segment)
self.sw2.compute_fitness(segment)
Npmin=min(self.sw1.Np, self.sw2.Np)
for ii in range(Npmin) :
dx=self.sw1.x[ii,0:2]-self.sw2.x[ii,0:2]
dv=self.sw1.v[ii,0:2]-self.sw2.v[ii,0:2]
self.corr_mat[0,0]=self.corr00[ii]
self.corr_mat[0,1]=self.corr01[ii]
self.corr_mat[1,0]=self.sw1.snr[ii]
self.corr_mat[1,1]=self.sw2.snr[ii]
wa,ev=np.linalg.eig(self.corr_mat)
drxn1 = np.argmax(wa) #larger eigenvalue
drxn2 = np.argmin(wa) # Smaller eigenvalue
self.sw1.x[ii,:]=self.x10[ii,:]+np.dot(dx,ev[:,drxn1])*ev[:,drxn1]
self.sw2.x[ii,:]=self.x20[ii,:]+np.dot(dx,ev[:,drxn2])*ev[:,drxn2]
#self.sw1.v[ii,:]=self.sw1.v[ii,:]+np.dot(dv,ev[:,drxn1])*ev[:,drxn1]
#self.sw2.v[ii,:]=self.sw2.v[ii,:]+np.dot(dv,ev[:,drxn2])*ev[:,drxn2]
self.sw1.apply_reflecting_boundary()
self.sw2.apply_reflecting_boundary()
self.sw1.compute_radius()
self.sw2.compute_radius()
def compute_gbest(self):
s1=self.sw1.gbest_snr
s2=self.sw2.gbest_snr
if s1 > s2 :
self.sw2.gbest_snr=s1
self.sw2.gbest=self.sw1.gbest
self.gbest_snr=s1
self.gbest=self.sw1.gbest
else :
self.sw1.gbest_snr=s2
self.sw1.gbest=self.sw2.gbest
self.gbest_snr=s2
self.gbest=self.sw1.gbest
#####################################################################################################
def generate_data_segment(row):
ifo=row.ifo
d=Detector(ifo)
signal_sps=row.sps
delta_f=1.0/row.tmax
delta_t=1.0/row.sps
tlen=int(row.tmax*row.sps)
flen=int(tlen/2)+1
wvform = row.waveform
trig_time=row.geocent_end_time
st_time=row.st_time
if row.injx_mode== 0 or row.injx_mode== 2 :
if ifo == 'L1' or ifo == 'H1' or ifo=='I1' :
psd=aLIGOZeroDetHighPower(flen, delta_f,row.f_lower )
elif ifo == 'V1' :
psd=AdvVirgo(flen, delta_f,row.f_lower)
elif ifo == 'K1':
psd=KAGRA(flen, delta_f,row.f_lower)
else :
raise Exception('Unknown IFO :'+self.ifo)
##print('noise seed=', row.noise_seed)
noise = pycbc.noise.gaussian.noise_from_psd( tlen, delta_t, psd, seed=row.noise_seed)
#print(len(noise))
if row.injx_mode== 0 :
signal = noise
#noise.resize(tlen)
if row.injx_mode == 1 or row.injx_mode == 2 :
hp, hc = get_td_waveform(approximant=row.waveform,
mass1=row.mass1,
mass2=row.mass2,
spin1x=row.spin1x,
spin2x=row.spin2x,
spin1y=row.spin1y,
spin2y=row.spin2y,
spin1z=row.spin1z,
spin2z=row.spin2z,
f_lower=row.f_lower,
coa_phase=row.coa_phase,
inclination=row.inclination,
polarization=row.polarization,
distance=row.distance,
delta_t=delta_t)
noise.start_time=st_time
hp.start_time=trig_time
hc.start_time=trig_time
signal = d.project_wave( hp, hc, row.ra_dec[0], row.ra_dec[1], row.polarization, method='constant', reference_time=trig_time )
if False :
plt.plot(noise.sample_times, noise, 'b', label='Noise')
plt.plot(signal.sample_times, signal, 'r', label='Signal')
plt.legend()
plt.savefig('signal.png')
exit(-1)
signal=noise.inject(signal)
if False :
plt.plot(signal.sample_times, signal, 'C0', label='Signal')
plt.legend()
plt.savefig('signal.png')
exit(-1)
return signal, psd
##############################################################################
def generate_timedomain_strain(row): ## would be depricate soon
ifo=row.ifo
search_dim=row.search_dim
d=Detector(ifo)
if hasattr(row, 'row') :
row1=row.row
Fp, Fc = d.antenna_pattern(row1.ra_dec[0], row1.ra_dec[1], row1.polarization, row1.time_geocent)
else :
row1=row
Fp, Fc = d.antenna_pattern(row1.ra, row1.dec, row1.pol, row1.trig_time)
signal_sps=row.sps
#Fp, Fc = d.antenna_pattern(row1.ra_dec[0], row1.ra_dec[1], row1.polarization, row1.trig_time)
print("row.tmax",row.tmax)
delta_f=1.0/row.tmax
delta_t=1.0/4096
tlen=int(row.tmax*row.sps)
flen=int(tlen/2)+1
print(ifo)
if ifo == 'L1' or ifo == 'H1' or ifo=='I1' :
psd=aLIGOZeroDetHighPower(flen, delta_f,row1.f_lower )
elif ifo == 'V1' :
psd=AdvVirgo(flen, delta_f,row1.f_lower)
elif ifo == 'K1':
psd=KAGRA(flen, delta_f,row1.f_lower)
elif ifo == 'L2' or ifo == 'H2' : ## L2 and H2 stands for 02 noise PSD
psd = from_txt(row.O2_PSD_file,flen, delta_f, row1.f_lower,False)
else :
raise Exception('Unknown IFO :'+self.ifo)
wvform = row1.waveform
if row.signal_stat != 1 :
noise = pycbc.noise.gaussian.noise_from_psd(tlen, delta_t, psd, seed=row.noise_seed)
#noise.resize(tlen)
if row.signal_stat == 3 or row.signal_stat == 4 :
ts=frame.read_frame(row.frame_file_name,row.frame_ch)
ts = highpass(ts, row1.f_lower)
ts = lowpass_fir(ts, 1200, 8)
t0=int((row.trig_time-row.st_time)*row.sps)
t1=t0+int(row.tmax*row.sps)
ts=ts[t0:t1]
ts= ts.detrend('constant')
#mx=2*max(ts)
#y=np.linspace(-mx, mx, 30)