-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdo_manage2.py
1746 lines (1496 loc) · 60.4 KB
/
do_manage2.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
import time
import numpy as np
import pandas as pd
import healpy as hp
from astropy.table import Table
from astropy.io import fits
from astropy.wcs import WCS
from scipy import interpolate
import os, socket, subprocess, shlex
import argparse
import logging, traceback
import paramiko
from helper_funcs import send_email, send_error_email, send_email_attach, send_email_wHTML
from sqlite_funcs import get_conn
from dbread_funcs import get_files_tab, get_info_tab, guess_dbfname
from coord_conv_funcs import convert_radec2imxy, convert_imxy2radec,\
convert_radec2thetaphi, convert_theta_phi2radec
from hp_funcs import pc_probmap2good_outFoVmap_inds
def cli():
parser = argparse.ArgumentParser()
parser.add_argument('--evfname', type=str,\
help="Event data file",
default=None)
parser.add_argument('--fp_dir', type=str,\
help="Directory where the detector footprints are",
default='/storage/work/jjd330/local/bat_data/rtfp_dir_npy/')
parser.add_argument('--Nrate_jobs', type=int,\
help="Total number of jobs",
default=16)
parser.add_argument('--TSscan', type=float,\
help="Min TS needed to do a full FoV scan",
default=6.25)
parser.add_argument('--pix_fname', type=str,\
help="Name of the file with good imx/y coordinates",\
default='good_pix2scan.npy')
parser.add_argument('--bkg_fname', type=str,\
help="Name of the file with the bkg fits",\
default='bkg_estimation.csv')
parser.add_argument('--dbfname', type=str,\
help="Name to save the database to",\
default=None)
parser.add_argument('--GWname', type=str,\
help="Name of the event to submit jobs as",\
default='')
parser.add_argument('--queue', type=str,\
help="Name of the queue to submit jobs to",\
default='cyberlamp')
parser.add_argument('--qos', type=str,\
help="Name of the qos to submit jobs to",\
default=None)
parser.add_argument('--pcfname', type=str,\
help="Name of the partial coding image",\
default='pc_2.img')
parser.add_argument('--BKGpyscript', type=str,\
help="Name of python script for Bkg Estimation",\
default='do_bkg_estimation_wPSs_mp2.py')
parser.add_argument('--RATEpyscript', type=str,\
help="Name of python script for Rates analysis",\
default='do_rates_mle_InOutFoV2.py')
parser.add_argument('--LLHINpyscript', type=str,\
help="Name of python script for LLH analysis",\
default='do_llh_inFoV4realtime2.py')
parser.add_argument('--LLHOUTpyscript', type=str,\
help="Name of python script for LLH analysis",\
default='do_llh_outFoV4realtime2.py')
# parser.add_argument('--SCANpyscript', type=str,\
# help="Name of python script for FoV scan",\
# default='do_llh_scan_uncoded.py')
# parser.add_argument('--PEAKpyscript', type=str,\
# help="Name of python script for FoV scan",\
# default='do_intLLH_forPeaks.py')
parser.add_argument('--do_bkg',\
help="Submit the BKG estimation script",\
action='store_true')
parser.add_argument('--do_rates',\
help="Submit the Rate jobs",\
action='store_true')
parser.add_argument('--do_llh',\
help="Submit the llh jobs",\
action='store_true')
parser.add_argument('--do_scan',\
help="Submit the scan jobs",\
action='store_true')
parser.add_argument('--skip_waiting',\
help="Skip waiting for the stuff to finish and use what's there now",\
action='store_true')
parser.add_argument('--archive',\
help="Run in archive mode, not realtime mode",\
action='store_true')
parser.add_argument('--rhel7',\
help="Submit to a rhel7 node",\
action='store_true')
parser.add_argument('--pbs_fname', type=str,\
help="Name of pbs script",\
default='/storage/work/jjd330/local/bat_data/BatML/submission_scripts/pyscript_template.pbs')
parser.add_argument('--pbs_rhel7_fname', type=str,\
help="Name of pbs script",\
default='/storage/work/jjd330/local/bat_data/BatML/submission_scripts/pyscript_template_rhel7.pbs')
parser.add_argument('--min_pc', type=float,\
help="Min partical coding fraction to use",\
default=0.1)
parser.add_argument('--twind', type=float,\
help="Number of seconds to go +/- from the trigtime",\
default=20)
parser.add_argument('--rateTScut', type=float,\
help="Min split det TS for seeding",\
default=4.5)
args = parser.parse_args()
return args
def im_dist(imx0, imy0, imx1, imy1):
return np.hypot(imx0 - imx1, imy0 - imy1)
def get_rate_res_fnames(direc='.'):
rate_fnames = [fname for fname in os.listdir(direc) if ('rates' in fname) and (fname[-4:]=='.csv')]
return rate_fnames
def get_res_fnames(direc='.'):
res_fnames = [fname for fname in os.listdir(direc) if (fname[-4:]=='.csv') and (fname[:4]=='res_')]
return res_fnames
def get_scan_res_fnames(direc='.'):
res_fnames = [fname for fname in os.listdir(direc) if (fname[-4:]=='.csv') and ('scan_res_' in fname)]
return res_fnames
# def get_peak_res_fnames(direc='.'):
#
# res_fnames = [fname for fname in os.listdir(direc) if (fname[-4:]=='.csv') and ('peak_scan_' in fname)]
# return res_fnames
def get_in_res_fnames(direc='.'):
rate_fnames = [fname for fname in os.listdir(direc) if (fname[:3]=='res') and\
(fname[-4:]=='.csv') and (not 'hpind' in fname)]
return rate_fnames
def get_peak_res_fnames(direc='.'):
rate_fnames = [fname for fname in os.listdir(direc) if (fname[:4]=='peak') and\
(fname[-4:]=='.csv') and (not 'hpind' in fname)]
return rate_fnames
def get_out_res_fnames(direc='.'):
rate_fnames = [fname for fname in os.listdir(direc) if (fname[:3]=='res') and\
(fname[-4:]=='.csv') and ('hpind' in fname)]
return rate_fnames
def get_merged_csv_df(csv_fnames, direc=None, ignore_index=False):
dfs = []
for csv_fname in csv_fnames:
try:
if direc is None:
dfs.append(pd.read_csv(csv_fname, dtype={'timeID':np.int}))
else:
dfs.append(pd.read_csv(os.path.join(direc,csv_fname), dtype={'timeID':np.int}))
except Exception as E:
logging.error(E)
continue
df = pd.concat(dfs, ignore_index=ignore_index)
return df
def probm2perc(pmap):
bl = (pmap>0)
p_map = np.copy(pmap)
inds_sort = np.argsort(p_map)[::-1]
perc_map = np.zeros_like(p_map)
perc_map[inds_sort] = np.cumsum(p_map[inds_sort])#*\
perc_map[~bl] = 1.
return perc_map
def get_merged_csv_df_wpos(csv_fnames, attfile, perc_map=None, direc=None, dur_name='dur', ignore_index=False):
dfs = []
for csv_fname in csv_fnames:
try:
if direc is None:
tab = pd.read_csv(csv_fname, dtype={'timeID':np.int})
else:
tab = pd.read_csv(os.path.join(direc,csv_fname), dtype={'timeID':np.int})
if len(tab) > 0:
# att_ind = np.argmin(np.abs(attfile['TIME'] - trigger_time))
# att_quat = attfile['QPARAM'][att_ind]
# ras = np.zeros(len(tab))
# decs = np.zeros(len(tab))
# for i in xrange(len(ras)):
# # print np.shape(res_tab['time'][i]), np.shape(attfile['TIME'])
# att_ind0 = np.argmin(np.abs(tab['time'][i] + tab['duration'][i]/2. - attfile['TIME']))
# att_quat0 = attfile['QPARAM'][att_ind0]
# ras[i], decs[i] = convert_imxy2radec(tab['imx'][i],\
# tab['imy'][i],\
# att_quat0)
t0_ = np.nanmean(tab['time'] + tab[dur_name]/2.)
att_ind0 = np.argmin(np.abs(t0_ - attfile['TIME']))
att_quat0 = attfile['QPARAM'][att_ind0]
try:
ras, decs = convert_imxy2radec(tab['imx'], tab['imy'], att_quat0)
except:
ras, decs = convert_theta_phi2radec(tab['theta'], tab['phi'], att_quat0)
tab['ra'] = ras
tab['dec'] = decs
if not perc_map is None:
Nside = hp.npix2nside(len(perc_map))
hp_inds = hp.ang2pix(Nside, ras, decs, lonlat=True, nest=True)
cred_lvl = perc_map[hp_inds]
tab['cls'] = cred_lvl
dfs.append(tab)
except Exception as E:
logging.warning(E)
continue
df = pd.concat(dfs, ignore_index=ignore_index)
return df
def mk_seed_tab4scans(res_tab, pc_fname, rate_seed_tab, TS_min=6.5, im_steps=20, pc_min=0.1):
PC = fits.open(pc_fname)[0]
pc = PC.data
w_t = WCS(PC.header, key='T')
pcbl = (pc>=(pc_min*.99))
pc_inds = np.where(pcbl)
pc_imxs, pc_imys = w_t.all_pix2world(pc_inds[1], pc_inds[0], 0)
imxax = np.linspace(-2,2,im_steps*4+1)
imyax = np.linspace(-1,1,im_steps*2+1)
im_step = imxax[1] - imxax[0]
bins = [imxax, imyax]
h = np.histogram2d(pc_imxs, pc_imys, bins=bins)[0]
inds = np.where(h>=10)
squareIDs_all = np.ravel_multi_index(inds, h.shape)
df_twinds = res_tab.groupby('timeID')
seed_tabs = []
for twind, dft in df_twinds:
if np.max(dft['TS']) >= TS_min:
seed_dict = {}
seed_dict['timeID'] = twind
seed_dict['dur'] = dft['duration'].values[0]
seed_dict['time'] = dft['time'].values[0]
bl_rate_seed = (rate_seed_tab['timeID']==twind)
squareIDs_done = rate_seed_tab['squareID'][bl_rate_seed]
squareIDs = squareIDs_all[~np.isin(squareIDs_all, squareIDs_done)]
seed_dict['squareID'] = squareIDs
seed_tabs.append(pd.DataFrame(seed_dict))
seed_tab = pd.concat(seed_tabs)
return seed_tab
def get_Nrank_val(vals, N):
if N >= len(vals):
return np.max(vals)
val_sort = np.sort(vals)
return val_sort[N-1]
def do_trng_overlap(tstart0, tend0, tstart1, tend1):
if tstart0 >= tstart1 and tstart0 < tend1:
return True
elif tstart0 < tend1 and tend0 >= tstart1:
return True
else:
return False
def mk_seed_tab(rates_res, TS_min=3.75, im_steps=20):
imxax = np.linspace(-2,2,im_steps*4+1)
imyax = np.linspace(-1,1,im_steps*2+1)
# imyg, imxg = np.meshgrid((imyax[1:]+imyax[:-1])/2., (imxax[1:]+imxax[:-1])/2.)
im_step = imxax[1] - imxax[0]
bins = [imxax, imyax]
df_twinds = rates_res.groupby('timeID')
seed_tabs = []
for twind, dft in df_twinds:
maxTS = np.nanmax(dft['TS'])
if maxTS >= TS_min:
TS_min2_ = min(maxTS-2.5, .8*maxTS)
TS_min2 = max(TS_min2_, np.nanmedian(dft['TS']), TS_min-.5)
seed_dict = {}
seed_dict['timeID'] = twind
seed_dict['dur'] = dft['dur'].values[0]
seed_dict['time'] = dft['time'].values[0]
pnts = np.vstack([dft['imx'],dft['imy']]).T
TSintp = interpolate.LinearNDInterpolator(pnts, dft['TS'])
imxax = np.linspace(-1.8, 1.8, 8*36+1)
imyax = np.linspace(-1.0, 1.0, 8*20+1)
xgrid, ygrid = np.meshgrid(imxax, imyax)
pnts = np.vstack([xgrid.ravel(),ygrid.ravel()]).T
TSgrid = TSintp(pnts)
bl = (TSgrid>=(TS_min2))
xs = xgrid.ravel()[bl]
ys = ygrid.ravel()[bl]
h = np.histogram2d(xs, ys, bins=bins)[0]
inds = np.where(h>0)
squareIDs = np.ravel_multi_index(inds, h.shape)
seed_dict['squareID'] = squareIDs
seed_tabs.append(pd.DataFrame(seed_dict))
seed_tab = pd.concat(seed_tabs)
return seed_tab
def get_hist2d_neib_inds(shape, indss, bins):
sqids = [] #np.empty(0,dtype=np.int)
imx0s = [] #np.empty(0)
imx1s = [] #np.empty(0)
imy0s = [] #np.empty(0)
imy1s = [] #np.empty(0)
for ii in range(len(indss[0])):
inds = (indss[0][ii],indss[1][ii])
for i in range(-1,2):
indx0 = inds[0] + i
indx1 = indx0 + 1
if indx0 < 0:
continue
if indx1 >= len(bins[0]):
continue
for j in range(-1,2):
indy0 = inds[1] + j
indy1 = indy0 + 1
if indy0 < 0:
continue
if indy1 >= len(bins[1]):
continue
sqids.append(np.ravel_multi_index([indx0,indy0], shape))
imx0s.append(bins[0][indx0])
imx1s.append(bins[0][indx1])
imy0s.append(bins[1][indy0])
imy1s.append(bins[1][indy1])
return sqids, imx0s, imx1s, imy0s, imy1s
def mk_in_seed_tab(rates_res, TS_min=4.5, im_steps=25, max_Ntwinds=8, max_overlaps=4, min_dlogl_cut=12.0):
imxax = np.linspace(-2,2,im_steps*4+1)
imyax = np.linspace(-1,1,im_steps*2+1)
# imyg, imxg = np.meshgrid((imyax[1:]+imyax[:-1])/2., (imxax[1:]+imxax[:-1])/2.)
im_step = imxax[1] - imxax[0]
bins = [imxax, imyax]
df_twinds = rates_res.groupby('timeID')
dur_bins = [0.0, 0.2, 0.5, 1.0, 2.0, 1e4]
ts_adj_facts = np.array([1.0, 1.05, 1.2, 1.3, 1.35])
dur_inds = np.digitize(rates_res['dur'], dur_bins)-1
ts_adj_fact = ts_adj_facts[dur_inds]
rates_res['TS2'] = rates_res['TS']*ts_adj_fact
idx = rates_res.groupby(['timeID'])['TS2'].transform(max) == rates_res['TS2']
rates_res_max_tab = rates_res[idx]
rates_max_sort = rates_res_max_tab.sort_values('TS2', ascending=False)
timeIDs = []
TS2s = []
dts0 = []
dts1 = []
Ntime_seeds = 0
for row_ind, row in rates_max_sort.iterrows():
dt0 = row['dt']
dt1 = dt0 + row['dur']
TS2 = row['TS2']
Noverlaps = 0
if TS2 >= 0.7*np.max(rates_max_sort['TS2']):
keep = True
else:
continue
for i in range(len(dts0)):
if do_trng_overlap(dts0[i], dts1[i], dt0, dt1):
Noverlaps += 1
if Noverlaps >= max_overlaps:
keep = False
break
if TS2 < 0.8*TS2s[i]:
keep = False
break
if keep:
timeIDs.append(row['timeID'])
dts0.append(dt0)
dts1.append(dt1)
TS2s.append(TS2)
Ntime_seeds += 1
if Ntime_seeds >= max_Ntwinds:
break
print Ntime_seeds
print timeIDs
print TS2s
seed_tabs = []
for twind, dft in df_twinds:
if not np.any(np.isclose(twind,timeIDs)):
continue
maxTS = np.nanmax(dft['TS'])
if maxTS >= TS_min:
print twind
logging.info("twind: %d"%(twind))
logging.info("maxTS: %.3f"%(maxTS))
bl = np.isfinite(dft['imx'])&(dft['TS']>1e-2)
df = dft[bl]
dlogls = np.max(np.square(df['TS'])) - np.square(df['TS'])
max_dlogl = np.max(dlogls)
med_dlogl = np.median(dlogls)
rank48_dlogl = get_Nrank_val(dlogls.values, 48)
rank196_dlogl = get_Nrank_val(dlogls.values, 196)
print "max, med dlogl: ", max_dlogl, med_dlogl
print "rank 48, 196 dlogl: ", rank48_dlogl, rank196_dlogl
# dlogl_cut at most the median
# at least dlogl of the 48th ranked pnt
# dlogl_cut at least 12
# TS at least TS_min-0.5
dlogl_cut = max(rank48_dlogl, min_dlogl_cut)
if len(dlogls) > 96:
dlogl_cut = min(dlogl_cut, med_dlogl)
dlogl_cut = min(dlogl_cut, rank196_dlogl)
print dlogl_cut
print np.sum(dlogls<=dlogl_cut), len(dlogls)
# TS_min2_ = min(maxTS-2.5, .8*maxTS)
# TS_min2 = max(TS_min2_, np.nanmedian(dft['TS']), TS_min-.5)
seed_dict = {}
seed_dict['timeID'] = twind
seed_dict['dur'] = dft['dur'].values[0]
seed_dict['time'] = dft['time'].values[0]
pnts = np.vstack([df['imx'],df['imy']]).T
# TSintp = interpolate.LinearNDInterpolator(pnts, dft['TS'])
try:
DLintp = interpolate.LinearNDInterpolator(pnts, np.sqrt(dlogls))
except Exception as E:
logging.warn("trouble with creating interp object for timeID %s"%(str(twind)))
logging.debug("shape(pnts): "+str(np.shape(pnts)))
logging.error(E)
logging.error(traceback.format_exc())
try:
logging.info("trying nearest interp")
DLintp = interpolate.NearestNDInterpolator(pnts, np.sqrt(dlogls))
except Exception as E:
logging.warn("trouble with creating interp object for timeID %s"%(str(twind)))
logging.warn("This failed too so skipping this timeID")
logging.error(E)
logging.error(traceback.format_exc())
continue
imxax = np.linspace(-1.8, 1.8, 20*36+1)
imyax = np.linspace(-1.0, 1.0, 20*20+1)
xgrid, ygrid = np.meshgrid(imxax, imyax)
pnts = np.vstack([xgrid.ravel(),ygrid.ravel()]).T
# TSgrid = TSintp(pnts)
try:
DLgrid = DLintp(pnts)**2
except Exception as E:
logging.warn("trouble calling the interp object so skipping timeID "+str(twind))
logging.error(E)
logging.error(traceback.format_exc())
continue
TSgrid = np.sqrt( np.max(np.square(df['TS'])) - DLgrid )
logging.debug("TSgrid min, max: %.3f, %.3f"\
%(np.nanmin(TSgrid),np.nanmax(TSgrid)))
# bl = (TSgrid>=(TS_min2))
bl = (DLgrid<=(dlogl_cut+0.5))&(TSgrid>=(TS_min-0.5))
xs = xgrid.ravel()[bl]
ys = ygrid.ravel()[bl]
h = np.histogram2d(xs, ys, bins=bins)[0]
inds = np.where(h>0)
seed_dict['squareID'],seed_dict['imx0'],seed_dict['imx1'],seed_dict['imy0'],seed_dict['imy1'] =\
get_hist2d_neib_inds(h.shape, inds, bins)
# squareIDs = np.ravel_multi_index(inds, h.shape)
# seed_dict['squareID'] = squareIDs
# seed_dict['imx0'] = bins[0][inds[0]]
# seed_dict['imx1'] = bins[0][inds[0]+1]
# seed_dict['imy0'] = bins[1][inds[1]]
# seed_dict['imy1'] = bins[1][inds[1]+1]
seed_tabs.append(pd.DataFrame(seed_dict))
if len(seed_tabs) < 1:
return []
seed_tab = pd.concat(seed_tabs)
seed_tab.drop_duplicates(inplace=True)
return seed_tab
def mk_in_seed_tab_archive(rates_res, twind_size, tbin_size=60.0, TS_min=4.5):
tbins0 = np.arange(-twind_size - 1.0, twind_size + 1.0, tbin_size)
tbins1 = tbins0 + tbin_size
Ntbins = len(tbins0)
seed_tabs = []
for i in range(Ntbins):
tbl = (rates_res['dt']>=tbins0[i])&(rates_res['dt']<tbins1[i])
df = mk_in_seed_tab(rates_res[tbl], TS_min=TS_min)
if len(df) > 0:
seed_tabs.append(df)
seed_tab = pd.concat(seed_tabs, ignore_index=True)
return seed_tab
def assign_in_seeds2jobs(seed_tab, Nmax_jobs=96):
SquareIDs, sqID_cnts = np.unique(seed_tab['squareID'], return_counts=True)
logging.debug("min, max sqID_cnts: %d, %d"%(np.min(sqID_cnts), np.max(sqID_cnts)))
Nsquares = len(SquareIDs)
logging.info("Nsquares: %d"%(Nsquares))
Ntbins = len(np.unique(seed_tab['timeID']))
logging.info("Ntbins: %d" %(Ntbins))
Ntot = len(seed_tab)
logging.info("Ntot Seeds: %d" %(Ntot))
Ntbins_perSq = float(Ntot) / Nsquares
logging.info("Tbins per Square: %.2f" %(Ntbins_perSq))
job_ids = np.zeros(Ntot, dtype=np.int) - 1
if Nsquares <= Nmax_jobs and Ntbins_perSq < 4:
Njobs = Nsquares
for i in range(Nsquares):
bl = (seed_tab['squareID']==SquareIDs[i])
job_ids[bl] = i
logging.debug("Njobs: %d"%(Njobs))
elif Nsquares <= Nmax_jobs/2 and Ntbins_perSq >= 6:
Njobs = 2*Nsquares
job_iter = 0
for i in range(Nsquares):
bl = (seed_tab['squareID']==SquareIDs[i])
Nt = np.sum(bl)
if Nt == 1:
job_ids[bl] = job_iter%Njobs
job_iter += 1
continue
job_ids[bl][:(Nt/2)] = job_iter%Njobs
job_iter += 1
job_ids[bl][(Nt/2):] = job_iter%Njobs
job_iter += 1
logging.debug("Njobs, job_iter: %d, %d"%(Njobs, job_iter))
elif Nsquares > Nmax_jobs:
Njobs = Nmax_jobs
job_iter = 0
for i in range(Nsquares):
bl = np.isclose(seed_tab['squareID'],SquareIDs[i])
Nt = np.sum(bl)
if Nt > (2*Ntbins_perSq):
inds_ = np.where(bl)[0]
job_ids[inds_[:(Nt/2)]] = job_iter%Njobs
job_iter += 1
job_ids[inds_[(Nt/2):]] = job_iter%Njobs
job_iter += 1
continue
job_ids[bl] = job_iter%Njobs
job_iter += 1
logging.debug("Njobs, job_iter: %d, %d"%(Njobs, job_iter))
else:
Njobs = min(Ntot, Nmax_jobs)
job_iter = 0
for i in range(Nsquares):
bl = (seed_tab['squareID']==SquareIDs[i])
Nt = np.sum(bl)
if Nt == 1:
job_ids[bl] = job_iter%Njobs
job_iter += 1
continue
job_ids[bl][:(Nt/2)] = job_iter%Njobs
job_iter += 1
job_ids[bl][(Nt/2):] = job_iter%Njobs
job_iter += 1
logging.debug("Njobs, job_iter: %d, %d"%(Njobs, job_iter))
logging.debug("sum(job_ids<0): %d"%(np.sum(job_ids<0)))
seed_tab['proc_group'] = job_ids
return seed_tab
def mk_out_seed_tab(in_seed_tab, hp_inds, att_q, Nside=2**4, Nmax_jobs=24):
tgrps = in_seed_tab.groupby('timeID')
Ntbins = len(tgrps)
Npix = len(hp_inds)
print "Npix: ", Npix
Njobs = min(Npix, Nmax_jobs)
print "Njobs: ", Njobs
timeIDs = []
t0s = []
durs = []
for timeID, df in tgrps:
timeIDs.append(timeID)
t0s.append(np.nanmean(df['time']))
durs.append(np.nanmean(df['dur']))
Nseeds = Npix*Ntbins
job_ids = np.zeros(Nseeds, dtype=np.int) - 1
times = np.zeros(Nseeds)
durss = np.zeros(Nseeds)
hpinds = np.zeros(Nseeds, dtype=np.int)
ras = np.zeros(Nseeds)
decs = np.zeros(Nseeds)
thetas = np.zeros(Nseeds)
phis = np.zeros(Nseeds)
timeIDss = np.empty(Nseeds, dtype=np.array(timeIDs).dtype)
job_iter = 0
for i in range(Npix):
hpind = hp_inds[i]
ra, dec = hp.pix2ang(Nside, hpind, nest=True, lonlat=True)
theta, phi = convert_radec2thetaphi(ra, dec, att_q)
jobid = job_iter%Njobs
job_iter += 1
for j in range(Ntbins):
ind = i*Ntbins + j
ras[ind] = ra
decs[ind] = dec
thetas[ind] = theta
phis[ind] = phi
hpinds[ind] = hpind
job_ids[ind] = jobid
times[ind] = t0s[j]
durss[ind] = durs[j]
timeIDss[ind] = timeIDs[j]
seed_dict = {'ra':ras, 'dec':decs, 'hp_ind':hpinds,
'theta':thetas, 'phi':phis, 'proc_group':job_ids,
'time':times, 'dur':durss, 'timeID':timeIDss}
out_seed_tab = pd.DataFrame(data=seed_dict)
return out_seed_tab
# def mk_seed_tab(rates_res, TS_min=3.5, im_steps=20):
#
# imxax = np.linspace(-2,2,im_steps*4+1)
# imyax = np.linspace(-1,1,im_steps*2+1)
# im_step = imxax[1] - imxax[0]
# bins = [imxax, imyax]
#
# df_twinds = rates_res.groupby('timeID')
# seed_tabs = []
# for twind, dft in df_twinds:
# if np.max(dft['TS']) >= TS_min:
# seed_dict = {}
# seed_dict['timeID'] = twind
# seed_dict['dur'] = dft['dur'].values[0]
# seed_dict['time'] = dft['time'].values[0]
#
# pnts = np.vstack([dft['imx'],dft['imy']]).T
# TSintp = interpolate.LinearNDInterpolator(pnts, dft['TS'])
# imxax = np.linspace(-1.5, 1.5, 8*30+1)
# imyax = np.linspace(-.85, .85, 8*17+1)
# xgrid, ygrid = np.meshgrid(imxax, imyax)
# pnts = np.vstack([xgrid.ravel(),ygrid.ravel()]).T
# TSgrid = TSintp(pnts)
# bl = (TSgrid>=(TS_min-.1))
# xs = xgrid.ravel()[bl]
# ys = ygrid.ravel()[bl]
#
# h = np.histogram2d(xs, ys, bins=bins)[0]
# inds = np.where(h>0)
# squareIDs = np.ravel_multi_index(inds, h.shape)
# seed_dict['squareID'] = squareIDs
# seed_tabs.append(pd.DataFrame(seed_dict))
#
# seed_tab = pd.concat(seed_tabs)
#
# return seed_tab
def mk_job_tab(seed_tab, Njobs, im_steps=20):
imxax = np.linspace(-2,2,im_steps*4+1)
imyax = np.linspace(-1,1,im_steps*2+1)
im_step = imxax[1] - imxax[0]
bins = [imxax, imyax]
squareIDs = np.unique(seed_tab['squareID'])
shp = (len(imxax)-1,len(imyax)-1)
data_dicts = []
for i, squareID in enumerate(squareIDs):
data_dict = {}
data_dict['proc_group'] = i%Njobs
indx, indy = np.unravel_index(squareID, shp)
data_dict['imx0'] = bins[0][indx]
data_dict['imx1'] = bins[0][indx+1]
data_dict['imy0'] = bins[1][indy]
data_dict['imy1'] = bins[1][indy+1]
data_dict['squareID'] = squareID
data_dicts.append(data_dict)
job_tab = pd.DataFrame(data_dicts)
return job_tab
def execute_ssh_cmd(client, cmd, server, retries=5):
tries = 0
while tries < retries:
try:
stdin, stdout, stderr = client.exec_command(cmd)
logging.info("stdout: ")
sto = stdout.read()
logging.info(sto)
return sto
except Exception as E:
logging.error(E)
logging.error(traceback.format_exc())
logging.error("Messed up with ")
logging.error(cmd)
client.close()
client = get_ssh_client(server)
tries += 1
logging.debug("retry %d of %d"%(tries,retries))
return
def get_ssh_client(server, retries=5):
tries = 0
try:
client = paramiko.SSHClient()
client.load_system_host_keys()
except Exception as E:
logging.error(E)
logging.error(traceback.format_exc())
return
while tries < retries:
try:
client.connect(server)
return client
except Exception as E:
logging.error(E)
logging.error(traceback.format_exc())
tries += 1
return
def sub_jobs(njobs, name, pyscript, pbs_fname, queue='open',\
workdir=None, qos=None, ssh=True, extra_args=None,\
ppn=1, rhel7=False):
hostname = socket.gethostname()
if len(name) > 15:
name = name[:15]
if 'aci.ics' in hostname and 'amon' not in hostname:
ssh=False
if ssh:
ssh_cmd = 'ssh aci-b.aci.ics.psu.edu "'
server = 'aci-b.aci.ics.psu.edu'
server = 'submit.aci.ics.psu.edu'
server = 'submit-001.aci.ics.psu.edu'
server = 'submit-010.aci.ics.psu.edu'
# client = paramiko.SSHClient()
# client.load_system_host_keys()
# client.connect(server)
client = get_ssh_client(server)
# base_sub_cmd = 'qsub %s -A %s -N %s -v '\
# %(args.pbs_fname, args.queue, args.name)
if qos is not None:
if rhel7:
base_sub_cmd = 'qsub %s -A %s -N %s -l nodes=1:ppn=%d -l qos=%s -l feature=rhel7 -v '\
%(pbs_fname, queue, name, ppn, qos)
else:
base_sub_cmd = 'qsub %s -A %s -N %s -l nodes=1:ppn=%d -l qos=%s -v '\
%(pbs_fname, queue, name, ppn, qos)
else:
if rhel7:
base_sub_cmd = 'qsub %s -A %s -N %s -l nodes=1:ppn=%d -l feature=rhel7 -v '\
%(pbs_fname, queue, name, ppn)
else:
base_sub_cmd = 'qsub %s -A %s -N %s -l nodes=1:ppn=%d -v '\
%(pbs_fname, queue, name, ppn)
else:
if qos is not None:
if rhel7:
base_sub_cmd = 'qsub %s -A %s -N %s -l nodes=1:ppn=%d -l qos=%s -l feature=rhel7 -v '\
%(pbs_fname, queue, name, ppn, qos)
else:
base_sub_cmd = 'qsub %s -A %s -N %s -l nodes=1:ppn=%d -l qos=%s -v '\
%(pbs_fname, queue, name, ppn, qos)
else:
if rhel7:
base_sub_cmd = 'qsub %s -A %s -N %s -l nodes=1:ppn=%d -l feature=rhel7 -v '\
%(pbs_fname, queue, name, ppn)
else:
base_sub_cmd = 'qsub %s -A %s -N %s -l nodes=1:ppn=%d -v '\
%(pbs_fname, queue, name, ppn)
if workdir is None:
workdir = os.getcwd()
if extra_args is None:
extra_args = ""
cmd = ''
jobids = []
for i in xrange(njobs):
# cmd_ = 'jobid=%d,workdir=%s,njobs=%d,pyscript=%s' %(i,workdir,njobs,pyscript)
cmd_ = 'jobid=%d,workdir=%s,njobs=%d,pyscript=%s,extra_args="%s"' %(i,workdir,njobs,pyscript,extra_args)
if ssh:
cmd += base_sub_cmd + cmd_
if i < (njobs-1):
cmd += ' | '
# cmd = base_sub_cmd + cmd_
# jbid = execute_ssh_cmd(client, cmd, server)
# jobids.append(jbid)
# try:
# stdin, stdout, stderr = client.exec_command(cmd)
# logging.info("stdout: ")
# sto = stdout.read()
# logging.info(sto)
# jobids.append(sto)
# except Exception as E:
# logging.error(E)
# logging.error(traceback.format_exc())
# logging.error("Messed up with ")
# logging.error(cmd)
else:
cmd = base_sub_cmd + cmd_
logging.info("Trying to submit: ")
logging.info(cmd)
try:
os.system(cmd)
# subprocess.check_call(cmd, shell=True)
except Exception as E:
logging.error(E)
logging.error("Messed up with ")
logging.error(cmd)
time.sleep(0.1)
if ssh:
# ssh_cmd = 'ssh aci-b.aci.ics.psu.edu "'
# cmd = ssh_cmd + cmd + '"'
logging.info("Full cmd to run:")
logging.info(cmd)
try:
jobids = execute_ssh_cmd(client, cmd, server)
# os.system(cmd)
# subprocess.check_call(cmd, shell=True)
# cmd_list = ['ssh', 'aci-b.aci.ics.psu.edu', '"'+cmd+'"']
# cmd_list = shlex.split(cmd)
# logging.info(cmd_list)
# subprocess.check_call(cmd_list)
except Exception as E:
logging.error(E)
logging.error("Messed up with ")
logging.error(cmd)
if ssh:
client.close()
return jobids
def find_peaks2scan(res_df, max_dv=10.0, min_sep=8e-3, max_Npeaks=48, min_Npeaks=2, minTS=6.0):
tgrps = res_df.groupby('timeID')
peak_dfs = []
for timeID, df_ in tgrps:
if np.nanmax(df_['TS']) < minTS:
continue
df = df_.sort_values('sig_nllh')
vals = df['sig_nllh']
# ind_sort = np.argsort(vals)
min_val = np.nanmin(df['sig_nllh'])
peak_dict = {'timeID': int(timeID), 'time':np.nanmean(df['time']),
'duration':np.nanmean(df['duration'])}
imxs_ = np.empty(0)
imys_ = np.empty_like(imxs_)
As_ = np.empty_like(imxs_)
Gs_ = np.empty_like(imxs_)
for row_ind, row in df.iterrows():
if row['sig_nllh'] > (min_val + max_dv) and len(imxs_) >= min_Npeaks:
break
if len(imxs_) >= max_Npeaks:
break
if len(imxs_) > 0:
imdist = np.min(im_dist(row['imx'], row['imy'], imxs_, imys_))
if imdist <= min_sep:
continue
imxs_ = np.append(imxs_, [row['imx']])
imys_ = np.append(imys_, [row['imy']])
As_ = np.append(As_, [row['A']])
Gs_ = np.append(Gs_, [row['ind']])
peak_dict['imx'] = imxs_
peak_dict['imy'] = imys_
peak_dict['Signal_A'] = As_
peak_dict['Signal_gamma'] = Gs_
peak_dfs.append(pd.DataFrame(peak_dict))
peaks_df = pd.concat(peak_dfs, ignore_index=True)
return peaks_df
def main(args):
fname = 'manager'
logging.basicConfig(filename=fname+'.log', level=logging.DEBUG,\
format='%(asctime)s-' '%(levelname)s- %(message)s')
f = open(fname+'.pid', 'w')
f.write(str(os.getpid()))
f.close()
logging.info("Wrote pid: %d" %(os.getpid()))
to = ['delauj2@gmail.com', 'aaron.tohu@gmail.com',
'g3raman@psu.edu', 'jak51@psu.edu']
subject = 'BATML ' + args.GWname
body = "Got data and starting analysis"
try:
send_email(subject, body, to)
except Exception as E:
logging.error(E)
logging.error("Trouble sending email")
t_0 = time.time()
has_sky_map = False
try:
sky_map_fnames = [fname for fname in os.listdir('.') if\
'cWB.fits.gz' in fname or 'bayestar' in fname\
or 'skymap' in fname]
sky_map = hp.read_map(sky_map_fnames[0], field=(0,), nest=True)
logging.info('Opened sky map')
perc_map = probm2perc(sky_map)