-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbnslib.py
2140 lines (1900 loc) · 77.2 KB
/
bnslib.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 numpy as np
from queue import Queue
import multiprocessing as mp
import datetime
import sys
import time
import warnings
from functools import wraps
from collections import OrderedDict
import os
from pycbc.detector import Detector
from pycbc.sensitivity import volume_montecarlo
from pycbc.waveform import get_td_waveform, get_fd_waveform
from pycbc.types import TimeSeries, FrequencySeries, load_frequencyseries
from pycbc.noise import noise_from_string
from pycbc.psd import interpolate, inverse_spectrum_truncation
from pycbc.psd import from_numpy_arrays, from_string
from pycbc.psd import aLIGOZeroDetHighPower as aPSD
from pycbc.filter import sigma
def optimal_snr(signal, psd='aLIGOZeroDetHighPower',
low_freq_cutoff=None, high_freq_cutoff=None):
"""Calculate the optimal signal-to-noise ratio for a given signal.
Arguments
---------
signal : pycbc.TimeSeries or pycbc.FrequencySeries
The signal of which to calculate the signal-to-noise ratio.
psd : {str or None or pycbc.FrequencySeries, 'aLIGOZeroDetHighPower}
A power spectral density to use for the noise-model. If set to a
string, a power spectrum will be generated using
pycbc.psd.from_string. If set to None, no noise will be assumed.
If a frequency series is given, the user has to make sure that
the delta_f and length match the signal.
low_freq_cutoff : {float or None, None}
The lowest frequency to consider. If a value is given, the power
spectrum will be generated with a lower frequency cutoff 2 below
the given one. (0 at minimum)
high_freq_cutoff : {float or None, None}
The highest frequency to consider.
Returns
-------
float
The optimal signal-to-noise ratio given the signal and the noise
curve (power spectrum).
"""
if psd is not None:
if isinstance(psd, str):
df = signal.delta_f
if isinstance(signal, TimeSeries):
flen = len(signal) // 2 + 1
elif isinstance(signal, FrequencySeries):
flen = len(signal)
psd_low = 0. if low_freq_cutoff is None else max(low_freq_cutoff - 2., 0.)
psd = from_string(psd, length=flen, delta_f=df,
low_freq_cutoff=psd_low)
return sigma(signal, psd=psd, low_frequency_cutoff=low_freq_cutoff,
high_frequency_cutoff=high_freq_cutoff)
def whiten(strain_list, low_freq_cutoff=20., max_filter_duration=4.,
psd=None):
"""Returns the data whitened by the PSD.
Arguments
---------
strain_list : pycbc.TimeSeries or list of pycbc.TimeSeries
The data that should be whitened.
low_freq_cutoff : {float, 20.}
The lowest frequency that is considered during calculations. It
must be >= than the lowest frequency where the PSD is not zero.
Unit: hertz
max_filter_duration : {float, 4.}
The duration to which the PSD is truncated to in the
time-domain. The amount of time is removed from both the
beginning and end of the input data to avoid wrap-around errors.
Unit: seconds
psd : {None or str or pycbc.FrequencySeries, None}
The PSD that should be used to whiten the data. If set to None
the pycbc.psd.aLIGOZeroDetHighPower PSD will be used. If a PSD
is provided which does not fit the delta_f of the data, it will
be interpolated to fit. If a string is provided, it will be
assumed to be known to PyCBC.
Returns
-------
pycbc.TimeSeries or list of pycbc.TimeSeries
Depending on the input type it will return a list of TimeSeries
or a single TimeSeries. The data contained in this time series
is the whitened input data, where the inital and final seconds
as specified by max_filter_duration are removed.
"""
org_type = type(strain_list)
if not org_type == list:
strain_list = [strain_list]
ret = []
for strain in strain_list:
df = strain.delta_f
f_len = int(len(strain) / 2) + 1
if psd is None:
psd = aPSD(length=f_len,
delta_f=df,
low_freq_cutoff=low_freq_cutoff-2.)
elif isinstance(psd, str):
psd = from_string(psd,
length=f_len,
delta_f=df,
low_freq_cutoff=low_freq_cutoff-2.)
else:
if not len(psd) == f_len:
msg = 'Length of PSD does not match data.'
raise ValueError(msg)
elif not psd.delta_f == df:
psd = interpolate(psd, df)
max_filter_len = int(max_filter_duration * strain.sample_rate) #Cut out the beginning and end
psd = inverse_spectrum_truncation(psd,
max_filter_len=max_filter_len,
low_frequency_cutoff=low_freq_cutoff,
trunc_method='hann')
f_strain = strain.to_frequencyseries()
kmin = int(low_freq_cutoff / df)
f_strain.data[:kmin] = 0
f_strain.data[-1] = 0
f_strain.data[kmin:] /= psd[kmin:] ** 0.5
strain = f_strain.to_timeseries()
ret.append(strain[max_filter_len:len(strain)-max_filter_len])
if not org_type == list:
return(ret[0])
else:
return(ret)
def list_length(inp):
"""Returns the length of a list or 1, if the input is not a list.
Arguments
---------
inp : list or other
The input.
Returns
-------
int
The length of the input, if the input is a list. Otherwise
returns 1.
Notes
-----
-A usecase for this function is to homologize function inputs. If
the function is meant to operate on lists but can also accept a
single instance, this function will give the length of the list the
function needs to create. (Useful in combination with the function
input_to_list)
"""
if isinstance(inp, list):
return len(inp)
else:
return 1
def input_to_list(inp, length=None):
"""Convert the input to a list of a given length.
If the input is not a list, a list of the given length will be
created. The contents of this list are all the same input value.
Arguments
---------
inp : list or other
The input that should be turned into a list.
length : {int or None, None}
The length of the output list. If set to None this function will
call list_length to determine the length of the list.
Returns
-------
list
Either returns the input, when the input is a list of matching
length or a list of the wanted length filled with the input.
"""
if length is None:
length = list_length(inp)
if isinstance(inp, list):
if len(inp) != length:
msg = f'Length of list {len(inp)} does not match the length'
msg += f' requirement {length}.'
raise ValueError(msg)
else:
return inp
else:
return [inp] * length
SECONDS_PER_MONTH = 60 * 60 * 24 * 30
def get_trigger_times(ts, thresh):
"""Generates an array of times that exceed the given threshold.
Arguments
---------
ts : pycbc.TimeSeries
The time series to which a threshold should be applied.
thresh : float
The threshold value
Returns
-------
numpy.array:
An array of sample times, where the threshold is exceeded.
"""
idxs = np.where(ts > thresh)[0]
if len(idxs) == 0:
return np.array([])
else:
return np.array(ts.sample_times[idxs])
def get_triggers(ts, thresh):
"""Generates an array of times that exceed the given threshold.
Arguments
---------
ts : pycbc.TimeSeries
The time series to which a threshold should be applied.
thresh : float
The threshold value
Returns
-------
numpy.array:
A 2D array. The row with index 0 contains the sample times where
the threshold was exceeded, the row with index 1 contains the
according values.
"""
idxs = np.where(ts > thresh)[0]
if len(idxs) == 0:
return np.array([[], []])
else:
ret = np.zeros((2, len(idxs)))
ret[0] = np.array(ts.sample_times[idxs])
ret[1] = np.array(ts.data[idxs])
return ret
def get_cluster_boundaries(triggers, boundarie_time=1.):
"""A basic clustering algorithm that generates a list start and end
times for every cluster.
Arguments
---------
triggers : iterable of floats or 2D array
A list or array containing the times of a time series that
exceed a given threshold. (As returned by get_trigger_times or
get_triggers)
boundarie_time : {float, 1.}
A time in seconds around the cluster boundaries that may not
contain any triggers for the cluster to be complete.
Returns
-------
list of list of float:
Returns a list that contains the boundarie times of all
clusters. As such each entry is a list of length 2. The first
of which is the inital time of the cluster, the second is the
final time of the cluster.
Note
----
This is a very basic clustering algorithm that simply expands the
boundaries of all clusters until there are no triggers within an
accepted range.
"""
if np.ndim(triggers) == 1:
trigger_times = triggers
elif np.ndim(triggers) == 2:
trigger_times = triggers[0]
else:
raise RuntimeError
i = 0
clusters = []
current_cluster = []
while i < len(trigger_times):
if len(current_cluster) == 0:
current_cluster.append(trigger_times[i])
elif len(current_cluster) == 1:
if trigger_times[i] - current_cluster[0] < boundarie_time:
current_cluster.append(trigger_times[i])
else:
current_cluster.append(current_cluster[0])
clusters.append(current_cluster)
current_cluster = [trigger_times[i]]
elif len(current_cluster) == 2:
if trigger_times[i] - current_cluster[1] < boundarie_time:
current_cluster[1] = trigger_times[i]
else:
clusters.append(current_cluster)
current_cluster = [trigger_times[i]]
i += 1
if len(current_cluster) == 2:
clusters.append(current_cluster)
elif len(current_cluster) == 1:
clusters.append([current_cluster[0], current_cluster[0]])
return clusters
def get_event_list(ts, cluster_boundaries):
"""Turns a list of clusters into events.
Arguments
---------
ts : pycbc.TimeSeries
The time series the clusters are derived from.
cluster_boundaries : list of list of float
A list of cluster boundaries as returned by
get_cluster_boundaries.
Returns
-------
list of tuples of float:
Returns a list of events. A event is a tuple of size two. The
first entry is the time of the event, the second is the value
of the time series at the corresponding event.
Notes
-----
-Each event corresponds to a cluster. The algorithm takes the
time and value of the maximum of the time series within each
cluster as event.
"""
events = []
samp_times = np.array(ts.sample_times)
for cstart, cend in cluster_boundaries:
start_idx = int(float(cstart - ts.start_time) / ts.delta_t)
end_idx = int(float(cend - ts.start_time) / ts.delta_t)
idx = start_idx + np.argmax(ts[start_idx:end_idx+1])
events.append((samp_times[idx], ts[idx]))
return events
def get_event_list_from_triggers(triggers, cluster_boundaries):
events = []
sort_idxs = np.argsort(triggers[0])
sorted_triggers = (triggers.T[sort_idxs]).T
for cstart, cend in cluster_boundaries:
sidx = np.searchsorted(sorted_triggers[0], cstart, side='left')
eidx = np.searchsorted(sorted_triggers[0], cend, side='right')
if sidx == eidx:
continue
idx = sidx + np.argmax(sorted_triggers[1][sidx:eidx])
events.append((sorted_triggers[0][idx], sorted_triggers[1][idx]))
return events
def events_above_threshold(event_list, thresh):
"""Filter events by a threshold on their value.
Arguments
---------
event_list : list of tuples of float
A list of events as returned by get_event_list.
thresh : float
A threshold value to filter events.
Returns
-------
list of tuples of float
A list of events that exceed the given threshold.
"""
ret = []
for event in event_list:
if event[1] > thresh:
ret.append(event)
return ret
def get_false_positives(event_list, injection_times, tolerance=3.):
"""Find a list of falsely identified events.
Arguments
---------
event_list : list of tuple of float
A list of events as returned by get_event_list.
injection_times : numpy.array of floats
An array containing the times at which a signal was actually
present in the data.
tolerance : {float, 3.}
The maximum time in seconds an injection time may be away from
an event time to be counted as a true positive.
Returns
-------
list of tuples of float
A list of events that were falsely identified as events.
"""
ret = []
for event in event_list:
if np.min(np.abs(injection_times - event[0])) > tolerance:
ret.append(event)
return ret
def get_true_positives(event_list, injection_times, tolerance=3.):
"""Find a list of correctly identified events.
Arguments
---------
event_list : list of tuple of float
A list of events as returned by get_event_list.
injection_times : numpy.array of floats
An array containing the times at which a signal was actually
present in the data.
tolerance : {float, 3.}
The maximum time in seconds an injection time may be away from
an event time to be counted as a true positive.
Returns
-------
list of tuples of float
A list of events that were correctly identified as events.
"""
ret = []
for event in event_list:
if np.min(np.abs(injection_times - event[0])) <= tolerance:
ret.append(event)
return ret
def split_true_and_false_positives(event_list, injection_times,
tolerance=3., assume_sorted=False,
workers=0):
"""Find a list of correctly identified events.
Arguments
---------
event_list : list of tuple of float
A list of events as returned by get_event_list.
injection_times : numpy.array of floats
An array containing the times at which a signal was actually
present in the data.
tolerance : {float, 3.}
The maximum time in seconds an injection time may be away from
an event time to be counted as a true positive.
assume_sorted : {bool, False}
Assume that the injection_times are sorted in an ascending
order. (If this is false the injection times are sorted
internally)
workers : {int or None, 0}
How many processes to use to split the events. If set to 0, the
events are analyzed sequentially. If set to None spawns as many
processes as there are CPUs available.
Returns
-------
true_positives : list of tuples of float
A list of events that were correctly identified as events.
false_positives : list of tuples of float
A list of events that were falsely identified as events.
"""
if assume_sorted:
injtimes = injection_times
else:
injtimes = injection_times.copy()
injtimes.sort()
def worker(sub_event_list, itimes, tol, output, wid):
tp = []
fp = []
for event in sub_event_list:
t, v = event
idx = np.searchsorted(itimes, t, side='right')
if idx == 0:
diff = abs(t - itimes[0])
elif idx == len(itimes):
diff = abs(t - itimes[-1])
else:
diff = min(abs(t - itimes[idx-1]), abs(t - itimes[idx]))
if diff <= tol:
tp.append(event)
else:
fp.append(event)
output.put((wid, tp, fp))
if workers == 0:
queue = Queue()
worker(event_list, injtimes, tolerance, queue, 0)
_, tp, fp = queue.get()
return tp, fp
else:
if workers is None:
workers = mp.cpu_count()
idxsrange = int(len(event_list) // workers)
overhang = len(event_list) - workers * idxsrange
prev = 0
queue = mp.Queue()
jobs = []
for i in range(workers):
if i < overhang:
end = prev + idxsrange + 1
else:
end = prev + idxsrange
p = mp.Process(target=worker,
args=(event_list[prev:end],
injtimes,
tolerance,
queue,
i))
prev = end
jobs.append(p)
for p in jobs:
p.start()
results = [queue.get() for p in jobs]
for p in jobs:
p.join()
results = sorted(results, key=lambda inp: inp[0])
tp = []
fp = []
for res in results:
tp.extend(res[1])
fp.extend(res[2])
return tp, fp
def get_event_times(event_list):
"""Extract the event times from a list of events.
Arguments
---------
event_list : list of tuples of float
A list of events as returned by get_event_list.
Returns
-------
list of float
A list containing the times of the events given by the
event_list.
"""
return [event[0] for event in event_list]
def get_closest_injection_times(injection_times, times,
return_indices=False,
assume_sorted=False):
"""Return a list of the closest injection times to a list of input
times.
Arguments
---------
injection_times : numpy.array of floats
An array containing the times at which a signal was actually
present in the data.
times : iterable of floats
A list of times. The function checks which injection time was
closest to every single one of these times.
return_indices : {bool, False}
Return the indices of the found injection times.
assume_sorted : {bool, False}
Assume that the injection times are sorted in ascending order.
(If set to false, the injection times are sorted internally)
Returns
-------
numpy.array of float:
Returns an array containing the injection times that were
closest to the provided times. The order is given by the order
of the input times.
numpy.array of int, optional:
Return an array of the corresponding indices. (Only returned if
return_indices is true)
"""
if assume_sorted:
injtimes = injection_times
sidxs = np.arange(len(injtimes))
else:
sidxs = injection_times.argsort()
injtimes = injection_times[sidxs]
ret = []
idxs = []
for t in times:
idx = np.searchsorted(injtimes, t, side='right')
if idx == 0:
ret.append(injtimes[idx])
idxs.append(sidxs[idx])
elif idx == len(injtimes):
ret.append(injtimes[idx-1])
idxs.append(sidxs[idx-1])
else:
if abs(t - injtimes[idx-1]) < abs(t - injtimes[idx]):
idx -= 1
ret.append(injtimes[idx])
idxs.append(sidxs[idx])
if return_indices:
return np.array(ret), np.array(idxs, dtype=int)
else:
return np.array(ret)
def get_missed_injection_times(event_list, injection_times,
tolerance=3., return_indices=False):
"""Find the injection times that are not present in a provided list
of events.
Arguments
---------
event_list : list of tuples of float
A list of events as returned by get_event_list.
injection_times : numpy.array of floats
An array containing the times at which a signal was actually
present in the data.
tolerance : {float, 3.}
The maximum time in seconds an injection time may be away from
an event time to be counted as a true positive.
return_indices : {bool, False}
Return the indices of the missed injection times.
Returns
-------
numpy.array of floats:
Returns an array containing injection times that were not
contained in the list of events, considering the tolerance.
numpy.array of int, optional:
Return an array of the corresponding indices. (Only returned if
return_indices is true)
"""
ret = []
idxs = []
event_times = np.array(get_event_times(event_list))
if len(event_times) == 0:
return injection_times
for idx, inj_time in enumerate(injection_times):
if np.min(np.abs(event_times - inj_time)) > tolerance:
ret.append(inj_time)
idxs.append(idx)
if return_indices:
return np.array(ret), np.array(idxs, dtype=int)
else:
return np.array(ret)
def false_alarm_rate(ts, injection_times, trigger_thresh=0.2,
ranking_thresh=0.5, cluster_tolerance=1.,
event_tolerance=3.):
"""Calculate the false-alarm rate of a search at given thresholds.
Arguments
---------
ts : pycbc.TimeSeries
The time series that is output by the search.
injection_times : numpy.array of floats
An array containing the times at which a signal was actually
present in the data.
trigger_thresh : {float, 0.2}
The threshold that is used to determine triggers from the
provided time series. (See the documentation of
get_trigger_times for more details)
ranking_thresh : {float, 0.5}
The threshold that is applied to the list of events to determine
which are significant. (See the documentation of
events_above_threshold for more details)
cluster_tolerance : {float, 1.}
The maximum separation of two triggers for them to be considered
part of the same cluster. (See the documentation of
get_cluster_boundaries for more details)
event_tolerance : {float, 3.}
The maximum separation between an event time and a trigger time
for the event to be counted as a true positive. (See the
documentation of get_false_positives for more details)
Returns
-------
float:
A false-alarm rate as false alarms per month.
Notes
-----
-This function is usually applied to the data with multiple
different values for the ranking_thresh. By doing so one obtains
the false-alarm rate as a function of a ranking statistic.
"""
triggers = get_trigger_times(ts, trigger_thresh)
clusters = get_cluster_boundaries(triggers,
boundarie_time=cluster_tolerance)
events = get_event_list(ts, clusters)
significant_events = events_above_threshold(events, ranking_thresh)
fp = get_false_positives(significant_events, injection_times,
tolerance=event_tolerance)
far = len(fp) / ts.duration * SECONDS_PER_MONTH
return far
def sensitive_fraction(ts, injection_times, trigger_thresh=0.2,
ranking_thresh=0.5, cluster_tolerance=1.,
event_tolerance=3.):
"""Calculate the sensitivity as a true positive rate.
Arguments
---------
ts : pycbc.TimeSeries
The time series that is output by the search.
injection_times : numpy.array of floats
An array containing the times at which a signal was actually
present in the data.
trigger_thresh : {float, 0.2}
The threshold that is used to determine triggers from the
provided time series. (See the documentation of
get_trigger_times for more details)
ranking_thresh : {float, 0.5}
The threshold that is applied to the list of events to determine
which are significant. (See the documentation of
events_above_threshold for more details)
cluster_tolerance : {float, 1.}
The maximum separation of two triggers for them to be considered
part of the same cluster. (See the documentation of
get_cluster_boundaries for more details)
event_tolerance : {float, 3.}
The maximum separation between an event time and a trigger time
for the event to be counted as a true positive. (See the
documentation of get_true_positives for more details)
Returns
-------
float:
The fraction of injected signals that were detected.
"""
triggers = get_trigger_times(ts, trigger_thresh)
clusters = get_cluster_boundaries(triggers,
boundarie_time=cluster_tolerance)
events = get_event_list(ts, clusters)
significant_events = events_above_threshold(events, ranking_thresh)
tp = get_true_positives(significant_events, injection_times,
tolerance=event_tolerance)
return float(len(tp)) / len(injection_times)
def filter_times(injection_times, times, assume_sorted=False):
"""Returns an index array. The indices point to positions in the
injection times the corresponding time of the times list can be
found.
Arguments
---------
injection_times : numpy.array of floats
An array containing the times at which a signal was actually
present in the data.
times : iterable of floats
A list of times.
assume_sorted : {bool, False}
Assume that the array of injection times is sorted.
Significantly speeds up the filtering process.
Returns
-------
numpy.array of int:
An array containing indices. The indices give the position of
the time from the times list in the injection_times array.
"""
ret = []
msg = 'Found non-matching time {} in injection times {}.'
if assume_sorted:
for time in times:
idx = np.searchsorted(injection_times, time)
if idx == len(injection_times) - 1:
if time == injection_times[-1]:
ret.append(len(injection_times)-1)
else:
msg = msg.format(time, injection_times)
raise RuntimeError(msg)
else:
if time == injection_times[idx]:
ret.append(idx)
elif time == injection_times[idx+1]:
ret.append(idx+1)
else:
msg = msg.format(time, injection_times)
raise RuntimeError(msg)
else:
for time in times:
idxs = np.where(injection_times == time)[0]
if len(idxs) > 0:
ret.append(idxs[0])
else:
msg = msg.format(time, injection_times)
raise RuntimeError(msg)
return np.array(ret)
def mchirp(m1, m2):
"""Calculate the chirp mass of the given component masses.
Arguments
---------
m1 : float or numpy.array of float
The primary mass.
m2 : float or numpy.array of float
The secondary mass.
Returns
-------
float or numpy.array of float:
The corresponding chirp-mass(es)
"""
return (m1 * m2) ** (3. / 5.) / (m1 + m2) ** (1. / 5.)
def sensitive_distance(ts, injection_times, injection_m1, injection_m2,
injection_dist, trigger_thresh=0.2,
ranking_thresh=0.5, cluster_tolerance=1.,
event_tolerance=3.):
"""Calculate the distance out to which the search is sensitive to
gravitational-wave sources.
Arguments
---------
ts : pycbc.TimeSeries
The time series that is output by the search.
injection_times : numpy.array of floats
An array containing the times at which a signal was actually
present in the data.
injection_m1 : numpy.array of floats
An array containing the primary masses of the injected signals.
(in solar masses)
injection_m2 : numpy.array of floats
An array containing the secondary masses of the injected
signals. (in solar masses)
injection_dist : numpy.array of floats
An array containing the distances of the injected signals. (in
solar mega Parsec)
trigger_thresh : {float, 0.2}
The threshold that is used to determine triggers from the
provided time series. (See the documentation of
get_trigger_times for more details)
ranking_thresh : {float, 0.5}
The threshold that is applied to the list of events to determine
which are significant. (See the documentation of
events_above_threshold for more details)
cluster_tolerance : {float, 1.}
The maximum separation of two triggers for them to be considered
part of the same cluster. (See the documentation of
get_cluster_boundaries for more details)
event_tolerance : {float, 3.}
The maximum separation between an event time and a trigger time
for the event to be counted as a true positive. (See the
documentation of get_true_positives for more details)
Returns
-------
float:
The distance out to which the search is able to detect
gravitational waves. (an average, in mega Parsec)
"""
triggers = get_trigger_times(ts, trigger_thresh)
clusters = get_cluster_boundaries(triggers,
boundarie_time=cluster_tolerance)
events = get_event_list(ts, clusters)
significant_events = events_above_threshold(events, ranking_thresh)
tp = get_true_positives(significant_events, injection_times,
tolerance=event_tolerance)
found_times, found_idxs = get_closest_injection_times(injection_times,
get_event_times(tp),
return_indices=True)
#missed_times = get_missed_injection_times(significant_events,
#injection_times,
#tolerance=event_tolerance)
missed_idxs = np.setdiff1d(np.arange(len(injection_times)), found_idxs)
#found_idxs = filter_times(injection_times, found_times)
if len(found_idxs) > 0:
found_m1 = injection_m1[found_idxs]
found_m2 = injection_m2[found_idxs]
found_dist = injection_dist[found_idxs]
found_mchirp = mchirp(found_m1, found_m2)
else:
found_m1 = np.array([1.])
found_m2 = np.array([1.])
found_dist = np.array([0.])
found_mchirp = np.array([1.])
#missed_idxs = filter_times(injection_times, missed_times)
if len(missed_idxs) > 0:
missed_m1 = injection_m1[missed_idxs]
missed_m2 = injection_m2[missed_idxs]
missed_dist = injection_dist[missed_idxs]
missed_mchirp = mchirp(missed_m1, missed_m2)
else:
missed_m1 = np.array([1.])
missed_m2 = np.array([1.])
missed_dist = np.array([1.])
missed_mchirp = np.array([np.inf])
vol, vol_err = volume_montecarlo(found_dist,
missed_dist,
found_mchirp,
missed_mchirp,
'distance',
'volume',
'distance')
rad = (3 * vol / (4 * np.pi))**(1. / 3.)
return rad
class progress_tracker():
"""A class that implements and prints a dynamic progress bar to
stdout.
Arguments
---------
num_of_steps : int
The number of iterations that is expected to occur.
name : {str, 'Progress'}
The name for the header of the progress bar. It will be followed
by a colon ':' when printed.
steps_taken : {int, 0}
The number of steps that are already completed.
"""
def __init__(self, num_of_steps, name='Progress', steps_taken=0):
self.t_start = datetime.datetime.now()
self.num_of_steps = num_of_steps
self.steps_taken = steps_taken
self.name = name
self._printed_header = False
self.last_string_length = 0
def __len__(self):
return self.num_of_steps
@property
def eta(self):
now = datetime.datetime.now()
return(int(round(float((now - self.t_start).seconds) / float(self.steps_taken) * float(self.num_of_steps - self.steps_taken))))
@property
def percentage(self):
return(int(100 * float(self.steps_taken) / float(self.num_of_steps)))
def get_print_string(self):
curr_perc = self.percentage
real_perc = self.percentage
#Length of the progress bar is 25. Hence one step equates to 4%.
bar_len = 25
if not curr_perc % 4 == 0:
curr_perc -= curr_perc % 4
if int(curr_perc / 4) > 0:
s = '[' + '=' * (int(curr_perc / 4) - 1) + '>' + '.' * (bar_len - int(curr_perc / 4)) + ']'
else:
s = '[' + '.' * bar_len + ']'
tot_str = str(self.num_of_steps)
curr_str = str(self.steps_taken)
curr_str = ' ' * (len(tot_str) - len(curr_str)) + curr_str
eta = str(datetime.timedelta(seconds=self.eta)) + 's'
perc_str = ' ' * (len('100') - len(str(real_perc))) + str(real_perc)
out_str = curr_str + '/' + tot_str + ': ' + s + ' ' + perc_str + '%' + ' ETA: ' + eta
if self.last_string_length > len(out_str):
back = '\b \b' * (self.last_string_length - len(out_str))
else:
back = ''
#back = '\b \b' * self.last_string_length
self.last_string_length = len(out_str)
return(back + '\r' + out_str)
#return(back + out_str)
def print_progress_bar(self, update=True):
if not self._printed_header:
print(self.name + ':')
self._printed_header = True
if update:
sys.stdout.write(self.get_print_string())
sys.stdout.flush()
if self.steps_taken == self.num_of_steps:
self.print_final(update=update)
else:
print(self.get_print_string())
if self.steps_taken == self.num_of_steps:
self.print_final(update=update)
def iterate(self, iterate_by=1, print_prog_bar=True, update=True):
if iterate_by > 0:
self.steps_taken += iterate_by
if print_prog_bar:
self.print_progress_bar(update=update)
def print_final(self, update=True):
final_str = str(self.steps_taken) + '/' + str(self.num_of_steps) + ': [' + 25 * '=' + '] 100% - Time elapsed: ' + str(datetime.timedelta(seconds=(datetime.datetime.now() - self.t_start).seconds)) + 's'
if update:
clear_str = '\b \b' * self.last_string_length
sys.stdout.write(clear_str + final_str + '\n')
sys.stdout.flush()
else:
print(final_str)
class mp_progress_tracker(progress_tracker):
"""A class that implements and prints a dynamic progress bar to
stdout. This special case is multiprocessing save.
Arguments
---------
num_of_steps : int
The number of iterations that is expected to occur.
name : {str, 'Progress'}
The name for the header of the progress bar. It will be followed