-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththresholds.py
More file actions
1445 lines (1243 loc) · 59.3 KB
/
thresholds.py
File metadata and controls
1445 lines (1243 loc) · 59.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
:copyright:
IRIS Data Management Center
:license:
This file is part of QuARG.
QuARG is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuARG is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuARG. If not, see <https://www.gnu.org/licenses/>.
"""
import pandas as pd
pd.set_option("future.no_silent_downcasting", True)
import reportUtils
import datetime
import os
def load_thresholdDicts(thresholdFile):
# FIRST, Read in the file and genrate two Dictionaries
# One will be the thresholdDict, which is used when initially grabbing metrics from webservices
# The other will provide defitinions of the thresholds
thresholdDefDict = {}
thresholdDict = {}
with open(thresholdFile) as f:
local_dict = locals()
exec(compile(f.read(), thresholdFile, "exec"), globals(), local_dict)
return (
local_dict["thresholdsDict"],
local_dict["thresholdsMetricsDict"],
local_dict["instrumentGroupsDict"],
)
def get_threshold_metrics(thresholds, thresholdFile):
metrics = list()
failedThresholds = list()
thresholdDefDict, thresholdMetDict, instrumentGroupsDict = load_thresholdDicts(
thresholdFile
)
for threshold in thresholds:
try:
for metric in thresholdMetDict[threshold]:
metrics.append(metric)
except:
if threshold not in failedThresholds:
failedThresholds.append(threshold)
print(
"WARNING: Unable to understand threshold %s: the threshold has likely been deleted from the Edit Thresholds form, but not removed from this Preference File"
% threshold
)
metrics = list(set(metrics))
return metrics, failedThresholds
def load_metric_and_metadata():
metrics_file = "./MUSTANG_metrics.txt"
metadata_file = "./EarthScope_metadata.txt"
try:
with open(metrics_file, "r") as f:
metricList = f.read().splitlines()
except Exception as e:
print("Warning: %s" % e)
metricList = list()
try:
with open(metadata_file, "r") as f:
metadataList = f.read().splitlines()
except Exception as e:
print("Warning: %s" % e)
metadataList = list()
return metricList, metadataList
def do_threshold(
threshold,
thresholdFile,
metricDF,
metaDF,
outfile,
instruments,
specified_start,
specified_end,
hasMetrics,
chanTypes,
):
print("Running %s" % threshold)
thresholdDefDict, thresholdMetDict, instrumentGroupsDict = load_thresholdDicts(
thresholdFile
)
metricList, metadataList = load_metric_and_metadata()
pd.options.mode.chained_assignment = None
def get_channel_lists(CH1, CH2):
ch1 = ""
ch2 = ""
if not CH1 == "":
ch1 = chanTypes[CH1]
if not CH2 == "":
ch2 = chanTypes[CH2]
return ch1, ch2
def do_channel_figuring(
dfToUse, CH1, CH2, ch1, ch2, chType1, chType2, doAbs1, doAbs2
):
columnsToNotChange = [
"target",
"start",
"end",
"network",
"station",
"location",
"channel",
"snl",
"new_target",
]
metricsInDF = [x for x in dfToUse.columns if x not in columnsToNotChange]
dfToUse["snl"] = dfToUse["target"].apply(
lambda x: os.path.splitext(os.path.splitext(x)[0])[0]
) # use snl instead of station to do merging, in case multiple location codes
#### CASES WITH AVG ###
if chType1 == "" and chType2 == "avg":
# CH2 must be H, CH1 can be V or H
for col in dfToUse.columns:
if col in columnsToNotChange:
continue
dfToUse.rename(columns={col: col + "_" + chType1}, inplace=True)
tmpDF = dfToUse[dfToUse["channel"].str.endswith(ch2)]
numeric_cols = tmpDF.select_dtypes(include="number").columns
horzAvg = (
tmpDF.groupby(["snl", "start"], as_index=False)[numeric_cols]
.mean()
.reset_index()
)
for col in horzAvg.columns:
if col in columnsToNotChange:
continue
horzAvg.rename(columns={col: col + chType2}, inplace=True)
dfToUse = pd.merge(dfToUse, horzAvg, how="inner", on=["snl", "start"])
newTargets = list()
for idx, row in dfToUse.iterrows():
splitTarget = row["target"].split(".")
thisSNL = row["snl"]
ch2ThisSNL = "".join(
sorted(
[
i
for i in list(
set(
dfToUse[dfToUse["snl"] == thisSNL]
.channel.str.strip()
.str[-1]
)
)
if i in ch2
]
)
)
newChannel = "%s/[%s]" % (splitTarget[3], ch2ThisSNL)
splitTarget[3] = newChannel
newTarget = ".".join(splitTarget)
newTargets.append(newTarget)
dfToUse["new_target"] = newTargets
if chType1 == "avg" and chType2 == "":
# CH1 must be H, CH2 can be H or V
for col in dfToUse.columns:
if col in columnsToNotChange:
continue
dfToUse.rename(columns={col: col + "_" + chType2}, inplace=True)
tmpDF = dfToUse[dfToUse["channel"].str.endswith(ch1)]
numeric_cols = tmpDF.select_dtypes(include="number").columns
horzAvg = tmpDF.groupby(["snl", "start"])[numeric_cols].reset_index()
for col in horzAvg.columns:
if col in columnsToNotChange:
continue
horzAvg.rename(columns={col: col + chType1}, inplace=True)
dfToUse = pd.merge(dfToUse, horzAvg, how="inner", on=["snl", "start"])
newTargets = list()
for idx, row in dfToUse.iterrows():
splitTarget = row["target"].split(".")
thisSNL = row["snl"]
ch1ThisSNL = "".join(
[
i
for i in list(
set(
dfToUse[dfToUse["snl"] == thisSNL]
.channel.str.strip()
.str[-1]
)
)
if i in ch1
]
)
newChannel = "%s[%s]/%s" % (
splitTarget[3][0:2],
ch1ThisSNL,
splitTarget[3][-1],
)
splitTarget[3] = newChannel
newTarget = ".".join(splitTarget)
newTargets.append(newTarget)
dfToUse["new_target"] = newTargets
if chType1 == "avg" and chType2 == "avg":
# This case can only happen if we are comparing two different metrics
# Create dataframe average of horizontals for metric 1
tmpDF = dfToUse[dfToUse["channel"].str.endswith(ch1)]
numeric_cols = tmpDF.select_dtypes(include="number").columns
horzAvg = tmpDF.groupby(["snl", "start"])[numeric_cols].mean().reset_index()
for col in horzAvg.columns:
if col in columnsToNotChange:
continue
horzAvg.rename(columns={col: col + "_" + chType2}, inplace=True)
dfToUse = pd.merge(dfToUse, horzAvg, how="inner", on=["snl", "start"])
newTargets = list()
for idx, row in dfToUse.iterrows():
splitTarget = row["target"].split(".")
thisSNL = row["snl"]
ch1ThisSNL = "".join(
[
i
for i in list(
set(
dfToUse[dfToUse["snl"] == thisSNL]
.channel.str.strip()
.str[-1]
)
)
if i in ch1
]
)
newChannel = "%s[%s]" % (splitTarget[3][0:2], ch1ThisSNL)
splitTarget[3] = newChannel
newTarget = ".".join(splitTarget)
newTargets.append(newTarget)
dfToUse["new_target"] = newTargets
#### CASES WITH VS ####
if (chType1 == "" and chType2 == "vs") or (chType1 == "vs" and chType2 == ""):
print("INFO: comparing 'all' with a 'vs' - this shouldn't happen")
if (chType1 == "avg" and chType2 == "vs") or (
chType1 == "vs" and chType2 == "avg"
):
print("INFO: comparing 'avg' with 'vs' - this shouldn't happen")
if chType1 == "vs" and chType2 == "vs":
# CH1 and CH2 must be H
dfToUse = dfToUse[~dfToUse["channel"].str.endswith(chanTypes["V"])]
for col in dfToUse.columns:
if col in columnsToNotChange:
continue
dfToUse.rename(columns={col: col + "_" + chType1}, inplace=True)
# Horizontal vs horizontal: need to copy the value of both horizontals for each NSL,
# such that both E/N and N/E can be computed
# Since it is H-vs v H-vs, both ch1 and ch2 should be exaclty the same
# create a column for snl, to use as a join later:
dfToUse["snl"] = dfToUse["target"].apply(
lambda x: os.path.splitext(os.path.splitext(x)[0])[0]
)
dtToStore = dfToUse.copy()
colList = list()
chanDict = dict()
for tmpChan in ch1:
# get all values for each channel, then create a new column with those values, associated with the snl
tmpValues = dtToStore[dtToStore.channel.str.endswith(tmpChan)]
tmpValues.drop(
["station", "location", "channel", "end", "target", "network"],
axis=1,
inplace=True,
)
for col in tmpValues.columns:
# if col in columnsToNotChange or col == 'snl':
if col in columnsToNotChange:
continue
newcol = col + "_" + tmpChan
if newcol not in colList:
colList.append(newcol)
tmpValues.rename(columns={col: newcol}, inplace=True)
for snl in set(tmpValues["snl"]):
try:
chanDict[snl] = chanDict[snl] + tmpChan
except:
chanDict[snl] = tmpChan
dfToUse.dropna(subset=["channel"], inplace=True)
mergedDF = pd.merge(
dfToUse[~dfToUse["channel"].str.endswith(tmpChan)],
tmpValues,
how="outer",
on=["snl", "start"],
)
dfToUse = pd.merge(dfToUse, mergedDF, how="outer")
for metric in metricsInDF:
theseCols = [x for x in colList if x.startswith(metric)]
sncl2 = metric + "_sncl2"
dfToUse[sncl2] = dfToUse[theseCols[0]]
for col in theseCols:
dfToUse[sncl2] = (
dfToUse[sncl2].fillna(dfToUse[col]).infer_objects(copy=False)
)
dfToUse.drop([col], axis=1, inplace=True)
dfToUse.dropna(subset=["target"], inplace=True)
newTargets = list()
for idx, row in dfToUse.iterrows():
try:
splitTarget = row["target"].split(".")
except:
newTargets.append(row["target"])
continue
thisSNL = row["snl"]
thisChan = splitTarget[3][-1]
try:
ch1ThisSNL = chanDict[thisSNL].replace(thisChan, "")
except:
print(
"INFO: unable to process %s - maybe it has H[orizontal] channels not included in the preference file?"
% thisSNL
)
newTargets.append("")
continue
newChannel = "%s/%s" % (splitTarget[3], ch1ThisSNL)
splitTarget[3] = newChannel
newTarget = ".".join(splitTarget)
newTargets.append(newTarget)
dfToUse["new_target"] = newTargets
#### CASES WITHOUT VS OR AVG ####
if chType1 == "" and chType2 == "":
# Can be any combination of H and V (H-V, V-H, H-H, V-V)
# CH1 == CH2 is handled directly in the dp_ method, since we already have a dataframe with the two metrics joined on target-day
#### V vs H, or H vs V ####
if CH1 != CH2:
# Can be same or different metrics, either way we need to get the different channels into a single row
for col in dfToUse.columns:
if col in columnsToNotChange:
continue
dfToUse.rename(columns={col: col + "_"}, inplace=True)
dfToUse["snl"] = dfToUse["target"].apply(
lambda x: os.path.splitext(os.path.splitext(x)[0])[0]
)
dtToStore = (
dfToUse.copy()
) # copy all values before subsetting for only ch1, so that all are availble as sncl2
dfToUse = dfToUse[
dfToUse["channel"].str.endswith(ch1)
] # now there will only be ch1 channels in the main slot
newChanDF = dfToUse[["channel", "target", "start"]]
newChanList = list()
oldChanList = list()
for tmpChanA in dfToUse["channel"]:
for tmpChanB in ch2:
newChanList.append("%s%s" % (tmpChanA[0:2], tmpChanB))
oldChanList.append(tmpChanA)
ncDF = pd.DataFrame(newChanList, columns=["second_channel"])
ncDF["channel"] = oldChanList
newChanDF = (
pd.merge(newChanDF, ncDF).drop_duplicates().reset_index(drop=True)
)
dfToUse = pd.merge(dfToUse, newChanDF)
colList = list()
for tmpChan in ch2:
# get all values for each channel, then create a new column with those values, associated with the snl
tmpValues = dtToStore[dtToStore.channel.str.endswith(tmpChan)]
tmpValues.drop(
["station", "location", "end", "network", "target"],
axis=1,
inplace=True,
)
for col in tmpValues.columns:
if (
col in columnsToNotChange
or col == "second_channel"
or col == "snl"
):
continue
newcol = col + tmpChan
if newcol not in colList:
colList.append(newcol)
tmpValues.rename(columns={col: newcol}, inplace=True)
tmpValues.rename(
columns={"channel": "second_channel"}, inplace=True
)
mergedDF = pd.merge(
dfToUse, tmpValues, on=["snl", "start", "second_channel"]
)
dfToUse = pd.merge(dfToUse, mergedDF, how="outer")
newTargets = list()
for idx, row in dfToUse.iterrows():
splitTarget = row["target"].split(".")
newChannel = "%s/%s" % (splitTarget[3], row["second_channel"][-1])
splitTarget[3] = newChannel
newTarget = ".".join(splitTarget)
newTargets.append(newTarget)
dfToUse["new_target"] = newTargets
for metric in metricsInDF:
theseCols = [x for x in colList if x.startswith(metric)]
sncl2 = metric + "_sncl2"
dfToUse[sncl2] = dfToUse[theseCols[0]]
for col in theseCols:
dfToUse[sncl2] = dfToUse[sncl2].fillna(dfToUse[col])
dfToUse.drop([col], axis=1, inplace=True)
if chType1 == "" and chType2 == "V":
pass
if chType1 == "" and chType2 == "V":
pass
if chType1 == "" and chType2 == "V":
pass
return dfToUse
def do_comparison(dfToUse, field1, operator, field2, doAbs1, doAbs2):
if operator == ">=":
if doAbs1 and doAbs2:
dfToUse = dfToUse[field1.abs() >= field2.abs()]
elif doAbs1:
dfToUse = dfToUse[field1.abs() >= field2]
elif doAbs2:
dfToUse = dfToUse[field1 >= field2.abs()]
else:
dfToUse = dfToUse[field1 >= field2]
if operator == "!>=":
if doAbs1 and doAbs2:
dfToUse = dfToUse[field1.abs() < field2.abs()]
elif doAbs1:
dfToUse = dfToUse[field1.abs() < field2]
elif doAbs2:
dfToUse = dfToUse[field1 < field2.abs()]
else:
dfToUse = dfToUse[field1 < field2]
if operator == ">":
if doAbs1 and doAbs2:
dfToUse = dfToUse[field1.abs() > field2.abs()]
elif doAbs1:
dfToUse = dfToUse[field1.abs() > field2]
elif doAbs2:
dfToUse = dfToUse[field1 > field2.abs()]
else:
dfToUse = dfToUse[field1 > field2]
if operator == "=":
if doAbs1 and doAbs2:
dfToUse = dfToUse[field1.abs() == field2.abs()]
elif doAbs1:
dfToUse = dfToUse[field1.abs() == field2]
elif doAbs2:
dfToUse = dfToUse[field1 == field2.abs()]
else:
dfToUse = dfToUse[field1 == field2]
if operator == "!=":
if doAbs1 and doAbs2:
dfToUse = dfToUse[field1.abs() != field2.abs()]
elif doAbs1:
dfToUse = dfToUse[field1.abs() != field2]
elif doAbs2:
dfToUse = dfToUse[field1 != field2.abs()]
else:
dfToUse = dfToUse[field1 != field2]
if operator == "<=":
if doAbs1 and doAbs2:
dfToUse = dfToUse[field1.abs() <= field2.abs()]
elif doAbs1:
dfToUse = dfToUse[field1.abs() <= field2]
elif doAbs2:
dfToUse = dfToUse[field1 <= field2.abs()]
else:
dfToUse = dfToUse[field1 <= field2]
if operator == "!<=":
if doAbs1 and doAbs2:
dfToUse = dfToUse[field1.abs() > field2.abs()]
elif doAbs1:
dfToUse = dfToUse[field1.abs() > field2]
elif doAbs2:
dfToUse = dfToUse[field1 > field2.abs()]
else:
dfToUse = dfToUse[field1 > field2]
if operator == "<":
if doAbs1 and doAbs2:
dfToUse = dfToUse[field1.abs() < field2.abs()]
elif doAbs1:
dfToUse = dfToUse[field1.abs() < field2]
elif doAbs2:
dfToUse = dfToUse[field1 < field2.abs()]
else:
dfToUse = dfToUse[field1 < field2]
return dfToUse
def simple_threshold(chanMetricDF, chanMetaDF, subDef):
# Whether we use chanMetricDF or chanMetaDF depends on whether this definition has metrics or metadata...
doAbs1 = 0
doAbs2 = 0
CH1 = ""
# Get the definition
threshDefs = thresholdDefDict[threshold]
try:
field = subDef.split()[0].split("[")[0]
try:
CH1 = subDef.split()[0].split("[")[1].replace("]", "")
ch1, ch2 = get_channel_lists(CH1, "")
except:
ch1 = ""
if "abs" in field:
doAbs1 = 1
field = field.replace("abs(", "").replace(")", "")
if field in metricList:
fieldType = "metric"
dfToUse = chanMetricDF
elif field in metadataList:
fieldType = "metadata"
field = field.lower()
dfToUse = chanMetaDF
else:
print("WARNING unknown field type")
return chanMetricDF, chanMetaDF, "simple"
try:
field = field.split("::")[1]
except:
pass
operator = subDef.split()[1]
try:
# it's numeric
value = float(subDef.split()[2])
except:
# it's not numeric, so the fielf better be a metadata field
if fieldType != "metadata":
print(
"Warning, only metadata fields can have non-numeric cutoff values"
)
return chanMetricDF, chanMetaDF, "simple"
else:
value = subDef.split()[2]
# If the threshold is only for horixontal or verticals, then subset it now:
if ch1 != "":
dfToUse = dfToUse[dfToUse["channel"].str.endswith(ch1)]
except Exception as e:
print("Warning: could not calculate threshold %s - %s" % (subDef, e))
return chanMetricDF, chanMetaDF, "simple"
dfToUse = do_comparison(
dfToUse, dfToUse[field], operator, value, doAbs1, doAbs2
)
if fieldType == "metric":
chanMetricDF = dfToUse
elif fieldType == "metadata":
chanMetaDF = dfToUse
return chanMetricDF, chanMetaDF, "simple"
# ============================#
# COMPLETENESS THRESHOLDS
def ratio_threshold(chanMetricDF, chanMetaDF, subDef):
doAbs1 = 0 # first metric
doAbs2 = 0 # second metric
doAbs3 = 0 # "ratio" - unused currently, placeholder
doAbs4 = 0 # cutoff value - unused currently, placeholder
chType1 = ""
chType2 = ""
try:
met1 = subDef.split("/")[0].split()[-1].split("[")[0]
met2 = subDef.split("/")[1].split()[0].split("[")[0]
except Exception as e:
print("Warning: Could not parse ratio threshold %s - %s" % (subDef, e))
return chanMetricDF, chanMetaDF, "ratio"
if "abs" in met1:
doAbs1 = 1
met1 = met1.replace("abs(", "").replace(")", "")
if "abs" in met2:
doAbs2 = 1
met2 = met2.replace("abs(", "").replace(")", "")
if met1 in metricList:
fieldType = "metric"
dfToUse = chanMetricDF
elif met1 in metadataList:
fieldType = "metadata"
dfToUse = chanMetaDF
else:
print("WARNING: unknown field type")
return chanMetricDF, chanMetaDF, "ratio"
try:
met1 = met1.split("::")[1]
except:
pass
try:
met2 = met2.split("::")[1]
except:
pass
# figure out what's going on with H/V, if anything
try:
CH1 = (
subDef.split("/")[0]
.split()[-1]
.split("[")[1]
.replace("]", "")
.replace(")", "")
)
try:
chType1 = CH1.split(":")[1]
CH1 = CH1.split(":")[0]
except:
pass
except:
CH1 = ""
try:
CH2 = (
subDef.split("/")[1]
.split()[0]
.split("[")[1]
.replace("]", "")
.replace(")", "")
)
try:
chType2 = CH2.split(":")[1]
CH2 = CH2.split(":")[0]
except:
pass
except:
CH2 = ""
## Only in the ratio threshold do we have to handle the absolute values outside of the do_comparison function
ch1, ch2 = get_channel_lists(CH1, CH2)
columnsToNotChange = [
"target",
"start",
"end",
"network",
"station",
"location",
"channel",
"snl",
"ratio",
"new_target",
]
if CH1 == CH2 and chType1 == chType2 == "":
if doAbs1:
dfToUse[met1] = dfToUse[met1].abs()
if doAbs2:
dfToUse[met2] = dfToUse[met2].abs()
dfToUse["ratio"] = (
dfToUse[met1] / dfToUse[met2]
) # Later we will whittle down to just the V or just the H, if necessary
else:
# Do the figuring on what needs to happen to the dataframe based on chType1 and chyType2
dfToUse = do_channel_figuring(
dfToUse, CH1, CH2, ch1, ch2, chType1, chType2, doAbs1, doAbs2
)
# create the ratio column:
if chType1 == "vs" or chType2 == "vs":
if doAbs1:
dfToUse[met1 + "_" + chType1] = dfToUse[met1 + "_" + chType1].abs()
if doAbs2:
dfToUse[met2 + "_sncl2"] = dfToUse[met2 + "_sncl2"].abs()
dfToUse["ratio"] = (
dfToUse[met1 + "_" + chType1] / dfToUse[met2 + "_sncl2"]
)
# delete extra columns, revert names of main metrics
for col in dfToUse.columns:
if col.endswith("_sncl2"):
dfToUse.drop([col], axis=1, inplace=True)
elif col not in columnsToNotChange:
dfToUse.rename(
columns={col: col.rsplit("_", 1)[0]}, inplace=True
)
else:
if chType1 == chType2 == "":
if doAbs1:
dfToUse[met1 + "_"] = dfToUse[met1 + "_"].abs()
if doAbs2:
dfToUse[met2 + "_sncl2"] = dfToUse[met2 + "_sncl2"].abs()
dfToUse["ratio"] = dfToUse[met1 + "_"] / dfToUse[met2 + "_sncl2"]
# delete extra columns, revert names of main metrics
for col in dfToUse.columns:
if col.endswith("_sncl2"):
dfToUse.drop([col], axis=1, inplace=True)
elif col not in columnsToNotChange:
dfToUse.rename(
columns={col: col.rsplit("_", 1)[0]}, inplace=True
)
else:
if doAbs1:
dfToUse[met1 + "_" + chType1] = dfToUse[
met1 + "_" + chType1
].abs()
if doAbs2:
dfToUse[met2 + "_" + chType2] = dfToUse[
met2 + "_" + chType2
].abs()
dfToUse["ratio"] = (
dfToUse[met1 + "_" + chType1] / dfToUse[met2 + "_" + chType2]
)
# delete extra columns, revert names of main metrics
for col in dfToUse.columns:
if col.endswith("_" + chType2):
dfToUse.drop([col], axis=1, inplace=True)
elif col not in columnsToNotChange:
dfToUse.rename(
columns={col: col.rsplit("_", 1)[0]}, inplace=True
)
if ch1 != "":
dfToUse = dfToUse[dfToUse["channel"].str.endswith(ch1)]
#####
try:
fields = subDef.split()
operator = fields[3]
value = float(fields[4])
except Exception as e:
print("Warning: could not calculate threshold %s - %s" % (subDef, e))
return
dfToUse = do_comparison(
dfToUse, dfToUse["ratio"], operator, value, doAbs3, doAbs4
)
if fieldType == "metric":
chanMetricDF = dfToUse
elif fieldType == "metadata":
chanMetaDF = dfToUse
return chanMetricDF, chanMetaDF, "ratio"
def average_threshold(chanMetricDF, chanMetaDF, subDef):
# Shouldn't have metadata in here, but keeping it open for future-proofing
doAbs1 = 0
doAbs2 = 0
CH1 = ""
CH2 = ""
try:
fields = subDef.split("::")[1].split()
field = fields[0].split("[")[0]
operator = fields[1]
value = float(fields[2])
try:
CH1 = fields[0].split("[")[1].replace("]", "")
ch1, ch2 = get_channel_lists(CH1, CH2)
except:
ch1 = ""
if "abs" in field:
doAbs1 = 1
field = field.replace("abs(", "").replace(")", "")
if field in metricList:
fieldType = "metric"
dfToUse = chanMetricDF
elif field in metadataList:
fieldType = "metadata"
dfToUse = chanMetaDF
else:
print("WARNING: unknown field type")
return
try:
field = field.split("::")[1]
except:
pass
dfToUse = dfToUse.groupby("target", as_index=False)[field].mean().round(1)
dfToUse.rename(columns={field: "value"}, inplace=True)
dfToUse["channel"] = [t.split(".")[3] for t in dfToUse["target"]]
dfToUse["start"] = datetime.datetime.strptime(specified_start, "%Y-%m-%d")
dfToUse["end"] = datetime.datetime.strptime(specified_end, "%Y-%m-%d")
# If the threshold is only for horixontal or verticals, then subset it now:
if ch1 != "":
dfToUse = dfToUse[dfToUse["channel"].str.endswith(ch1)]
except Exception as e:
print("WARNING: Unable to calculate %s - %s" % (subDef, e))
return dfToUse, fieldType, "average"
dfToUse = do_comparison(
dfToUse, dfToUse["value"], operator, value, doAbs1, doAbs2
)
if fieldType == "metric":
chanMetricDF = dfToUse
elif fieldType == "metadata":
chanMetaDF = dfToUse
return chanMetricDF, chanMetaDF, "average"
def median_threshold(chanMetricDF, chanMetaDF, subDef):
# Shouldn't have metadata in here, but keeping it open for future-proofing
doAbs1 = 0
doAbs2 = 0
CH1 = ""
CH2 = ""
try:
fields = subDef.split("::")[1].split()
field = fields[0].split("[")[0]
operator = fields[1]
value = float(fields[2])
try:
CH1 = fields[0].split("[")[1].replace("]", "")
ch1, ch2 = get_channel_lists(CH1, CH2)
except:
ch1 = ""
if "abs" in field:
doAbs1 = 1
field = field.replace("abs(", "").replace(")", "")
if field in metricList:
fieldType = "metric"
dfToUse = chanMetricDF
elif field in metadataList:
fieldType = "metadata"
dfToUse = chanMetaDF
else:
print("WARNING: unknown field type")
return chanMetricDF, chanMetaDF, "median"
try:
field = field.split("::")[1]
except:
pass
dfToUse = dfToUse.groupby("target", as_index=False)[field].median().round(1)
dfToUse.rename(columns={field: "value"}, inplace=True)
dfToUse["channel"] = [t.split(".")[3] for t in dfToUse["target"]]
dfToUse["start"] = datetime.datetime.strptime(specified_start, "%Y-%m-%d")
dfToUse["end"] = datetime.datetime.strptime(specified_end, "%Y-%m-%d")
# If the threshold is only for horixontal or verticals, then subset it now:
if ch1 != "":
dfToUse = dfToUse[dfToUse["channel"].str.endswith(ch1)]
except Exception as e:
print("WARNING: Unable to calculate %s - %s" % (subDef, e))
return chanMetricDF, chanMetaDF, "median"
dfToUse = do_comparison(
dfToUse, dfToUse["value"], operator, value, doAbs1, doAbs2
)
if fieldType == "metric":
chanMetricDF = dfToUse
elif fieldType == "metadata":
chanMetaDF = dfToUse
return chanMetricDF, chanMetaDF, "median"
def compare_threshold(chanMetricDF, chanMetaDF, subDF):
doAbs1 = 0
doAbs2 = 0
CH1 = ""
CH2 = ""
chType1 = ""
chType2 = ""
columnsToNotChange = [
"target",
"start",
"end",
"network",
"station",
"location",
"channel",
"snl",
"ratio",
"new_target",
]
try:
fields = subDef.split()
met1 = fields[0].split("[")[0]
operator = fields[1]
met2 = fields[2].split("[")[0]
except Exception as e:
print("WARNING: Unable to calculate %s - %s" % (subDef, e))
return chanMetricDF, chanMetaDF, "comparison"
if "abs" in met1:
doAbs1 = 1
met1 = met1.replace("abs(", "").replace(")", "")
if "abs" in met2:
doAbs2 = 1
met2 = met2.replace("abs(", "").replace(")", "")
if met1 in metricList:
fieldType = "metric"
dfToUse = chanMetricDF
elif met1 in metadataList:
fieldType = "metadata"
dfToUse = chanMetaDF
else:
print("WARNING: unknown field type")
return chanMetricDF, chanMetaDF, "comparison"
try:
met1 = met1.split("::")[1]
except:
pass
try:
met2 = met2.split("::")[1]
except:
pass
# figure out what's going on with H/V, if anything