-
Notifications
You must be signed in to change notification settings - Fork 4
/
csv_check_work_tapes.py
executable file
·5107 lines (4218 loc) · 386 KB
/
csv_check_work_tapes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Run initial checks on csv files
Make checked csv files (will drop some damaged data)
out of the raw csv files extracted from binary.
This uses the following workflow:
# split the dataframe into station and ground station
df_st_list = all_split(df,gzip_filename)
config.cumsum_test = cumsum_test
# This is a key bit of code to test
# check the timeseries data and remove any that don't fit
df_gst, df_dropped, df_orig, rec_fixed_frame, rec_fixed_simple_timestamp, rec_adjusted_timestamps, rec_deleted_non_uniq, rec_deleted_timestamps, rec_repeated_frame, compliance_passed = check_compliance(df_gst,gzip_filename)
# Fix the frame number if it was incorrectly recorded
df_gst, rec_fixed_frame, rec_repeated_frame = station_fix_frames(df_gst)
# Where possible, do a really simple fix on the timestamp
df_gst, rec_fixed_simple_timestamp = station_simple_fix_timestamp(df_gst)
# find the cumulative sum of the good records
df_gst = calculate_cumsum(df_gst)
# estimate the delta as it changes over time
df_gst = calculate_delta4(df_gst)
# fix timestamps if possible (called from check_compliance)
df_gst, df_dropped, df_orig, rec_adjusted_timestamps, compliance_passed = fix_timestamps(df_gst, df_dropped)
# fix any gaps (called from fix_timestamps, which is called from check_compliance)
Search for gaps in the record. Blank records are inserted if the
following conditions are met:
Can either be called by the bad record, or for the whole
dataframe.
df_gst = station_fix_missing_timestamps2(df_gst)
split_good_records
finally, save the good files and the dropped files (note that the dropped files
are concatenated - so bear the timestamp of the first record)
if there are a lot of missed records, then reducing config.cumsum_final_test
to a smaller number (e.g. 10), may reduced the missed records
(but make require some manual corrections at the join stage)
See also the notes in config.py - there are some adjustable parameters.
:copyright:
The pdart Development Team & Ceri Nunn
:license:
GNU Lesser General Public License, Version 3
(https://www.gnu.org/copyleft/lesser.html)
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from future.builtins import * # NOQA
from datetime import datetime, timedelta
import os
import io
import gzip
import glob
import math
import numpy as np
import numpy.ma as ma
import logging, logging.handlers
import csv
import fnmatch
import shutil
import pandas as pd
from random import choice, seed
from itertools import groupby
import sys, traceback
from collections import OrderedDict
from obspy.core.utcdatetime import UTCDateTime
from obspy.core import Stream, Trace, Stats, read
# from pdart.save_24_hours import update_starttimes
import pdart.config as config
# from pdart.csv_import_work_tapes import find_output_dir, make_output_dir, make_filelist
import matplotlib.pyplot as plt
# global DELTA
DELTA = 0.1509433962
INTERVAL = '603774us'
INVALID = -99999
# X should point north, Y east, but this is not always the case
# so we rename LPX to MH1, and LPY to MH2
NETWORK='XA'
# global first_record
# global last_record
# consecutive frames
# FRAMES = list(range(0,90))
def call_csv_check_work_tapes(
checked_dir='.',
processed_dir='.',
log_dir='.',
filenames=None,
# logging_level=logging.DEBUG
logging_level=logging.INFO,
single_station=None,
single_ground_station=None
):
'''
Makes initial stream files from gzipped csv files which have been checked.
Calls csv_import_work_tapes()
'''
# if no filenames have been passed, then look for them
if filenames is None:
filenames = []
for filename in glob.glob(os.path.join(checked_dir,'wtn*.csv.gz')):
filenames.append(os.path.basename(filename))
for filename in filenames:
print('Searching for :', os.path.join(checked_dir,filename))
try:
for in_file in glob.glob(os.path.join(checked_dir,filename)):
orig_timestamps = csv_check_work_tapes(in_file,single_station,
single_ground_station,logging_level,processed_dir,log_dir)
except Exception as e:
logging.info(traceback.format_exc())
logging.info(traceback.print_exc(file=sys.stdout))
logging.info('FINAL: Statistics - Exited before end')
print('Warning, continuing')
# close the log file so that we can open a new one
logger = logging.getLogger()
handlers = logger.handlers[:]
for handler in handlers:
handler.close()
logger.removeHandler(handler)
def csv_check_work_tapes(gzip_filename,single_station=None,
single_ground_station=None,logging_level=logging.INFO,processed_dir='.',log_dir='.',delete_previous=True):
"""
Makes a stream file from the gzipped csv file. The timing is based on
the timing in the csv file, and so the seismograms are not yet
continuous.
csv_import() makes streams from the individual csv file.
:type gzip_filename: str
:param gzip_filename: gzipped filename of the CSV file to be read.
:type single_station: str
:param single_station: The name of a single station can be specified (the
entire file is read in first)
:type single_ground_station: int
:param single_station: The name of a single ground station can be specified
(the entire file is read in first)
:rtype: :class:`~obspy.core.stream.Stream`
:return: A ObsPy Stream object.
"""
print('Processing file: ', gzip_filename)
print('Writing to ', processed_dir)
print('Log dir ', log_dir)
log_filename = os.path.basename(gzip_filename)
log_filename = log_filename + '.log'
log_filename = os.path.join(log_dir,log_filename)
print('log filename ', log_filename)
logging.basicConfig(filename=log_filename, filemode='w',
level=logging_level,format='%(message)s')
# reset the global variables
global first_record
first_record = None
global last_record
last_record = None
global rec_initial_total
rec_initial_total = None
global gst_total
gst_total = 0
global total
total = 0
logging.info('############################################')
logging.info(gzip_filename)
logging.info('############################################')
print(gzip_filename)
logging.info('config.low_tolerance={}'.format(config.low_tolerance))
logging.info('config.high_tolerance={}'.format(config.high_tolerance))
logging.info('config.lower_tolerance={}'.format(config.lower_tolerance))
logging.info('config.higher_tolerance={}'.format(config.higher_tolerance))
df = None
df = pd.read_csv(gzip_filename, dtype=str)
if len(df) == 0:
delete_previous = False
if delete_previous:
out_gzip_filename = os.path.basename(gzip_filename)
out_gzip_filename = os.path.join(processed_dir,out_gzip_filename)
delete_wildcard = out_gzip_filename.replace('.csv.gz', '.*')
delete_list = glob.glob(delete_wildcard, recursive=False)
for file1 in delete_list:
if '.log' not in file1:
os.remove(file1)
print('Removing file ', file1)
default_config()
df = initial_cleanup(df)
df = drop_last_frame(df)
initial_report(df)
all_station_order(df,gzip_filename)
df, rec_station_duplicates = all_station_duplicates_v2(df,gzip_filename)
all_flat_seismogram(df,gzip_filename)
if config.initial == False:
df, rec_drop_damaged_total = all_known_errors(df,gzip_filename)
else:
rec_drop_damaged_total = 0
df, rec_damaged_sync_total = all_delete_damaged(df)
# station
# df = all_station_check(df,station_order)
# duplicates are not currently removed (checking at the end instead)
rec_duplicates = 0
# df, rec_duplicates = all_drop_duplicates(df)
detailed_report(df)
# check for non-consecutive stations
# all_check_stations(df)
# split into station and ground station
logging.debug('df total {}'.format(len(df)))
# split the dataframe into station and ground station
df_st_list = all_split(df,gzip_filename)
# rec_missing_total = 0
# rec_final_total = 0
# rec_negative_total = 0
# rec_fixed_frame_total = 0
# rec_adjusted_timestamps_total = 0
# rec_deleted_timestamps_total = 0
# rec_repeated_frame_total = 0
# rec_fixed_simple_timestamp_total = 0
# # timestamps may be adjusted more than once - this gives the final number
# rec_adjusted_timestamps_final_total = 0
rec_final_total = 0
rec_negative_total = 0
rec_clock_flag_total = 0
rec_adjusted_timestamps_final_total = 0
rec_deleted_timestamps_total = 0
rec_missing_total = 0
rec_fixed_frame_total = 0
rec_fixed_simple_timestamp_total = 0
rec_adjusted_timestamps_total = 0
rec_deleted_non_uniq_total = 0
rec_repeated_frame_total = 0
rec_dropped_total = 0
overall_start_times = []
# go through each station and ground station combination
for dict1 in df_st_list:
start_times = []
end_times = []
lengths = []
final_station = []
final_ground_station = []
df_gst = dict1['df_gst']
corr_ground_station = df_gst['corr_ground_station'].iloc[0]
orig_station = df_gst['orig_station'].iloc[0]
orig_timestamp = df_gst['orig_timestamp'].iloc[0]
# logging.info('Temp 8- Length of this section: {}'.format(len(df_gst)))
# the station and timestamp of the last records for the whole
# ground station
config.last_station = dict1['last_station']
config.last_timestamp = dict1['last_timestamp']
config.last_orig_idx = df_gst['orig_idx'].iloc[-1]
# If required, process a single station or ground station (or both)
if single_station is not None:
if orig_station != single_station:
continue
if single_ground_station is not None:
if corr_ground_station != single_ground_station:
continue
# if orig_timestamp != pd.Timestamp('1977-04-20 02:28:58.870000+00:00'):
# print(orig_timestamp)
# continue
logging.info('############ Ground station: {} Station: {} {}'.format(corr_ground_station,orig_station,orig_timestamp))
if len(df_gst) == 0:
continue
global df_orig_shown
df_orig_shown = False
if config.initial:
# use this setting to view large breaks and gaps
station_test_missing_timestamps(df_gst,gzip_filename)
return df_gst, None, 0, 0
else:
station_test_missing_timestamps(df_gst,gzip_filename)
df_original = df_gst.copy()
cumsum_test_list = [10, 20, 90, 180]
# loop through, increasing the number of records in the cumulative sum test
# [the idea is that a big section of records that work together are probably right]
for cumsum_test in cumsum_test_list:
logging.debug('config.cumsum_test={}'.format(config.cumsum_test))
config.cumsum_test = cumsum_test
# each time, start from the original data
df_gst = df_original.copy()
# check the timeseries data and remove any that don't fit
# note that both df_gst and df_dropped are taken from the last one (that hopefully works)
df_gst, df_dropped, df_orig, rec_fixed_frame, rec_fixed_simple_timestamp, rec_adjusted_timestamps, rec_deleted_non_uniq, rec_deleted_timestamps, rec_repeated_frame, compliance_passed = check_compliance(df_gst,gzip_filename)
if cumsum_test > 10:
logging.info('WARNING: Ground station/Station - {} {} Using cumsum_test={}'.format(
corr_ground_station, orig_station,cumsum_test))
if cumsum_test == 180:
logging.debug('------------------')
logging.debug(df_orig.tail().to_string())
logging.debug(df_dropped.tail().to_string())
logging.debug(df_gst.tail().to_string())
logging.debug('------------------')
# # there's no reason to carry on if all records have been deleted
# if len(df_gst) == 0:
# break
# break out if bad records have been deleted (also inlcudes only bad reocrds)
if compliance_passed:
# logging.info('Compliance passed at cumsum_test={}'.format(cumsum_test))
# logging.info(len(df_dropped))
break
# else:
# logging.info('Compliance not passed at cumsum_test={}'.format(cumsum_test))
# logging.info(len(df_dropped))
# logging.debug('--------------------------')
# logging.debug(df_gst.to_string())
# df_orig_shown = True
# logging.debug('--------------------------')
rec_fixed_frame_total += rec_fixed_frame
rec_fixed_simple_timestamp_total += rec_fixed_simple_timestamp
rec_adjusted_timestamps_total += rec_adjusted_timestamps
rec_deleted_non_uniq_total += rec_deleted_non_uniq
rec_deleted_timestamps_total += rec_deleted_timestamps
rec_repeated_frame_total += rec_repeated_frame
if config.initial:
continue
if len(df_gst) > 0:
# find the cumulative sum of the good records
# this looks at any that have already been fixed
df_gst = calculate_cumsum2(df_gst)
logging.info('still there?')
logging.debug(df_gst.to_string())
logging.info('still there?')
df_list1, df_list_bad = split_good_records(df_gst)
for df1 in df_list1:
# make some final checks to make sure it works
df1 = station_final_check(df1, df_orig)
start_time = UTCDateTime(df1['corr_timestamp'].iloc[0])
start_times.append(start_time)
end_time = UTCDateTime(df1['corr_timestamp'].iloc[-1])
end_times.append(end_time)
lengths.append(len(df1))
final_station.append(orig_station)
final_ground_station.append(corr_ground_station)
record_diff_time = end_time - start_time
if record_diff_time > 3600*12 or record_diff_time < 0:
logging.info('SEVERE: Ground station/Station - {} {} Start to end of record longer than 12 hours {} {} ({} s)'.format(
corr_ground_station, orig_station,start_time,end_time,record_diff_time))
print('SEVERE: Ground station/Station - {} {} Start to end of record longer than 12 hours {} {} ({} s)'.format(
corr_ground_station, orig_station,start_time,end_time,record_diff_time))
else:
logging.info('INFO: Ground station/Station - {} {} Start to end of record {} {} ({} s)'.format(
corr_ground_station, orig_station,start_time,end_time,record_diff_time))
df_list2 = split_midnight(df1)
# write the files
for df2 in df_list2:
# write the files
write_files(df2,gzip_filename,processed_dir)
# add up the totals
gst_total += len(df1)
rec_final_total += len(df1)
# make a warning? if there's a warning, make a single severe
# tests on the start times
# +or- 24 hours of each other
# print out all the start - end times - number of records
# not more than 4 hours long
# SEVERE if they are
if len(df_list_bad) > 0:
for df_bad in df_list_bad:
# vertical_stack = pd.concat([survey_sub, survey_sub_last10], axis=0)
df_dropped = pd.concat([df_dropped, df_bad], ignore_index = False)
rec_drop_local = len(df_dropped)
rec_clock_flag_local = (df_dropped['clock_flag'] == 1).sum()
if rec_dropped_total > 0:
if rec_dropped_total < 180:
logging.info('WARNING: Ground station/Station - {} {} - Dropped {} record(s)'.format(
corr_ground_station, orig_station,rec_dropped_total))
else:
logging.info('SEVERE: Ground station/Station - {} {} - Dropped {} record(s)'.format(
corr_ground_station, orig_station,rec_dropped_total))
print('SEVERE: Ground station/Station - {} {} - Dropped {} record(s)'.format(
corr_ground_station, orig_station,rec_dropped_total))
if rec_clock_flag_local > 179:
logging.info('SEVERE: Ground station/Station - {} {} - {} clock flag record(s) have been dropped'.format(
corr_ground_station, orig_station,rec_dropped_total))
print('SEVERE: Ground station/Station - {} {} - {} clock flag record(s) have been dropped'.format(
corr_ground_station, orig_station,rec_dropped_total))
for st, en, l, gr, sta in zip(start_times, end_times, lengths, final_ground_station, final_station):
logging.info('START_TIMES: Ground station/Station - {} {} - {} {} {}'.format(gr, sta, str(st), str(en), l))
logging.info('############################################')
earlier = False
for i, st in enumerate(start_times):
if i > 0:
if st < start_times[i-1]:
earlier = True
if earlier == True:
logging.info('SEVERE: File possibly contains records with the wrong timing')
overall_start_times.extend(start_times)
rec_dropped_total += len(df_dropped)
write_dropped_files(df_dropped,gzip_filename,processed_dir)
rec_clock_flag_total += (df_gst['clock_flag'] == 1).sum()
rec_missing1 = df_gst['orig_no'].isna().sum()
rec_missing_total += rec_missing1
# rec_final_total += len(df_gst)
if rec_missing1 > 0:
logging.info('WARNING: Ground station/Station - {} {} Inserted {} blank record(s)'.format(
corr_ground_station, orig_station,rec_missing1))
# logging.info('##INFORMATION: Ground station/Station - 7 S15########## Ground station: {} Station: {} {}'.format(corr_ground_station,orig_station,orig_timestamp))
#
# logging.info('this is the end ')
# logging.info(df_gst[(df_gst['orig_timestamp'] != df_gst['corr_timestamp']) & (~df_gst['orig_no'].isna())].to_string())
# exit()
rec_adjusted_timestamps_final = ((df_gst['orig_timestamp'] != df_gst['corr_timestamp']) & (~df_gst['orig_no'].isna())).sum()
if rec_adjusted_timestamps_final > 0:
logging.info('WARNING: Ground station/Station - {} {} Adjusted {} timestamp(s) (simple/complex)'.format(
corr_ground_station, orig_station, rec_adjusted_timestamps_final))
rec_adjusted_timestamps_final_total += rec_adjusted_timestamps_final
# df_gst, gaps_long, gaps_8888 = calculate_gaps(df_gst)
if config.initial:
logging.info('############################################')
logging.info('WARNING: Used initial=True')
else:
logging.info('############################################')
earlier = False
for i, st in enumerate(overall_start_times):
if i > 0:
if st < overall_start_times[i-1]:
earlier = True
if earlier == True:
logging.info('SEVERE: File (overall) possibly contains records with the wrong timing')
if len(overall_start_times) >= 2:
overall_start_times.sort()
total_diff_time = overall_start_times[-1] - overall_start_times[0]
if abs(total_diff_time) > 3600*24:
logging.info('SEVERE: Ground station/Station - {} {}: This file is more than 24 hours long: {} s ({:01f}) {} {}'.format(
corr_ground_station, orig_station,total_diff_time,total_diff_time/3600,overall_start_times[0],overall_start_times[-1]))
rec_damaged_total = (rec_deleted_timestamps_total + rec_duplicates +
rec_station_duplicates + rec_drop_damaged_total + rec_dropped_total)
rec_valid_total = rec_final_total - rec_missing_total
if rec_valid_total != 0:
rec_damaged_percentage = 100*(rec_damaged_total/rec_valid_total)
else:
rec_damaged_percentage = 100
if rec_valid_total != 0:
rec_missing_percentage = 100*(rec_missing_total/rec_valid_total)
else:
rec_missing_percentage = 100
rec_valid_of_intial_percentage = 100*(rec_valid_total/rec_initial_total)
logging.info('############################################')
config.extra_ground_stations.sort()
if len(config.extra_ground_stations) > 0:
logging.info('INFO: Final Check - Extra ground stations added {}'.format(config.extra_ground_stations))
if rec_clock_flag_total > 0:
logging.info('WARNING: Final Check - {} clock flag(s)'.format(rec_clock_flag_total))
if rec_negative_total > 0:
logging.info('Negative gaps: {}'.format(
rec_negative_total))
if rec_missing_total > 0:
logging.info('WARNING: Final Check - Inserted {} blank record(s) ({:0.02f}%)'.format(
rec_missing_total,rec_missing_percentage))
if rec_dropped_total > 0:
logging.info('WARNING: Final Check - Dropped {} record(s)'.format(
rec_dropped_total))
if rec_damaged_sync_total > 0:
logging.info('WARNING: Final Check - Removed {} damaged sync code(s)'.format(
rec_damaged_sync_total))
if rec_damaged_total > 0:
logging.info('WARNING: Final Check - Removed {} damaged record(s) ({:0.02f}%) known damaged {} duplicates {} station duplicates {} deleted timestamp(s) {} dropped record(s) {}'.format(
rec_damaged_total,rec_damaged_percentage,rec_drop_damaged_total,rec_duplicates,rec_station_duplicates,
rec_deleted_timestamps_total, rec_dropped_total))
if rec_fixed_frame_total > 0:
logging.info('WARNING: Final Check - Simple adjustments to {} frame number(s)'.format(
rec_fixed_frame_total))
# if rec_fixed_simple_timestamp_total > 0:
# logging.info('WARNING: Final Check - Simple adjustments to {} timestamp(s)'.format(
# rec_fixed_simple_timestamp_total))
# using the final total, which is calculated from the difference
# between corr_timestamp and orig_timestamp
if rec_adjusted_timestamps_final_total > 0:
logging.info('WARNING: Final Check - Adjusted {} timestamp(s) (simple/complex)'.format(
rec_adjusted_timestamps_final_total))
if rec_deleted_non_uniq_total > 0:
logging.info('WARNING: Final Check - {} Non unique record(s) removed'.format(
rec_deleted_non_uniq_total))
if single_station is not None or single_ground_station is not None:
logging.info('FINAL: Processed only {} and {} '.format(single_station, single_ground_station))
logging.info('FINAL: Number of records: {}'.format(rec_final_total))
if rec_valid_of_intial_percentage < 95:
logging.info('FINAL: WARNING Number of valid records: {} ({:0.02f}% of initial)'.format(rec_valid_total, rec_valid_of_intial_percentage))
else:
logging.info('FINAL: Number of valid records: {} ({:0.02f}% of initial)'.format(rec_valid_total, rec_valid_of_intial_percentage))
rec_percent_sync = 100*(rec_damaged_sync_total/rec_initial_total)
rec_percent_damaged = 100*(rec_damaged_total/rec_initial_total)
# making a distinction between sync damaged and other damaged - because there might be some potential to include the other damaged
logging.info('FINAL: Statistics Initial={} Final={} Sync errors={} Percent sync errors={:0.02f}% Dropped due to timing={} Percent dropped={:0.02f}% Inserted={} Final Valid={} Final Valid Percent={:0.02f}%'.format(
rec_initial_total,
rec_final_total,
rec_damaged_sync_total,
rec_percent_sync,
rec_damaged_total,
rec_percent_damaged,
rec_missing_total,
rec_valid_total,
rec_valid_of_intial_percentage))
# FINAL: Number of records: 110581
# WARNING: Final Check - Inserted 2386 blank record(s) (2.21%)
# WARNING: Final Check - Removed 767 damaged record(s) (0.71%) - sync code 767 known damaged 0 duplicates 0 station duplicates 0 deleted timestamp(s) 0
# WARNING: Final Check - Simple adjustments to 1 frame number(s)
# WARNING: Final Check - Adjusted 3 timestamp(s) (simple/complex)
# logging.info('total {}'.format(total))
# logging.info('gst total {}'.format(gst_total))
def write_files(df,gzip_filename,processed_dir):
# wtn.17.19.csv.gz
if len(df) > 0:
corr_ground_station = df['corr_ground_station'].iloc[0]
orig_station = df['orig_station'].iloc[0]
starttime = df['corr_timestamp'].iloc[0]
julday = str('{:03}'.format(starttime.dayofyear))
year = starttime.year
str_starttime = starttime.strftime('%H_%M_%S_%f')
# xa.s12.01.afr.1976.066.1.0.mseed
out_gzip_filename = gzip_filename.replace('.csv.gz', '')
out_gzip_filename = '{}.{}.{}.{}.{}.{}.csv.gz'.format(out_gzip_filename,orig_station,corr_ground_station,year,julday,str_starttime)
out_gzip_filename = os.path.basename(out_gzip_filename)
out_gzip_filename = os.path.join(processed_dir,out_gzip_filename)
print('Writing File ', out_gzip_filename)
df.to_csv(out_gzip_filename,index=False,date_format='%Y-%m-%dT%H:%M:%S.%fZ',quoting=csv.QUOTE_NONNUMERIC)
def split_midnight(df_gst):
# if the datafile crosses midnight, split it
#TODO Note that if there are no valid values around midnight, but the
#dataframe does have values at midnight, the records can start or end with
#the empty ones, which isn't ideal
df_gst['days'] = df_gst.corr_timestamp.dt.normalize()
gb = df_gst.groupby('days')
df_list = [gb.get_group(x) for x in gb.groups]
return df_list
def default_config():
config.extra_ground_stations = []
config.station_order = []
config.last_station=None
config.last_timestamp=None
# the other parameters can be set in the calling file,
# and shouldn't be reset here
def write_dropped_files(df_dropped,gzip_filename,processed_dir):
# wtn.17.19.csv.gz
if (df_dropped is not None) and (len(df_dropped) > 0):
df_dropped.sort_values(by=['orig_idx'], inplace=True)
corr_ground_station = df_dropped['corr_ground_station'].iloc[0]
orig_station = df_dropped['orig_station'].iloc[0]
starttime = df_dropped['corr_timestamp'].iloc[0]
julday = str('{:03}'.format(starttime.dayofyear))
year = starttime.year
str_starttime = starttime.strftime('%H_%M_%S_%f')
out_gzip_filename = gzip_filename.replace('.csv.gz', '')
# out_gzip_filename = '{}.{}.{}.dropped.csv.gz'.format(out_gzip_filename,orig_station,corr_ground_station)
out_gzip_filename = '{}.{}.{}.{}.{}.{}.dropped.csv.gz'.format(out_gzip_filename,orig_station,corr_ground_station,year,julday,str_starttime)
out_gzip_filename = os.path.basename(out_gzip_filename)
out_gzip_filename = os.path.join(processed_dir,out_gzip_filename)
df_dropped.to_csv(out_gzip_filename,index=False,date_format='%Y-%m-%dT%H:%M:%S.%fZ',quoting=csv.QUOTE_NONNUMERIC)
logging.info('WARNING: Ground station/Station - {} {} - Dropped {} records(s)'.format(corr_ground_station,orig_station,len(df_dropped)))
# logging.debug('Dropped files:\n{}'.format(df_dropped.to_string()))
def initial_cleanup(df):
df['orig_timestamp'] = df['orig_timestamp'].astype('datetime64[ns, UTC]')
# main tapes extracted without the S
df['orig_station'].replace('11', 'S11',inplace=True)
df['orig_station'].replace('12', 'S12',inplace=True)
df['orig_station'].replace('14', 'S14',inplace=True)
df['orig_station'].replace('15', 'S15',inplace=True)
df['orig_station'].replace('16', 'S16',inplace=True)
df['orig_station'] = df['orig_station'].astype('string')
if 'bit_synchronizer' in df.columns:
df['bit_synchronizer'] = df['bit_synchronizer'].astype('string')
else:
df['bit_synchronizer'] = pd.NA
df['sync'] = df['sync'].astype('string')
df['orig_no'] = to_Int64(df['orig_no'])
df['clock_flag'] = to_Int64(df['clock_flag'])
df['orig_frame'] = to_Int64(df['orig_frame'])
df['orig_ground_station'] = to_Int64(df['orig_ground_station'])
df['orig_mh1_1'] = to_Int64(df['orig_mh1_1'])
df['orig_mh2_1'] = to_Int64(df['orig_mh2_1'])
df['orig_mhz_1'] = to_Int64(df['orig_mhz_1'])
df['orig_mh1_2'] = to_Int64(df['orig_mh1_2'])
df['orig_mh2_2'] = to_Int64(df['orig_mh2_2'])
df['orig_mhz_2'] = to_Int64(df['orig_mhz_2'])
df['orig_mh1_3'] = to_Int64(df['orig_mh1_3'])
df['orig_mh2_3'] = to_Int64(df['orig_mh2_3'])
df['orig_mhz_3'] = to_Int64(df['orig_mhz_3'])
df['orig_mh1_4'] = to_Int64(df['orig_mh1_4'])
df['orig_mh2_4'] = to_Int64(df['orig_mh2_4'])
df['orig_mhz_4'] = to_Int64(df['orig_mhz_4'])
df['frame'] = to_Int64(df['frame'])
if 'shz_4' in df.columns:
df['shz_4'] = to_Int64(df['shz_4'])
df['shz_6'] = to_Int64(df['shz_6'])
df['shz_8'] = to_Int64(df['shz_8'])
df['shz_10'] = to_Int64(df['shz_10'])
df['shz_12'] = to_Int64(df['shz_12'])
df['shz_14'] = to_Int64(df['shz_14'])
df['shz_16'] = to_Int64(df['shz_16'])
df['shz_18'] = to_Int64(df['shz_18'])
df['shz_20'] = to_Int64(df['shz_20'])
df['shz_22'] = to_Int64(df['shz_22'])
df['shz_24'] = to_Int64(df['shz_24'])
df['shz_26'] = to_Int64(df['shz_26'])
df['shz_28'] = to_Int64(df['shz_28'])
df['shz_30'] = to_Int64(df['shz_30'])
df['shz_32'] = to_Int64(df['shz_32'])
df['shz_34'] = to_Int64(df['shz_34'])
df['shz_36'] = to_Int64(df['shz_36'])
df['shz_38'] = to_Int64(df['shz_38'])
df['shz_40'] = to_Int64(df['shz_40'])
df['shz_42'] = to_Int64(df['shz_42'])
df['shz_44'] = to_Int64(df['shz_44'])
# shz 46 doesn't work for all stations, so replace with null
# if necessary
if 'shz_46' not in df.columns:
df['shz_46'] = pd.NA
df['shz_46'] = to_Int64(df['shz_46'])
df['shz_48'] = to_Int64(df['shz_48'])
df['shz_50'] = to_Int64(df['shz_50'])
df['shz_52'] = to_Int64(df['shz_52'])
df['shz_54'] = to_Int64(df['shz_54'])
df['shz_58'] = to_Int64(df['shz_58'])
df['shz_60'] = to_Int64(df['shz_60'])
df['shz_62'] = to_Int64(df['shz_62'])
df['shz_64'] = to_Int64(df['shz_64'])
else:
logging.info('WARNING: No SHZ values found.')
# replace empty ground station and orig station with values
df['orig_ground_station'].fillna(-1,inplace=True)
df['orig_station'].fillna('S0',inplace=True)
df['orig_frame'].fillna(-99,inplace=True)
df['frame'].fillna(-99,inplace=True)
# add new columns for timestamps
df['corr_timestamp'] = df['orig_timestamp']
df['corr_gap'] = np.NaN
df['frame_change'] = 1
df['corr_gap_count'] = 1
df['corr_ground_station'] = df['orig_ground_station']
df['cumsum'] = 0
# df['begin'] = False
# df['end'] = False
df['begin_end'] = 'None'
df['delta4'] = pd.NA
# df['guess_count'] = pd.NA
df['orig_idx'] = df.index
return df
def drop_last_frame(df):
# drop the last frame if it is empty
# if df['orig_no'].iloc[-60] == 4369 and pd.isna(df['orig_station'].iloc[-60]):
if df['orig_no'].iloc[-60] == 4369 and (df['orig_station'].iloc[-60] == 'S0'):
df = df[:-60]
logging.info('INFO: Last frame removed because it was empty')
else:
logging.info('WARNING: Last frame was not empty (record will probably continue to next csv file)')
return df
def initial_report(df):
global rec_initial_total
logging.info('Total records: {}'.format(len(df)))
rec_initial_total = (df['orig_station'] != 'S17').sum()
logging.info('Total records (excluding S17): {}'.format(rec_initial_total))
df_filter = df[df['orig_station'] != 'S17']
df_filter2 = df_filter[df_filter['sync'] != '1110001001000011101101']
damaged_records = len(df_filter2)
if damaged_records > 0:
logging.info('WARNING: Data Check - {} ({:0.02f}%) damaged record(s) - sync code is incorrect'.format(damaged_records, (100*damaged_records/rec_initial_total)))
# if damaged_records > 200:
#
# logging.info('WARNING: Data Check - {} ({:0.02f}%) damaged record(s) - sync code is incorrect'.format(damaged_records, (100*damaged_records/rec_initial_total)))
# raise Exception
def detailed_report(df):
# logging.info(df['corr_ground_station'].dropna().values.astype('int').tolist())
groups = [ list(group) for key, group in groupby(df['corr_ground_station'].dropna().values.astype('int').tolist())]
logging.info('Ground station, no_of_records')
for group in groups:
logging.info('{}, {}'.format(int(group[0]), len(group)))
missing_timestamps = (df['orig_timestamp'].isna()).sum()
if missing_timestamps > 0:
logging.info('WARNING: Data Check - {} missing timestamp(s)'.format(missing_timestamps))
else:
logging.info('PASSED: Data Check - {} missing timestamp(s)'.format(missing_timestamps))
# missing_frames = (df['frame'] == -99).sum()
# if missing_frames > 0:
# logging.info('WARNING: Data Check - {} missing frame(s)'.format(missing_frames))
missing_clock_flags = df['clock_flag'].isna().sum()
if missing_clock_flags > 0:
logging.info('WARNING: Data Check - {} missing clock flag(s)'.format(missing_clock_flags))
missing_stations = (df['orig_station'] == 'S0').sum()
if missing_stations > 0:
logging.info('WARNING: Data Check - {} missing station(s)'.format(missing_stations))
else:
logging.info('PASSED: Data Check - {} missing station(s)'.format(missing_stations))
missing_ground_stations = (df['corr_ground_station'] == -1).sum()
if missing_ground_stations > 0:
logging.info('WARNING: Data Check - {} missing ground station(s)'.format(missing_ground_stations))
else:
logging.info('PASSED: Data Check - {} missing ground station(s)'.format(missing_ground_stations))
set_clock_flag = (df['clock_flag'] == 1).sum()
if set_clock_flag > 0:
logging.info('WARNING: Data Check - {} clock flag(s)'.format(set_clock_flag))
else:
logging.info('PASSED: Data Check - {} clock flag(s)'.format(set_clock_flag))
global first_record
first_record = df['orig_timestamp'].iloc[0:5].min()
global last_record
last_record = df['orig_timestamp'].iloc[-5:].max()
logging.info('First record: {} Last record: {}'.format(first_record, last_record))
logging.info('First record: {} Last record: {}'.format(UTCDateTime(first_record), last_record))
elapsed = last_record-first_record
if elapsed > pd.Timedelta(hours=12):
logging.info('WARNING: Time Elapsed: {}'.format(elapsed))
else:
logging.info('Time Elapsed: {}'.format(elapsed))
def all_known_errors(df,gzip_filename):
rec_drop_damaged_total = 0
df, rec_drop_damaged1 = all_drop_idx(df, gzip_filename, problem_gzip_filename='wtn.1.3.csv.gz',
orig_idx_start=337105, orig_idx_end=337250,single_station='S12')
rec_drop_damaged_total += rec_drop_damaged1
df, rec_drop_damaged1 = all_drop_data(df, gzip_filename, problem_gzip_filename='wtn.1.41.csv.gz',
start_timestamp ='1976-03-18T21:56:43.634000Z',
end_timestamp='1976-01-06T08:37:33.856000Z',
start_station='S12',
end_station=pd.NA,
corr_ground_station1=1,
corr_ground_station2=pd.NA)
rec_drop_damaged_total += rec_drop_damaged1
df, rec_drop_damaged1 = all_drop_data(df, gzip_filename, problem_gzip_filename='wtn.1.43.csv.gz',
start_timestamp ='1976-06-09T13:08:47.744000Z',
end_timestamp='1976-03-20T09:15:41.240000Z',
start_station=pd.NA,
end_station='S17',
corr_ground_station1=4,
corr_ground_station2=4,
start_orig_no=16,
end_orig_no=16)
df, rec_drop_damaged1 = all_drop_data(df, gzip_filename, problem_gzip_filename='wtn.10.19.csv.gz',
start_timestamp ='1976-08-01T14:55:50.865000Z',
end_timestamp='1976-11-30T00:00:51.674000Z',
start_station='S15',
end_station='S14',
corr_ground_station1=10,
corr_ground_station2=1,
start_orig_no=3395,
end_orig_no=57344)
rec_drop_damaged_total += rec_drop_damaged1
# 70 3395 1976-08-01 14:55:50.865000+00:00 11 S15 1 10
df, rec_drop_damaged1 = all_drop_data(df, gzip_filename, problem_gzip_filename='wtn.10.24.csv.gz',
start_timestamp ='1976-12-02T11:58:04.049000Z',
end_timestamp='1976-01-06T09:12:31.008000Z',
start_station='S12',
end_station=pd.NA,
corr_ground_station1=6,
corr_ground_station2=pd.NA,
start_orig_no=846,
end_orig_no=1792
# begin:
# 846,"1976-12-02T11:58:04.049000Z",1,"S12",0,6,53
# end:
# 1792,"1976-01-06T09:12:31.008000Z",48,"",0,"",8,136,968,8
)
rec_drop_damaged_total += rec_drop_damaged1
# new
df, rec_drop_damaged1 = all_drop_data(df, gzip_filename, problem_gzip_filename='wtn.10.33.csv.gz',
start_timestamp ='1976-01-01T18:01:01.795000Z',
end_timestamp='1976-12-07T18:59:16.887000Z',
start_station=pd.NA,
end_station='S14',
corr_ground_station1=pd.NA,
corr_ground_station2=9,
start_orig_no=3787,
end_orig_no=48
)
# beginning of bad:
# 3787,"1976-01-01T18:01:01.795000Z",23,"",1,"",584,518,448,584,582,512,520,518,0,520,582,576,"00000",3,"1
# end of bad:
# 48,"1976-12-07T18:59:16.887000Z",60,"S14",0,9,499,452,519,500,452,519,500,452,519,500,452,519,"00011",59,
rec_drop_damaged_total += rec_drop_damaged1
df, rec_drop_damaged1 = all_drop_data(df, gzip_filename, problem_gzip_filename='wtn.10.39.csv.gz',
start_timestamp ='1976-12-11T09:14:44.010000Z',
end_timestamp='1976-03-09T21:56:27.395000Z',
start_station='S12',
end_station=pd.NA,
corr_ground_station1=6,
corr_ground_station2=pd.NA)
rec_drop_damaged_total += rec_drop_damaged1
df, rec_drop_damaged1 = all_drop_data(df, gzip_filename, problem_gzip_filename='wtn.10.55.csv.gz',
start_timestamp ='1976-12-21T03:53:04.950000Z',
end_timestamp='1976-12-21T03:52:56.107000Z',
start_station='S15',
end_station='S14',
corr_ground_station1=9,
corr_ground_station2=9,
start_orig_no=339,
end_orig_no=16)