-
Notifications
You must be signed in to change notification settings - Fork 0
/
gwcat_mod.py
2413 lines (2294 loc) · 109 KB
/
gwcat_mod.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 json
import pandas as pd
import numpy as np
from astropy.time import Time
from astropy.io import fits
import healpy as hp
import h5py
import os
import requests
from . import gwcat_gwosc as gwosc
from . import gwcat_gracedb as gracedb
from . import plotloc
from astropy.table import Table
import astropy_healpix as ah
from pycbc.waveform import get_td_waveform
import ciecplib
# import gracedb
# import gwosc
def json2jsonp(fileIn,fileOut=None,verbose=False):
"""Read Json file and convert to Jsonp
Inputs:
* fileIn [string]: json filename
* fileOut [string, optional]: jsonp filename. Default = input with json->jsonp
* verbose [boolean, optional]: set to for verbose output. Default=False
Outputs:
* None
"""
if fileOut==None:
fileOut=fileIn.replace('json','jsonp')
if verbose:print('reading JSON from {}'.format(fileIn))
if verbose:print('writing JSONP to {}'.format(fileOut))
fIn=open(fileIn,'r')
fOut=open(fileOut,'w')
lines=fIn.readlines()
lines[0]='catdata('+lines[0]
lines[-1]=lines[-1]+');'
for l in lines:
fOut.write(l)
fOut.close()
return
def compareElement(el1,el2,verbose=False):
"""Convert event from pandas dataframe format to json-style object
Inputs:
* el1 [object]: element 1 to compare
* el1 [object]: element 2 to compare
* verbose [boolean, optional]: set to for verbose output. Default=False
Outputs:
* Boolean or None:
* True: Elements are the same
* False: Elements are not the same
* None: Elements can't be compared
"""
if type(el1)!=type(el2):
# types are different
if verbose: print('inconsistent types [{},{}]'.format(type(el1),type(el2)))
return(False)
elif type(el1)==dict and type(el2)==dict:
for el in el1:
if el in el2:
# if verbose: print('Comparing elements {}'.format(el))
return(compareElement(el1[el],el2[el],verbose=verbose))
else:
# if verbose: print('element {} not in dict 2'.format(el))
return(False)
for el in el2:
if el not in el1:
# if verbose: print('element {} not in dict 1'.format(el))
return(False)
else:
try:
# if verbose: print('Comparing elements {}'.format(el1))
if el1==el2:
# if verbose: print('{}=={}'.format(el1,el2))
return(True)
else:
# if verbose: print('{}!={}'.format(el1,el2))
return(False)
except:
print('ERROR: unable to compare [{} , {}] / [{},{}]'.format(el1,el2),type(el1),type(el2))
return()
return()
def dataframe2jsonEvent(evIn,params,verbose=False):
"""Convert event from pandas dataframe format to json-style object
Inputs:
* dataIn [object]:pandas-style event record
* params [dictionary]: units information (merge with datadict)
* verbose [boolean, optional]: set to for verbose output. Default=False
Outputs:
* Json-style event object:
"""
evOut={}
for p in range(len(params)):
param=params[p]
if verbose: print('Converting value {}'.format(param))
if param in evIn:
try:
pv=evIn[param+'_valtype']
except:
if verbose: print('ERROR: No valtype found for {}'.format(param))
pv=''
pass
try:
np.isnan(pv)
pass
except:
evOut[param]={}
if pv=='value':
evOut[param]['best']=evIn[param]
elif pv=='bestfit':
evOut[param]['best']=evIn[param]
try:
evOut[param]['err']=[evIn[param+'_errp'],evIn[param+'_errm']]
except:
if verbose: print('WARNING: no err found form {}'.format(param))
elif pv=='range':
try:
evOut[param]['lim']=[evIn[param+'_errp'],evIn[param+'_errm']]
except:
if verbose: print('WARNING: no lim found form {}'.format(param))
elif pv=='upper':
evOut[param]['upper']=evIn[param]
elif pv=='lower':
evOut[param]['lower']=evIn[param]
else:
if verbose: print('ERROR: unknown type for {} [{}]'.format(param,pv))
return(evOut)
def getManual(loc='',verbose=True,export=False,
dirOut=None,fileOut=None,indent=2):
"""Get data from manually constructed data-file
Inputs:
* loc [string, optional]: filename to load. Default='data/manual-events.json'
* verbose [boolean, optional]: set for verbose output. Default=False
* export [boolean, optional]: set to for export data to new file. Default=False
* dirOut [string, optional]: directory to export data to (if export=-True). Default=../../data/
* fileOut [string, optional]: file to export data to (if export=-True). Default=manual-events.json
* indent [integer, optional]: json indent in exported file (if export=True). Default=2
Outputs:
* Json-style object containing data in datafile
"""
if loc=='':
loc='data/manual-events.json'
if verbose: print('Retrieving Manual data from {}'.format(loc))
manread=json.load(open(loc,'r'))
mandata={'meta':{'retrieved':Time.now().isot,'src':loc}}
for s in manread:
mandata[s]=manread[s]
if verbose: print('Retrieved data for {} events'.format(len(mandata['data'])))
if export:
if dirOut==None:
dirOut='../../data/'
if fileOut==None:
fileOut='manual-events.json'
if verbose: print('Exporting to {}'.format(os.path.join(dirOut,fileOut)))
fOut=open(os.path.join(dirOut,fileOut),'w')
json.dump(mandata,fOut,indent=indent)
fOut.close()
return mandata
def setPrec(v,prec):
"""Set precision of variable
Inputs:
* v [float]: value to set precision of
* prec [integer]: precision to use
Outputs:
* [float]: value at set precision
"""
if prec:
precstr='{:.'+'{}'.format(prec)+'g}'
else:precstr='{}'
return float(precstr.format(v))
class GWCat(object):
"""Cataloge object containing useful methods for editing and accessing
"""
def __init__(self,fileIn='../data/events.json',statusFile='status.json',
dataDir='data/',baseurl='https://data.cardiffgravity.org/gwcat-data/',dataurl='https://ligo.gravity.cf.ac.uk/~chris.north/gwcat-data/',verbose=False,mode='public'):
"""Initialise catalogue from input file and set basic parameters
Inputs:
* fileIn [string, optional]: filename to load from. Default=../data/events.json
* statusFile [string, optional]: filename to use for data status. Default=status.json
* dataDir [string, optional]: Directory to store data in. Default=data/
* baseurl [string, optional]: URL to use for absolute URLs. Default=https://data.cardiffgravity.org/gwcat-data/
* dataurl [string, optional]: URL to use for absolute URLs for data files. Default='https://ligo.gravity.cf.ac.uk/~chris.north/gwcat-data/
* verbose [boolean, optional]: set for verbose output. Default=False
* mode [string, optional]: mode. Default=public
Outputs:
* None
"""
self.dataDir=dataDir
if not os.path.isdir(dataDir):
# make new directory
os.mkdir(dataDir)
if baseurl[-1]!='/':baseurl=baseurl+'/'
self.baseurl=baseurl
self.dataurl=dataurl
self.statusFile=os.path.join(dataDir,statusFile)
self.mode=mode
if mode=='dev':
self.devMode=True
self.sess=ciecplib.Session("LIGO")
else:
self.devMode=False
self.sess=None
self.getStatus()
eventsIn=json.load(open(fileIn))
self.data=eventsIn['data']
self.datadict=eventsIn['datadict']
self.cols=list(self.datadict.keys())
self.links=eventsIn['links']
self.evTimes = self.getTimestamps()
self.json2dataframe(verbose=verbose)
if 'meta' in eventsIn:
self.meta=eventsIn['meta']
self.meta['created']=Time.now().isot
else:
self.meta={'created':Time.now().isot}
return
def getEvent(self,ev):
"""Get event from database by event name
Inputs:
* ev [string]: event
Outputs:
* [object] json-style event object
* (None if no event not in database)
"""
if ev in self.data:
return(self.data[ev])
else:
return
def getParameter(self,ev,param):
"""Get parameter for event from database
Inputs:
* ev [string]: event name
* param [string]: parameter name
Outputs:
* [object] json-style parameter object
* (None if no event not in database)
"""
pOut=None
if ev in self.data:
if param in self.data[ev]:
pOut=self.data[ev][param]
return(pOut)
def getTimestamps(self):
"""Get timestamps of all events in database
Inputs:
* None
Outputs:
* [object] list of timestamps (of creation) in database, listed by event name
"""
evTimes={}
for ev in self.data:
try:
evTimes[ev]=Time(self.data[ev]['meta']['created_date'])
except:
# print('no created_date for {}'.format(ev))
pass
return(evTimes)
def getStatus(self):
"""Load status from status file (set by self.statusFile). Initialise file if not present. Store in self.status.
Inputs:
* None
Outputs:
* None
"""
try:
self.status=json.load(open(self.statusFile))
except:
print("Initialising status")
self.status={}
json.dump(self.status,open(self.statusFile,'w'))
return
def saveStatus(self):
"""Save status (in self.status) for status file (set by self.statusFile).
Inputs:
* None
Outputs:
* None
"""
json.dump(self.status,open(self.statusFile,'w'),indent=4)
return
def updateStatus(self,ev,desc='',statusIn=None,verbose=False):
"""Update status for event and save to status file
Inputs:
* ev [string]: event name
* desc [string, optional]: Description to use in verbose output
* statusIn [opject, optional]: status values to add for event. Default: load from metadata of event
* verbose [boolean, optional]: set for verbose output. Default=False
Outputs:
* None
"""
# check if it's in status
if type(ev)!=str:
print('ERROR: ev must be string object:',type(ev))
return
if statusIn==None:
# get status from event data
try:
event=self.getEvent(ev)
status=event['meta']
except:
print('ERROR: cannot find event {}'.format(ev))
return
elif type(statusIn)!=dict:
print('ERROR: status must be dict object:',type(status))
return
else:
if 'meta' in statusIn:
status=statusIn['meta']
else:
status=statusIn
if not ev in self.status:
self.status[ev]={}
for m in status:
self.status[ev][m]=status[m]
# if (event):
# if not ev in self.status:
# self.status[ev]={}
# if 'meta' in status:
# for m in event['meta']:
# self.status[ev][m]=event['meta'][m]
if desc!='':desctxt='[{}]'.format(desc)
if verbose:print('update status: {} {}'.format(ev,desctxt))
self.saveStatus()
return
def updateMapSrc(self,ev,verbose=False):
"""Update map source fits file and created date, and store in metadata. Load header and extract distance if possible. Called during importManual and importGraceDB.
Inputs:
* ev [string]: event name
* verbose [boolean, optional]: set for verbose output. Default=False
Outputs:
* None
"""
lmap=self.getLink(ev,'skymap-fits',verbose=verbose)
if len(lmap)>1 and verbose:
print('Warning: more than one skymap link for {}'.format(ev))
if len(lmap)==0 and verbose:
print('Warning: no skymap link for {}'.format(ev))
if len(lmap)>0:
l=lmap[0]
tmpDir=os.path.join(self.dataDir,'tmp')
try:
hdr=fits.getheader(l['url'],ext=1)
self.data[ev]['meta']['mapdatesrc']=hdr['DATE']
self.data[ev]['meta']['mapurlsrc']=l['url']
self.updateStatus(ev,verbose=verbose,desc='Map src')
if verbose:print('Skymap loaded for {}:'.format(ev),l['url'])
try:
distmu=hdr['DISTMEAN']
distsd=hdr['DISTSTD']
self.data[ev]['DL']={'best':distmu,'err':[-distsd,distsd]}
if verbose:print('obtained distance information for {} [{:.2f},{:.2f}]'.format(ev,distmu,distsd))
except:
if verbose:print('no distance information for {}'.format(ev))
except:
print('WARNING: Error loading skymap for {}:'.format(ev),l)
return
def importManual(self,manIn,verbose=False):
"""import Manual data into catalogue. Overwrites any existing data for events if they are already present
Inputs:
* manIn [object]: event data
* verbose [boolean, optional]: set for verbose output. Default=False
Outputs:
* None
"""
print('*** Importing Manual Data...')
for g in manIn['data']:
# get old metadata
dmeta={}
if g in self.data:
if 'meta' in self.data[g]:
dmeta=self.data[g]['meta']
self.data[g]=manIn['data'][g]
# update metadata
for m in manIn['data'][g]['meta']:
dmeta[m]=manIn['data'][g]['meta'][m]
self.data[g]['meta']=dmeta
if g in manIn['links']:
for l in manIn['links'][g]:
self.addLink(g,l,verbose=verbose)
self.updateStatus(g,verbose=verbose,desc='Manual import')
for ev in manIn['links']:
self.updateMapSrc(ev,verbose=True)
self.updateStatus(ev,verbose=verbose,desc='Map src')
self.evTimes = self.getTimestamps()
self.json2dataframe(verbose=verbose)
if not 'manuall' in self.meta:
self.meta['manual']={}
for m in manIn['meta']:
self.meta['manual'][m]=manIn['meta'][m]
return
def setPrecision(self,extraprec=3,verbose=False):
"""set precision for best, err, lower, upper for all events, based on precision in self.datadict
Inputs:
* extraprec [integer, optional]: additional precision to store. Default=3
* verbose [boolean, optional]: set for verbose output. Default=False
Outputs:
* None
"""
from numbers import Number
for ev in self.data:
for p in self.data[ev]:
newParam=self.getParameter(ev,p)
try:
assert(newParam)
assert p in self.datadict
assert 'sigfig' in self.datadict[p]
except:
# if verbose:print('unable to set precision for {}[{}]'.format(ev,p))
continue
sigfig=self.datadict[p]['sigfig']
if isinstance(newParam,Number) and not isinstance(newParam,bool):
newParam=self.setPrec(newParam,sigfig+extraprec)
else:
if 'best' in newParam:
if isinstance(newParam['best'],Number) and not isinstance(newParam['best'],bool):
newbest=setPrec(newParam['best'],sigfig+extraprec)
if verbose:
if self.getParameter(ev,p)['best']!=newbest:
print('Set precision {}[{}][best]: {}->{}'.format(ev,p,self.getParameter(ev,p)['best'],newbest))
newParam['best']=newbest
if 'err' in newParam:
if newbest!=0:
bprec=np.floor(np.log10(np.abs(newbest)))+1-(sigfig+extraprec)
else:
bprec=sigfig
mult=10**(-bprec)
newlow=np.round(newParam['err'][0]*mult)/mult
newhigh=np.round(newParam['err'][1]*mult)/mult
newerr=[newlow,newhigh]
# for e in range(len(newParam['err'])):
# newerr.append(setPrec(newParam['err'][e],sigfig))
if verbose:
if self.getParameter(ev,p)['err'][0]!=newlow or self.getParameter(ev,p)['err'][1]!=newhigh:
print('Set precision {}[{}][err]: {}->{}'.format(ev,p,self.getParameter(ev,p)['err'],newerr))
newParam['err']=newerr
if 'lower' in newParam:
newParam['lower']=setPrec(newParam['lower'],sigfig+extraprec)
if 'upper' in newParam:
newParam['upper']=setPrec(newParam['upper'],sigfig+extraprec)
self.data[ev][p]=newParam
return
def importGWTC(self,gwtcIn,verbose=False,devMode=False,forceOverwrite=False,catalog='GWTC'):
"""import GWTC data into catalogue. Uses gwosc.gwtc_to_cat to convert.
Updates H5 source file.
Convert to dataframe
Inputs:
* gwtcIn [object]: event data
* verbose [boolean, optional]: set for verbose output. Default=False
* devMode [boolean, optional]: set to fix DCC link for dev mode. Default=False.
* forceOverwrite [boolean, optional: set to force overwrite of events with earlier version numbers
* catalog [string, optional]: catalog to read from. Default=GWTC.
Outputs:
* None
"""
print('*** Importing GWTC Catalog...')
catData=gwosc.gwtc_to_cat(gwtcIn,self.datadict,verbose=verbose,devMode=self.devMode,catalog=catalog)
for ev in catData['data']:
# get old metadata
dmeta={}
if ev in self.data:
verEx=self.getParameter(ev,'version')
verNew=catData['data'][ev]['version']
if (verNew) and (verEx):
if (verNew <= verEx):
if forceOverwrite:
print('Forcing replacement of {} v{} with v{}'.format(ev,verEx,verNew))
else:
if verbose:
print('Not replacing {} v{} with v{}'.format(ev,verEx,verNew))
continue
else:
if verbose:
print('Updating {} v{} with v{}'.format(ev,verEx,verNew))
if 'meta' in self.data[ev]:
dmeta=self.data[ev]['meta']
self.data[ev]=catData['data'][ev]
# update metadata
for m in catData['data'][ev]['meta']:
dmeta[m]=catData['data'][ev]['meta'][m]
self.data[ev]['meta']=dmeta
if ev in catData['links']:
for l in catData['links'][ev]:
self.addLink(ev,l,verbose=verbose)
self.updateStatus(ev,verbose=verbose,desc='{} Catalog import'.format(catalog))
for ev in catData['links']:
self.updateH5Src(ev,verbose=verbose)
self.updateStatus(ev,verbose=verbose,desc='Data file src')
self.evTimes = self.getTimestamps()
self.json2dataframe(verbose=verbose)
if not catalog in self.meta:
self.meta[catalog]={}
for m in gwtcIn['meta']:
self.meta[catalog][m]=gwtcIn['meta'][m]
return
def matchGraceDB(self,verbose=False):
"""match confirmed events with GraceDB events (assuming <1s GPS timestamp difference)
Inputs:
* verbose [boolean, optional]: set for verbose output. Default=False
Outputs:
* None
"""
gdblist=[]
gpslist=[]
for ev in self.data:
name=self.data[ev]['name']
gps=self.getParameter(ev,'GPS')
if name[0]=='S':
try:
gps['best']
except:
continue
gdblist.append(name)
gpslist.append(gps['best'])
gpslist=np.array(gpslist)
gdblist=np.array(gdblist)
for ev in self.data:
if self.data[ev]['name'][0]=='S':
# is a gracedb event itself
continue
tgps=self.getParameter(ev,'GPS')
try:
tgps['best']
except:
continue
idx=np.where(np.abs(gpslist-tgps['best'])<1)[0]
if len(idx)>0:
matchname=gdblist[idx][0]
if verbose:
print('matching {} with {}'.format(ev,matchname))
self.data[ev]['meta']['gracedb']=matchname
# maplink=self.getLink(ev,'skymap-fits')
# mapgdb=self.getLink(matchname,'skymap-fits')
# if len(maplink)==0 and len(mapgdb)>0:
# if verbose:print('copying GraceDB map link from {} to {}: {}'.format(matchname,ev,mapgdb[0]))
# self.addLink(ev,mapgdb[0],verbose=verbose)
return
# backwards compatibility
def importGwosc(self,gwoscIn,verbose=False):
"""OBSOLETE - inpurt passed to importGWTC
Inputs:
* verbose [boolean, optional]: set for verbose output. Default=False
Outputs:
* None
"""
print('***WARNING: importGwosc replaced by importGWTC***')
self.importGWTC(gwoscIn,verbose=verbose)
def importGraceDB(self,gracedbIn,verbose=False,forceUpdate=False,highSigOnly=False):
"""import GraceDB data into catalogue. Uses gracedb.gracedb2cat to convert.
Remove retracted events.
Remove low-significant events
Update map source file.
Export to dataframe
Inputs:
* gracedbIn [object]: event data
* verbose [boolean, optional]: set for verbose output. Default=False
* forceUpdate [boolean, optional]: set to force updates of gracedb events. Default=False (only update new events)
* highSigOnly [boolean, optional]: set to remove low significance events. Default=False (include low significance events)
Outputs:
* None
"""
print('*** Importing GraceDB...')
evTimes=self.getTimestamps()
gdb=gracedb.gracedb2cat(gracedbIn['data'],verbose=verbose,
knownEvents=evTimes,forceUpdate=forceUpdate)
for g in gdb['data']:
if gdb['data'][g]['meta'].get('type')=='Retraction':
if verbose:print('Skipping retracted event {}'.format(g))
if g in self.data:
print('Removing data for retracted event {}'.format(g))
self.data.pop(g)
if g in self.links:
print('Removing links for retracted event {}'.format(g))
self.links.pop(g)
continue
if highSigOnly:
if gdb['data'][g].get('Significance')=='Low':
if g in self.data:
print('Removing data for low-significance event {}'.format(g))
self.data.pop(g)
if g in self.data:
print('Removing links for low-significance event {}'.format(g))
self.links.pop(g)
print('Skipping low-significance event {}'.format(g))
continue
# get old metadata
dmeta={}
if g in self.data:
if 'meta' in self.data[g]:
dmeta=self.data[g]['meta']
self.data[g]=gdb['data'][g]
# update metadata
for m in gdb['data'][g]['meta']:
dmeta[m]=gdb['data'][g]['meta'][m]
self.data[g]['meta']=dmeta
for l in gdb['links'][g]:
self.addLink(g,l,verbose=verbose)
self.updateStatus(g,verbose=verbose,desc='GraceDB import')
for ev in gdb['links']:
if gdb['data'][ev]['meta'].get('type')=='Retraction':
continue
self.updateMapSrc(ev,verbose=verbose)
self.updateStatus(ev,verbose=verbose,desc='Map src')
self.evTimes = self.getTimestamps()
self.json2dataframe(verbose=verbose)
if not 'graceDB' in self.meta:
self.meta['graceDB']={}
for m in gracedbIn['meta']:
self.meta['graceDB'][m]=gracedbIn['meta'][m]
return
def updateH5Src(self,ev,verbose=False):
"""Update H5 source fits file, and store in metadata. Called during importGWTC.
Inputs:
* ev [string]: event name
* verbose [boolean, optional]: set for verbose output. Default=False
Outputs:
* None
"""
ldat=self.getLink(ev,'data-file',verbose=verbose)
if len(ldat)>1 and verbose:
print('Warning: more than one data file link for {} [{}]'.format(ev,self.data[ev]['catalog']))
if len(ldat)==0 and verbose:
print('Warning: no data file link for {} [{}]'.format(ev,self.data[ev]['catalog']))
if len(ldat)>0:
l=ldat[0]
tmpDir=os.path.join(self.dataDir,'tmp')
try:
# self.data[ev]['meta']['h5datesrc']=Time.now().isot
self.data[ev]['meta']['h5urlsrc']=l['url']
if 'zenodo_version' in self.data[ev]['meta']:
stat={'h5zenodosrc':self.data[ev]['meta']['zenodo_version']}
self.updateStatus(ev,statusIn=stat,verbose=verbose,desc='H5 zenodo src')
if verbose:print('Data file loaded for {}:'.format(ev),l['url'])
except:
print('WARNING: Error loading data file for {}:'.format(ev),l)
def updateH5(self,verbose=False,forceUpdate=False,forceUpdateData=False,replace=False):
"""Check whether H5 files need updating and re-download if necessary (using getH5 or getH5Local).
Update parameters from H5 files.
Inputs:
* ev [string]: event name
* verbose [boolean, optional]: set for verbose output. Default=False
* replace [boolean, optional]: set to replace existing parameters with H5. Default=False
* forceUpdate [boolean, optional]: set to download all files. Default=False (only download updated files)
* forceUpdateData [boolean, optional]: set to force update of all data. Default=False (only download updated files)
Outputs:
* None
"""
# update h5 data files and parameters
print('*** Updating data files...')
for ev in self.data:
try:
if not ev in self.status:
self.status[ev]={}
# compare map creation dates and versions
if 'h5datelocal' in self.status[ev] and 'h5datesrc' in self.status[ev]:
h5datelocal=Time(self.status[ev]['h5datelocal']).gps
h5datesrc=Time(self.status[ev]['h5datesrc']).gps
else:
h5datelocal=-1
h5datesrc=-1
if 'h5verlocal' in self.status[ev] and 'h5versrc' in self.status[ev]:
h5verlocal=self.status[ev]['h5verlocal']
h5versrc=self.status[ev]['h5versrc']
else:
h5verlocal=-1
h5versrc=-1
if 'h5zenodolocal' in self.status[ev] and 'h5zenodosrc' in self.status[ev]:
h5zenodolocal=self.status[ev]['h5zenodolocal']
h5zenodosrc=self.status[ev]['h5zenodosrc']
else:
h5zenodolocal=-1
h5zenodosrc=-1
h5file=self.status[ev].get('h5urllocal','')
if not os.path.isfile(h5file):
if verbose:print('No file. Need to re-download data file for {}'.format(ev))
updateH5=True
elif h5zenodosrc>0 and h5zenodolocal>0:
if h5zenodosrc>h5zenodolocal:
if verbose:print('Newer zenodo version [{}>{}]. Need to re-download data file for {}'.format(h5zenodosrc,h5zenodolocal,ev))
updateH5=True
else:
if verbose:print('Older zenodo version file. Do not need to re-download data file for {}'.format(ev))
updateH5=False
elif h5versrc>0 and h5verlocal>0:
if h5versrc>h5verlocal:
if verbose:print('Newer version [{}>{}]. Need to re-download data filename for {}'.format(h5versrc,h5verlocal,ev))
updateH5=True
else:
if verbose:print('Older version file. Do not need to re-download data file for {}'.format(ev))
updateH5=False
elif h5datesrc>0 and h5datelocal>0:
if (h5datesrc-h5datelocal)>1:
if verbose:
print('Newer file. Need to re-download data file for {}'.format(ev))
print('src',Time(h5datesrc,format='gps').isot)
print('local',Time(h5datelocal,format='gps').isot)
updateH5=True
else:
if verbose:print('Older file. Do not need to re-download data file for {}'.format(ev))
updateH5=False
else:
if verbose:print('Unable to determine H5 file date/version for {}. Re-downloading'.format(ev))
updateH5=True
except:
if verbose:print('Error determining H5 file date/version for {}. Re-downloading'.format(ev))
updateH5=True
if updateH5 or forceUpdate:
if verbose:print('Updating data file for {}'.format(ev))
stat=self.getH5(ev,verbose=verbose)
if stat!=0:
self.getH5Local(ev,verbose=verbose)
else:
if verbose:print('No data file update required for {}'.format(ev))
# update data (if required)
updateH5data=False
try:
if 'h5datelocal' in self.status[ev] and 'h5dateloaded' in self.status[ev]:
h5datelocal=Time(self.status[ev]['h5datelocal']).gps
h5dateloaded=Time(self.status[ev]['h5dateloaded']).gps
else:
h5datelocal=-1
h5dateloaded=-1
if 'h5verlocal' in self.status[ev] and 'h5verloaded' in self.status[ev]:
h5verlocal=self.status[ev]['h5verlocal']
h5verloaded=self.status[ev]['h5verloaded']
else:
h5verlocal=-1
h5verloaded=-1
if h5datelocal>0 and h5dateloaded>0:
if (h5datelocal-h5dateloaded)>1:
if verbose:
print('File newer than data. Need to re-load data file for {}'.format(ev))
print('local',Time(h5datelocal,format='gps').isot)
print('loaded',Time(h5dateloaded,format='gps').isot)
updateH5data=True
else:
if verbose:
print('No need to update h5 data for {}'.format(ev))
updateH5data=False
elif h5verlocal>0 and h5verloaded>0:
if h5verlocal>h5verloaded:
if verbose:
print('File later version than data [{}>{}]. Need to re-load data file for {}'.format(ev))
updateH5data=True
else:
if verbose:
print('No need to update h5 data for {}'.format(ev))
updateH5data=False
else:
if verbose: print('Unable to determine H5 data date/version for {}. Re-loading'.format(ev))
updateH5data=True
except:
if verbose: print('Error determining H5 data date/version for {}. Re-loading'.format(ev))
updateH5data=True
if updateH5data or forceUpdateData:
try:
h5File=self.status[ev]['h5urllocal']
except:
if verbose:print('no local data file for {}'.format(ev))
continue
if 'approximant' in self.data[ev]:
approx=self.data[ev]['approximant']
if verbose:
print('approximant found for {}: {}'.format(ev,self.data[ev]['approximant']))
else:
approx=None
if verbose:
print('no approximant found for {}'.format(ev))
newparams=self.getH5Params(ev,approx=approx,verbose=verbose)
if (newparams):
for p in newparams:
if (p in self.data[ev]):
if replace:
self.data[ev][p]=newparams[p]
if verbose:
print('replacing {}[{}]:{}->{}'.format(ev,p,self.data[ev][p],newparams[p]))
else:
if verbose:
print('NOT replacing {}[{}]:{}->{}'.format(ev,p,self.data[ev][p],newparams[p]))
else:
self.data[ev][p]=newparams[p]
print('adding {}[{}]:{}'.format(ev,p,newparams[p]))
stat={'h5dateloaded':Time.now().isot,
'h5verloaded':self.data[ev]["version"]}
if 'approximant' in newparams:
stat['approximant']=newparams['approximant']
self.updateStatus(ev,statusIn=stat,verbose=verbose,desc='h5 data loaded')
else:
if verbose: print('no parameters from H5 for {}'.format(ev))
else:
if verbose:print('No H5 data update required for {}'.format(ev))
return
def getH5(self,ev,verbose=False):
"""Download h5 files and update status with filenames, timestamps.
Call extractTar if tarfile.
Check file is valid H5 file.
Inputs:
* ev [string]: event name
* verbose [boolean, optional]: set for verbose output. Default=False
Outputs:
* [object] dict containing extracted "h5" and "map" file locations.
"""
# download and import remote h5 file into database
import h5py
h5Dir=os.path.join(self.dataDir,'h5')
if not os.path.exists(h5Dir):
# create directory
os.mkdir(h5Dir)
print('Created directory: {}'.format(h5Dir))
ldat=self.getLink(ev,'data-file')
if len(ldat)==0:
if verbose: print('ERROR: no data file link for {}'.format(ev))
return
if len(ldat)>1:
if verbose: print('WARNING: more than one data file link for {}'.format(ev))
url=ldat[0]['url']
if verbose: print('Downloading data file for {} from {}'.format(ev,url))
if url.find("zenodo")>=0 and url.find("content")>=0:
try:
# New Zenodo format file
zenurl=url.replace("/content","")
srcfile=os.path.split(zenurl)[-1]
if verbose: print('Zenodo src file:',zenurl,os.path.split(zenurl),srcfile)
except:
srcfile=os.path.split(url)[-1]
else:
srcfile=os.path.split(url)[-1]
if self.devMode:
h5req=self.sess.get(url)
else:
h5req=requests.get(url)
if h5req.ok:
try:
# if url.find('.fits.gz')>=0:
# fileext='fits.gz'
# else:
# fileext='fits'
if srcfile.find(ev)<0:
h5File=os.path.join(h5Dir,'{}_{}'.format(ev,srcfile))
if h5File.find('.h')<0:
h5File=h5File+'.h5'
else:
h5File=os.path.join(h5Dir,srcfile)
fOut=open(h5File,'wb')
fOut.write(h5req.content)
fOut.close()
if verbose:print('Data file downloaded')
except:
print('ERROR: Problem loading/saving data file:',h5req.status_code)
return h5req
if ldat[0]['filetype']=='tar':
print('NEED TO EXTRACT TARBALL')
stat={'tarurllocal':h5File,
'tarurlsrc':url,
'tardatelocal':Time.now().isot,
'tardatesrc':Time(os.path.getmtime(h5File),format='unix').isot,
'tarverlocal':self.data[ev]["version"],
'tarversrc':self.data[ev]["version"]}
self.updateStatus(ev,statusIn=stat,verbose=verbose,desc='tar file local')
tarout=self.extractTar(ev,verbose=verbose)
h5File=tarout['h5']
try:
testread=h5py.File(h5File)
if verbose: print('Valid h5 file for {}: {}'.format(ev,h5File))
# hdr=fits.getheader(fitsFile,ext=1)
stat={'h5urllocal':h5File,
'h5datelocal':Time.now().isot,
'h5datesrc':Time(os.path.getmtime(h5File),format='unix').isot,
'h5verlocal':self.data[ev]["version"],
'h5versrc':self.data[ev]["version"]}
if 'zenodo_version' in self.data[ev]['meta']:
stat['h5zenodolocal']=self.data[ev]['meta']['zenodo_version']
stat['h5zenodosrc']=self.data[ev]['meta']['zenodo_version']
self.data[ev]['meta']['h5urllocal']=h5File
self.data[ev]['meta']['h5datelocal']=Time.now().isot
self.data[ev]['meta']['h5datesrc']=Time.now().isot
self.updateStatus(ev,statusIn=stat,verbose=verbose,desc='data file local')
except:
print('ERROR: Problem opening data file for {}:'.format(ev),h5File)
return(-1)
# self.calcAreas(ev,verbose=verbose)
else:
print('ERROR: Problem loading h5 file:',h5req.status_code)
return h5req.status_code
return(0)
def extractTar(self,ev,statusid='tarurllocal',maponly=False,verbose=False):
"""Extract h5 and map file from tarfile
Inputs:
* ev [string]: event name
* statusid [string, optional]: id in status file to identify tar file
* maponly [boolean, optional]: set to only extract the map file. Default=False
* verbose [boolean, optional]: set for verbose output. Default=False
Outputs:
* [number] HTTP status code if unsuccessful. 0 if not.
"""
import tarfile
tarFile=self.status[ev][statusid]
tarF=tarfile.open(tarFile)
tarNames=tarF.getnames()
# get first file with _comoving.h5 - for GWTC-2
h5name=[n for n in tarNames if '_comoving.h5' in n]
# h5name=[n for n in tarNames if '.h5' in n]
if len(h5name)>0:
h5name=h5name[0]
mapname=[]
for n in tarNames:
# GWTC-2 filename
if n.find('PublicationSamples.fits')>=0:
# for GWTC-2
mapname.append(n)
# GWTC-2.1 filename
if 'approximant' in self.status[ev]:
if n.find(ev)>=0 and n.find(self.status[ev]['approximant'])>=0:
mapname.append(n)
# GWTC-3 filename
if n.find(ev)>=0 and n.find('Mixed.fits')>=0:
mapname.append(n)
# catch for GWTC-3 zenodo filename error
if n.find(ev.replace('GW200210_092254','GW200210_092255'))>=0 and n.find('Mixed.fits')>=0:
mapname.append(n)
# else:
# mapname=[n for n in tarNames if 'PublicationSamples.fits' in n]
if verbose:print('map for {}:{}'.format(ev,mapname))
out={'h5':'','map':''}
# extract h5 to h5 directory tarfile
if not maponly:
h5Dir=os.path.join(self.dataDir,'h5')
try:
tarF.extract(h5name,path=h5Dir)
h5File=os.path.join(h5Dir,h5name)
if (verbose): print('Extracted h5 file to {}'.format(h5File))
# save location of h5 file to status
stat={'h5urllocal':h5File,
'h5datelocal':Time.now().isot,
'h5verlocal':self.data[ev]["version"],
'h5versrc':self.data[ev]["version"],
'h5urlsrc':self.status[ev]["tarurlsrc"]}
self.updateStatus(ev,statusIn=stat,verbose=verbose,desc='h5 file local')
out['h5']=h5File
except:
pass
# extract fits to fits directory
if len(mapname)>0:
fitsDir=os.path.join(self.dataDir,'fits')
if not os.path.exists(fitsDir):
# create directory
os.mkdir(fitsDir)
print('Created directory: {}'.format(fitsDir))
try:
tarF.extract(mapname[0],path=fitsDir)
mapFile=os.path.join(fitsDir,mapname[0])
if (verbose): print('Extracted Map to {}'.format(mapFile))
# save location of map to status
# save location of h5 file to status
stat={'mapurllocal':mapFile,
'mapdatelocal':Time.now().isot,
'mapdatesrc':Time(os.path.getmtime(mapFile),format='unix').isot,
'mapverlocal':self.data[ev]["version"],
'mapversrc':self.data[ev]["version"]}
if 'maptarurlsrc' in self.status[ev]:
stat['mapurlsrc']=self.status[ev]['maptarurlsrc']
elif 'tarurlsrc' in self.status[ev]:
stat['mapurlsrc']=self.status[ev]['tarurlsrc']
self.updateStatus(ev,statusIn=stat,verbose=verbose,desc='map file local')
out['map']=mapFile