-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPZS_Manager_V1.py
More file actions
1600 lines (1313 loc) · 73.5 KB
/
PZS_Manager_V1.py
File metadata and controls
1600 lines (1313 loc) · 73.5 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
#%%
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 6 18:06:04 2018
@author: bcubrich
SUMMARY
--------------------------------
This code takes audit files for gaseous data and collects the audit and
indicated measurements, then outputs a pipe delimited text file called
'QA_output.txt' that can be directly uploaded to AQS.
INDEX
-------------------------------
1. Imports
2. Global Vars
3. Functions
-functions to get filenames and directories
4. Analysis Main
3. Write to file
-Write the above df to a file
"""
'''---------------------------------------------------------------------------
1. Imports
----------------------------------------------------------------------------'''
#need most of these imports for the code to work
import pandas as pd
import numpy as np
from tkinter import Tk
from tkinter.filedialog import askopenfilename
import os
from tkinter import *
import pyodbc
import datetime as dt
import time
import sys
from bs4 import BeautifulSoup
#from tkinter.filedialog import asksavefilename
from tkinter.filedialog import askdirectory
'''---------------------------------------------------------------------------
2. Global Vars
----------------------------------------------------------------------------'''
global you
global counter
global auto_run
counter=0
'''---------------------------------------------------------------------------
3. Functions
----------------------------------------------------------------------------'''
def get_db_dat(start_date,end_date):
#get data from MS SQL server, AVdata table.
#This is where we keep the AV data at DEQ,
#and I use this function to get a df of data off of the
#server.
driver_names = pyodbc.drivers() #get drivers that will work in the current env.
db='AVData.Reporting.CalibrationDataFull' #this is where the data comes from
#Need to login to the server with these
username=####Redacted, contact bcubrich@utah.gov for details
password=####Redacted, contact bcubrich@utah.gov for details
#create a connection to the server
cnxn = pyodbc.connect(r'DRIVER={'+driver_names[0]+'};'
r'SERVER=168.178.43.244;'
r'DATABASE=AVData;'
r'UID='+username+';PWD='+password+';'
r'timeout=10')
#This is a SQL query that is saved inside of this program as a
#giant block of text. This only thing that needs to be updated are the
#dates over which the query will be performed. You can see that this is the only
#black text in the giant block below.
query="""SELECT 'QA' AS TransactionType, 'I' AS ActionIndicator, '1-Point QC' AS AssessmentType,
1113 As PerformingAgencyCode,
AqsStateCode AS State,
AqsCountyTribalCode AS County,
AqsSiteCode AS Site,
AqsParameterCode AS ParameterCode,
AqsParameterOccuranceCode AS POC,
StartDate AS StartDate,
CAST(CONVERT(varchar,StartDate,112) AS INT) AS AssessmentDate,
--FORMAT(StartDate, 'yyyyMMdd', 'en-US'),
--EndDate,
'1' As AssessmentNumber,
ParameterAqsMethodCode AS MethodCode,
AqsUnitCode AS ReportingUnit,
Value,
ExpectedValue
,
CASE WHEN (Value < (ExpectedValue*0.93)) THEN '7%Low' ELSE '' END AS 'Low7Test',
CASE WHEN (Value < (ExpectedValue*0.9)) THEN '10%Low' ELSE '' END AS 'Low10Test',
CASE WHEN (Value < (ExpectedValue*0.85)) THEN '15%Low' ELSE '' END AS 'Low15Test',
CASE WHEN (Value > (ExpectedValue*1.07)) THEN '7%High' ELSE '' END AS 'High7Test',
CASE WHEN (Value > (ExpectedValue*1.1)) THEN '10%High' ELSE '' END AS 'High10Test',
CASE WHEN (Value > (ExpectedValue*1.15)) THEN '15%High' ELSE '' END AS 'High15Test',
PhaseName
FROM AVData.Reporting.CalibrationDataFull
WHERE SiteAbbreviation IN ('BV','ED','ES','MA','BR','HV','O2','SM','LN','NR','RS','SF','V4','H3','HW','P2','AI','BI','SA','CV','EN','HC','RP')
AND StartDate > '"""+start_date+"""'
AND StartDate < '"""+end_date+"""'
AND ParameterEnabled = 1
AND PhaseEnabled = 1
AND AqsParameterCode != 88313
--AND ExcludeFromReporting = 0
--AND NOT (SiteAbbreviation ='RS' AND ParameterName = 'O3')
--AND ParameterAqsMethodCode != '199'
AND (
PhaseName Like '%[Pp][Rr][Ee]%'
OR ((PhaseName Like '%[Ss][Pp][Aa][Nn]%' OR PhaseName Like '[Ss][Pp][Aa][Nn]%' OR PhaseName Like '[Nn][Oo][_][Ss][Pp][Aa][Nn]%')
OR PhaseName Like '%[Zz][Ee][Rr][Oo]%'
AND AqsParameterCode != 42603
)
)
ORDER BY AqsStateCode,
AqsCountyTribalCode,
AqsSiteCode,
AqsParameterCode,
StartDate"""
#use pandas to execute the query and use the connection to the database we
#created, storing the results in the DataFrame 'df'
df = pd.read_sql_query(query, cnxn)
#some of the df needs to be as strings for the rest of the code to work.
#This is largely because of leading zeros being dropped when the location
#codes are converted to numbers, but also due to some logic later on.
converters={'PerformingAgencyCode':str,'State':str,
'County':str, 'Site':str, 'ParameterCode':str,
'POC':str, 'MethodCode':str, 'ReportingUnit':str,
'ParameterCode':str, 'AssessmentDate':str}
#apply the converters
df=df.astype(converters)
return df #Get back the df you want when this is called.
def Get_PZS_dat():
#This function takes most of the runtime when pressing the button 'run'.
#This function works by looking at all of the PREC, ZERO, SPANs from the
#last year prior to the end_date of the query. It drops this down to a
#list of unique PZSs. Of course this list probably has too many entries,
#including those where the station or instrument has been discontinued, but
#I tried to be inclusive as possible.
#same converters as always
converters={'PerformingAgencyCode':str,'State':str,
'County':str, 'Site':str, 'ParameterCode':str,
'POC':str, 'MethodCode':str, 'ReportingUnit':str,
'ParameterCode':str, 'AssessmentDate':str}
#Want to get data from the database up until now
end_date=dt.datetime.now()
#go back a year from the start date.
start_date=str(end_date-pd.Timedelta('365 days'))[:-3]
end_date=str(dt.datetime.now())[:-3] #drop extra digits
df=get_db_dat(start_date,end_date) #call get_db_dat with start and end date
df=df.astype(converters) #apply converters
#convert the date from assesment date format to 'normal datetime'
df['date_normal']=df['AssessmentDate'].str[4:6]+'-'+df['AssessmentDate'].str[-2:]+'-'+df['AssessmentDate'].str[:4]
#convert that to a datetime
df['datetime']=pd.to_datetime(df['date_normal'])
#create a column with the station name
df['Station']=df['State'] + df['County'] + df['Site']
#make the phase name PRES, PREC, PREZ all the same, because at some sites
#it will get changed part way through, but we want it to be the same
df['PhaseName']=df['PhaseName'].str.replace('PRES','PREC').str.replace('PREZ','PREC')
df=df.fillna(value='0') #convert nans to zeros
#create a paramter that can be used ot drop duplicates
df['DropDup']=df['Station']+df['PhaseName']+ df['ParameterCode']
#drop duplicates down to each phase we want at each station
pzs_df=df.drop_duplicates(subset=['DropDup']).copy()
#create three separate dfs, on for each of PREC, ZERO, SPAN
prec_df=pzs_df[pzs_df['PhaseName'].str.contains('PR')].copy()
span_df=pzs_df[pzs_df['PhaseName'].str.contains('SPAN')].copy()
zero_df=pzs_df[pzs_df['PhaseName'].str.contains('ZERO')].copy()
#dont know what the diff zero should be, so I drop it.
zero_df=zero_df[zero_df['ParameterCode']!='42612']
return (prec_df,span_df,zero_df) #return the three the dfs
def out_dir():
#get the directory where we want to save some files at some point.
filename = askdirectory(title = "Select Save File Path") # Open single file
return filename
'''--------------------------------------------------------------------------
4. Analysis Main
This section focuses on the pandas df 'output_df'. I use this df to store up
all the info needed for an AQS upload that can be easily saved to a pipe
delimited csv, and to create a df we can explore for any pzs fails, etc.
----------------------------------------------------------------------------'''
def pzs_main():
print('Started')
global you
global report_out_path
'''--------------------------------------------------------------------------
4a. Setup needed information
----------------------------------------------------------------------------'''
converters={'PerformingAgencyCode':str,'State':str, #convert some of df to string
'County':str, 'Site':str, 'ParamterCode':str,
'POC':str, 'MethodCode':str, 'ReportingUnit':str,
'ParameterCode':str, 'AssessmentDate':str}
prec_dict={'42101':10, '44201':7, '42401':10,'42601':15, #what s allowable prec %disc.
'42602':15,'42600':15,'42603':15, '42612':15}
span_dict={'42101':10, '44201':7, '42401':10,'42601':10, #what s allowable span %disc.
'42602':10, '42600':10, '42603':10, '42612':10}
param_dict={'42101':'CO', '44201':'O3', '42401':'SO2','42601':'NO', #convert from parameter code to analyte
'42602':'NO2', '42600':'NOy', '42603':'NOx', '42612':'NOy-NO Diff'}
zero_dict_24={'42101':0.41, '44201':0.0031, '42401':0.0031,'42601':0.0031, #allowable zeros values (ppm)
'42602':0.0031,'42600':0.0031,'42603':0.0031, '42612':0.0031}
zero_dict={'42101':0.61, '44201':0.0051, '42401':0.0051,'42601':0.0051, #14 day allowable
'42602':0.0051,'42600':0.0051,'42603':0.0051, '42612':0.0051}
prec_warn_dict={'42101':0.7, '44201':0.7, '42401':0.7,'42601':0.667, #Fraction of allowable considered a warning
'42602':0.667,'42600':0.667,'42603':0.667, '42612':0.667}
span_warn_dict={'42101':0.7, '44201':0.7, '42401':0.7,'42601':0.7,
'42602':0.7, '42600':0.7, '42603':0.7, '42612':0.7}
zero_warn_dict={'42101':0.7, '44201':0.7, '42401':0.7,'42601':0.7,
'42602':0.7, '42600':0.7, '42603':0.7, '42612':0.7}
#Station run's by site symbol instead of station code
run_dict={'BV':'Kati', 'ED':'Kati','ES':'Kati','MA':'Kati',
'BR':'John','HV':'John','O2':'John', 'SM':'John',
'LN':'Shauna', 'NR':'Shauna','RS':'Shauna', 'SF':'Shauna', 'V4':'Shauna',
'H3':'Luke','HW':'Luke','P2':'Luke','AI':'Luke','BI':'Luke','SA':'Luke',
'CV':'Thad','EN':'Thad','HC':'Thad','RP':'Thad'}
#Use this to map the operator to the station. Will need to be updated yearly
station_run_dict={'490110004':'Kati', '490450004':'Kati','490170006':'Kati','490351007':'Kati',
'490030003':'John','490571003':'John','490570002':'John', '490050007':'John',
'490494001':'Shauna', '490354002':'Shauna','490130002':'Shauna', '490495010':'Shauna', '490471004':'Shauna',
'490353013':'Luke','490353006':'Luke','490071003':'Luke','490116001':'Luke','490456001':'Luke','490353005':'Luke',
'490352005':'Thad','490210005':'Thad','490530007':'Thad','490353010':'Thad'}
#I use the following to get information about the site.
site_text="""index,SITE NAME,Site Symbol,State Code,County Code,Site Code,Parameter,Analyt,POC,Method,Unit
0,Brigham City,BR,49,003,0003,44201,(O3),1,087,007
1,Smithfield,SM,49,005,0007,44201,(O3),1,087,007
2,Price #2,P2,49,007,1003,44201,(O3),1,087,007
3,Bountiful #2,BV,49,011,0004,44201,(O3),1,087,007
4,Roosevelt,RS,49,013,0002,,,0,000,000
5,Escalante,ES,49,017,0006,44201,(O3),1,087,007
6,Enoch,EN,49,021,0005,44201,(O3),1,087,007
7,Copperview,CV,49,035,2005,42101,(CO),1,554,007
8,Hawthorne,HW,49,035,3006,44201,(O3),1,087,007
9,Rose Park,RP,49,035,3010,42101,(CO),1,054,007
10,Herriman,H3,49,035,3013,44201,(O3),1,087,007
11,Erda,ED,49,045,0004,44201,(O3),1,087,007
12,Vernal,V4,49,047,1004,44201,(O3),1,047,007
13,Lindon,LN,49,049,4001,42101,(CO),2,593,007
14,Spanish Fork,SF,49,049,5010,44201,(O3),1,087,007
15,Ogden,O2,49,057,0002,42101,(CO),1,054,007
16,Harrisville,HV,49,057,1003,44201,(O3),1,087,007
17,Hurricane,HC,49,053,0007,44201,(O3),1,087,007
18,Antelope Island,AI,49,011,6001,61101,(WS),1,050,012
19,Saltair,SA,49,035,3005,61101,(WS),1,050,012
20,Near Road,NR,49,035,4002,44201,(O3),1,087,007
21,Magna,MA,49,035,1007,44201,(O3),1,087,007
22,Badger Island,BI,49,045,6001,44201,(O3),1,087,007"""
#sites_df is information about the site that we currently have. If they aren't
#in this df then I can't print the name and sybmbol of the site late.
#The other information is just extra because I used this in another script
sites_df=pd.DataFrame()
for line in site_text.split('\n'): #Split site_text into lines and create a df out of them
temp_df=pd.DataFrame(line.split(',')).T
sites_df=sites_df.append(temp_df) #append each line in site_text to sites_df
sites_df=sites_df.set_index(0)
sites_df.columns=sites_df.loc['index',:]
sites_df=sites_df.drop('index', axis='index')
#need to check if the script was triggered by a human or automaticallty (at 5:30 am)
if auto_run==0: #human ran
#if it is human ran then we will assume that we want to look a month on either
#side of thier query for long lastin PZS gaps. In the end the script
#will look at PZS failures in the user identified date range, but
#will look at the date range +/-30 days for PZS gaps.
av_start=str(pd.to_datetime(av_date1)-pd.Timedelta('30 days'))+'.000'
av_end=str(pd.to_datetime(av_date2)+pd.Timedelta('30 days'))+'.000'
elif auto_run==1: #autoran
#if autoran we want to look for >= two week times gaps a month before
#the query started. The script already makes av_date1 two weeks before
#todays date. We will go back 17 days to cover a '31 day month'
#in the end, the script will look at two weeks of PZS fails and
#a month of two week gaps when autoran
av_start=str(av_date1-pd.Timedelta('17 days'))[:-3]
av_end=str(av_date2)[:-3]
output_df=get_db_dat(av_start,av_end) #query database for PZS data
#same as above. Convert dates to 'normal' american style, get a datetime
output_df['date_normal']=output_df['AssessmentDate'].str[4:6]+'-'+output_df['AssessmentDate'].str[-2:]+'-'+output_df['AssessmentDate'].str[:4]
output_df['datetime']=pd.to_datetime(output_df['date_normal'])
#get a unique station id for each site.
output_df['Station']=output_df['State'] + output_df['County'] + output_df['Site']
#Do you want to organize the output by run?
if run_org==1: #yes, organize by run
#going to need to use the current 'station_run_dict' to see what runs
#belong to whom. We can use this later to sort the df, and print who's
#run is who's in the email.
output_df['Run']=output_df['Station'].map(station_run_dict)
else: #don't organize by run? We'll just organize by station ID then.
output_df['Run']=output_df['Station']
#doing the replacement again so that any spell of Precision will now be PREC
output_df['PhaseName']=output_df['PhaseName'].str.replace('PRES','PREC').str.replace('PREZ','PREC')
'''----------------------------------------------------------------------------
4b. Check for failures and Add to df
---------------------------------------------------------------------------'''
output_df=output_df.fillna(value='0')
#max_pzs means the absolute value of the %disc between obs and exp
#that the EPA will allow for us to consider the data valid. Need to use
#dictionaries to apply this. That way later we can do a simple pandas+
#np.where() statement to see if the current PZS passed it's allowed value.
#Of course in the case of zeros you need to look at the ABS value allowed,
#not a % disc.The next 10 line for loop + if statements handles this.
max_pzs=[] #list to store the max allowed for each line in df
for param_code, ps in zip(output_df['ParameterCode'],output_df['PhaseName']):
if 'prec' in ps.lower() or 'pres' in ps.lower() or 'prez' in ps.lower():
max_pzs.append(prec_dict.get(param_code))
elif 'span' in ps.lower():
max_pzs.append(span_dict.get(param_code))
elif 'zero' in ps.lower():
max_pzs.append(zero_dict_24.get(param_code))
else:
max_pzs.append('error!!!')
#append the max allowable list created above to the df
output_df['MaxAllowed']=max_pzs
#simply calculate the percent disc.
output_df['PZS_diff']=(output_df['Value']-output_df['ExpectedValue'])/output_df['ExpectedValue']*100
#also calculate it by rounding. at the 1's place. Bo may choose to argue that
#This is the prefered value.
output_df['PZS_diff_round']=np.round(output_df['PZS_diff'], decimals=0)
#float that biz so we can do math. Mathematical!!
output_df['MaxAllowed']=output_df['MaxAllowed'].apply(float)
#some values are in ppb. This causes issues with zero checking. Need
#to check the "UNIT" code to see if it in ppb or ppm.
output_df['Value']=np.where((output_df['ReportingUnit'].str.contains('008'))&
(output_df['PhaseName'].str.contains('ZERO')),
output_df['Value']/1000,output_df['Value'])
#now we need to check if the PZS is passed or not. This should be doable
#in a doubly nested np.where() statement, but I couldn't get it to work.
#this messy looking set of if's in a for loop does the same job.
pzs_check=[] #list to store pass/fails for each line in output_df
#gonna loop each line in output_df, but just need to look at a few params
#A flossier way to do this might be by using df.iterrows.
#sort of annoying cuz the whole point of creating 'output_df['MaxAllowed']'
#was to do this with np.where, which is what I used to do, but now we need
#to recursilvely check for failures, then for warnings, then call it a pass.
for phase, value, diff, allowed, param in zip(output_df['PhaseName'],
output_df['Value'],
output_df['PZS_diff'],
output_df['MaxAllowed'],
output_df['ParameterCode']):
#again, if we could do np.where this would be easy, but now we need to
#check what kind of PZS each entry is, and use dictionaries to check for
#passes and fails.
if 'prec' in phase.lower():
if np.abs(diff)>=allowed:
pzs_check.append('FAIL!!!')
elif np.abs(diff)>=allowed*prec_warn_dict.get(param): #multiply by fraction to get correct warning levels
pzs_check.append('WARNING')
else:
pzs_check.append('PASS')
elif 'span' in phase.lower():
if np.abs(diff)>=allowed:
pzs_check.append('FAIL!!!')
elif np.abs(diff)>=allowed*span_warn_dict.get(param): #multiply by fraction to get correct warning levels
pzs_check.append('WARNING')
else:
pzs_check.append('PASS')
elif 'zero' in phase.lower():
if np.abs(value)>=allowed:
pzs_check.append('FAIL!!!')
elif np.abs(value)>=allowed*zero_warn_dict.get(param):
pzs_check.append('WARNING')
else:
pzs_check.append('PASS')
else:
pzs_check.append('No Match')
#append pzs_check to the df
output_df['PZS_Check']= pzs_check
#double check checks if we could pass the pzs of we used rounding instead of
#the raw value.
output_df['PZS_DoubleCheck']=np.where((np.abs(output_df['PZS_diff_round'])>output_df['MaxAllowed'])&\
(~output_df['PhaseName'].str.contains('ZERO')),'FAIL!!!','PASS')
output_df['PZS_DoubleCheck']=np.where((np.abs(output_df['Value'])>output_df['MaxAllowed'])&\
(output_df['PhaseName'].str.contains('ZERO')),'FAIL!!!',output_df['PZS_DoubleCheck'])
#pzs_fail is a list of failed PZSs, so we can report them later.
pzs_fail_df=output_df[output_df['PZS_Check']=='FAIL!!!'].copy()
#next split of the failures into each kind. This will be useful when
#we go to write the automated email later.
prec_fail_df=pzs_fail_df[pzs_fail_df['PhaseName'].str.contains('PR')].copy()
span_fail_df=pzs_fail_df[pzs_fail_df['PhaseName'].str.contains('SPAN')].copy()
# span_fail_df=span_fail_df[span_fail_df['ParameterCode']!='42612'].copy()
zero_fail_df=pzs_fail_df[pzs_fail_df['PhaseName'].str.contains('ZERO')].copy()
zero_fail_df=zero_fail_df[zero_fail_df['ParameterCode']!='42612']
#we also need a list of all the warning by PZS for the same reason.
#Also, I drop NO-NOy diff zeros cuz that value is calculated.
pzs_warn_df=output_df[output_df['PZS_Check']=='WARNING'].copy()
prec_warn_df=pzs_warn_df[pzs_warn_df['PhaseName'].str.contains('PR')].copy()
span_warn_df=pzs_warn_df[pzs_warn_df['PhaseName'].str.contains('SPAN')].copy()
zero_warn_df=pzs_warn_df[pzs_warn_df['PhaseName'].str.contains('ZERO')].copy()
zero_warn_df=zero_warn_df[zero_warn_df['ParameterCode']!='42612']
'''-------------------------------------------------------------------------
4c. Any Two Week Gap in Last month check
---------------------------------------------------------------------------'''
#pass_df contains all the passing PZSs
pass_df=output_df[output_df['PZS_Check']!='FAIL!!!'].sort_values(['Run','Site','ParameterCode','PhaseName','AssessmentDate']).copy()
#per BO's request I also have to keep track of cases where rounding saves the day
pass_round_df=output_df[output_df['PZS_DoubleCheck']!='FAIL!!!'].copy()
#this text variable is how we will write the email at the end
two_week_gaps_text='<br><b><u>TWO WEEK GAPS IN PAST MONTH</u></b><br><br>'
#technically as long as we get a PZS anytime on the 14th day it count's
#so a two week gap is really 15 days.
gap = pd.Timedelta('15 days')
#I want to know how much time we lose due to PZS fails, and if we cna save time by rounding
gap_count=0
save_count=0
save_time=0
lost_time=0
kati_counter=0
john_counter=0
shauna_counter=0
luke_counter=0
thad_counter=0
#for loop is going ot look at each station one at a time. Then, within that
#it needs to look at each "phasename', which is eahc PZS for each parameter
for site in pass_df['Station'].unique():
PZS_temp=pass_df[(pass_df['Station']==site)].copy()
site_name=sites_df[(sites_df['County Code']==PZS_temp['County'].values[0])&(sites_df['Site Code']==site[-4:])]
site_name='{} ({}, '.format(site_name['SITE NAME'].values[0].strip(),site_name['Site Symbol'].values[0])
#this is the loop for each phasename
for param in pass_df['PhaseName'].unique():
#sort the dates within the passing PZSs
PZS_date=pass_df[(pass_df['PhaseName']==param) & (pass_df['Station']==site)].StartDate.sort_values().copy()
#loop through each date in the sorted list and see if the timedelta
#is greater than 15.
for date1, date2 in zip(PZS_date, PZS_date[1:]):
date1=date1
date2=date2
delta=pd.to_datetime(date2)-pd.to_datetime(date1)
if delta>gap:
#don't need these print statements for the exe version
gap_count+=1
run=station_run_dict.get(site)
if run=='Kati':
kati_counter+=1
if kati_counter==1:
two_week_gaps_text+=(" <br>Kati's Run<br>")
if run=='John':
john_counter+=1
if john_counter==1:
two_week_gaps_text+=(" John's Run<br>")
if run=='Shauna':
shauna_counter+=1
if shauna_counter==1:
two_week_gaps_text+=(" <br>Shauna's Run<br>")
if run=='Luke':
luke_counter+=1
if luke_counter==1:
two_week_gaps_text+=(" <br>Luke's Run<br>")
if run=='Thad':
thad_counter+=1
if thad_counter==1:
two_week_gaps_text+=(" <br>Thad's Run<br>")
two_week_gaps_text+=r' At {} {}) the parameter {} ({}) has a gap '\
r'of {:.2f} days between {} and {}. Null '\
r'hourly data between these dates.<br>'\
.format(site_name,site, param, param_dict.get(param),(delta.days + delta.seconds/86400), date1, date2)
round_test_df=pass_round_df[(pass_round_df['StartDate']>=pd.to_datetime(date1))&
(pass_round_df['StartDate']<=pd.to_datetime(date2))&
(pass_round_df['Station']==site)&
(pass_round_df['PhaseName']==param)]
exact_test_df=pass_df[(pass_df['StartDate']>=pd.to_datetime(date1))&
(pass_df['StartDate']<=pd.to_datetime(date2))&
(pass_df['Station']==site)&
(pass_df['PhaseName']==param)]
lost_time+=delta.days + delta.seconds/86400
# if len(round_test_df)==len(exact_test_df): print('\n')
losses=0
if len(round_test_df)>len(exact_test_df):
save_time+=delta.days + delta.seconds/86400
PZS_date=pass_round_df[(pass_round_df['PhaseName']==param) & (pass_round_df['Station']==site)].StartDate.sort_values().copy()
# print('--Some data in this interval can be saved by scientific rounding.')
two_week_gaps_text+=' --Some data in this interval can be saved by scientific rounding.<br>'
for date1, date2 in zip(PZS_date, PZS_date[1:]):
date1=date1
date2=date2
delta2=pd.to_datetime(date2)-pd.to_datetime(date1)
# saved_days=delta.days-delta2.days
if delta2>gap:
# print(r'**The data from {} to {} cannot be saved'\
# r' by scientific rounding. Still, {} days were lost in this range.'\
# .format(date1,date2,delta2))
save_time+=-(delta2.days + delta2.seconds/86400)
two_week_gaps_text+=(r' **The data from {} to {} cannot be saved'\
r' by scientific rounding. Still, {} days were lost in this range.<br>'.format(date1,date2,delta2))
losses+=1
if losses==0:
# print('**In fact, all data in this range can be saved. {} days saved.'.format(delta))
two_week_gaps_text+='**In fact, all data in this range can be saved. {} days saved.'.format(delta)
save_count+=1
# print('\n')
# print(delta)
# if gap_count>0:
# print ('WARNING!!!!!!!!')
# print ("Some stations contain gaps greater than 14 days, be sure to null the appropriate data")
# if float(lost_time)>0: saved='{:.2f}%'.format(save_time/(lost_time)*100)
'''----------------------------------------------------------------------------
5. Create Email Messages
---------------------------------------------------------------------------'''
''' 5a. Create Span Email Text '''
'''-------------------------------------------------------------------------'''
########################
#Repeat starts here
########################
#Now we wa gonna email out all the failed entries so that can be further QCed
span_text='<b><u>SPAN FAILURES AND WARNINGS</u></b><br><br>'
#In some cases we extended the dfs to much further than the interval of
#interest, so we gotta chop it back down. We also gotta sort by run.
span_fail_df=span_fail_df[span_fail_df['datetime']>=pd.to_datetime(cut_date1)]
span_fail_df=span_fail_df[span_fail_df['datetime']<=pd.to_datetime(cut_date2)]
span_fail_df=span_fail_df.sort_values(['Run','Site','ParameterCode','PhaseName','AssessmentDate'])
#need this so we can print who's run it is only once, instead of n_fail+n_warn times per operator
kati_counter=0
john_counter=0
shauna_counter=0
luke_counter=0
thad_counter=0
#loop through all the failures and write an email line for each one.
for state, county, site, parameter, phase, date, diff, obs, exp, allow, run in zip(span_fail_df['State'],
span_fail_df['County'],
span_fail_df['Site'],
span_fail_df['ParameterCode'],
span_fail_df['PhaseName'],
span_fail_df['StartDate'],
span_fail_df['PZS_diff'],
span_fail_df['Value'],
span_fail_df['ExpectedValue'],
span_fail_df['MaxAllowed'],
span_fail_df['Run']):
#one way to get the site symbol of each site
site_name=sites_df[(sites_df['County Code']==county)&(sites_df['Site Code']==site)]
site_name=site_name['Site Symbol'].values[0]
#yeah, so. All these if's are katies fault, and are needed to print out who's
#run the email is on. One day I need to think of a good way to generalize
#all of this. Probably you could have an enrty feild where you can
#input all the run operators and their fields and then just go through the
#list one by one with a for loop that is as long as there are operatores.
#once again, the if's just make sure that the run operators name is printed once and ony once.
if run=='Kati':
kati_counter+=1
if kati_counter==1:
span_text+=(" <br>Kati's Run<br>")
if run=='John':
john_counter+=1
if john_counter==1:
span_text+=(" John's Run<br>")
if run=='Shauna':
shauna_counter+=1
if shauna_counter==1:
span_text+=(" <br>Shauna's Run<br>")
if run=='Luke':
luke_counter+=1
if luke_counter==1:
span_text+=(" <br>Luke's Run<br>")
if run=='Thad':
thad_counter+=1
if thad_counter==1:
span_text+=(" <br>Thad's Run<br>")
#the 'ifs' here are so that failures today will be highlighted in the email.
#This is the section of code that actually write the email statement for each line
color='#ffb3b3'
if str(date)[:10]==str(dt.datetime.now())[:10]: color='#ff3333'
span_text+=' <span style="background-color: '+color+'">'
span_text+=(' <b>{}</b> - {} ({}) fail {:.2f}%. (of \u00B1{:.2f}) at {}. Obs.={:.4f}, Exp.={:.4f}</span><br>'
.format(site_name, param_dict.get(parameter),phase, diff, allow, date.strftime("%Y-%m-%d %H:%S"), obs, exp))
########################
#Repeat ends here
########################
########################################
#see repeat above for following 56 lines
########################################
span_warn_df=span_warn_df[span_warn_df['datetime']>=pd.to_datetime(cut_date1)]
span_warn_df=span_warn_df[span_warn_df['datetime']<=pd.to_datetime(cut_date2)]
span_warn_df=span_warn_df.sort_values(['Run','Site','ParameterCode','PhaseName','AssessmentDate'])
span_text+='<br>'
kati_counter=0
john_counter=0
shauna_counter=0
luke_counter=0
thad_counter=0
for state, county, site, parameter, phase, date, diff, obs, exp, allow, run in zip(span_warn_df['State'],
span_warn_df['County'],
span_warn_df['Site'],
span_warn_df['ParameterCode'],
span_warn_df['PhaseName'],
span_warn_df['StartDate'],
span_warn_df['PZS_diff'],
span_warn_df['Value'],
span_warn_df['ExpectedValue'],
span_warn_df['MaxAllowed'],
span_warn_df['Run']):
site_name=sites_df[(sites_df['County Code']==county)&(sites_df['Site Code']==site)]
site_name=site_name['Site Symbol'].values[0]
if run=='Kati':
kati_counter+=1
if kati_counter==1:
span_text+=(" <br>Kati's Run<br>")
if run=='John':
john_counter+=1
if john_counter==1:
span_text+=(" John's Run<br>")
if run=='Shauna':
shauna_counter+=1
if shauna_counter==1:
span_text+=(" <br>Shauna's Run<br>")
if run=='Luke':
luke_counter+=1
if luke_counter==1:
span_text+=(" <br>Luke's Run<br>")
if run=='Thad':
thad_counter+=1
if thad_counter==1:
span_text+=(" <br>Thad's Run<br>")
color='#ffffcc'
if str(date)[:10]==str(dt.datetime.now())[:10]: color='#ffff00'
span_text+=' <span style="background-color: '+color+'">'
span_text+=(' <b>{}</b> - {} ({}) warning {:.2f}%. (of \u00B1{:.2f}) at {}. Obs.={:.4f}, Exp.={:.4f}</span><br>'
.format(site_name, param_dict.get(parameter),phase, diff, allow, date.strftime("%Y-%m-%d %H:%S"), obs, exp))
#%%
''' 5b. Create Precision Email Text '''
'''-------------------------------------------------------------------------'''
########################################
#see repeat above for following 56 lines
########################################
prec_fail_df=prec_fail_df[prec_fail_df['datetime']>=pd.to_datetime(cut_date1)]
prec_fail_df=prec_fail_df[prec_fail_df['datetime']<=pd.to_datetime(cut_date2)]
prec_fail_df=prec_fail_df.sort_values(['Run','Site','ParameterCode','PhaseName','AssessmentDate'])
prec_text='<br><b><u>PRECISION FAILURES AND WARNINGS</u></b><br><br>'
kati_counter=0
john_counter=0
shauna_counter=0
luke_counter=0
thad_counter=0
for state, county, site, parameter, phase, date, diff, obs, exp, allow,run in zip(prec_fail_df['State'],
prec_fail_df['County'],
prec_fail_df['Site'],
prec_fail_df['ParameterCode'],
prec_fail_df['PhaseName'],
prec_fail_df['StartDate'],
prec_fail_df['PZS_diff'],
prec_fail_df['Value'],
prec_fail_df['ExpectedValue'],
prec_fail_df['MaxAllowed'],
prec_fail_df['Run']):
site_name=sites_df[(sites_df['County Code']==county)&(sites_df['Site Code']==site)]
site_name=site_name['Site Symbol'].values[0]
if run=='Kati':
kati_counter+=1
if kati_counter==1:
prec_text+=(" <br>Kati's Run<br>")
if run=='John':
john_counter+=1
if john_counter==1:
prec_text+=(" John's Run<br>")
if run=='Shauna':
shauna_counter+=1
if shauna_counter==1:
prec_text+=(" <br>Shauna's Run<br>")
if run=='Luke':
luke_counter+=1
if luke_counter==1:
prec_text+=(" <br>Luke's Run<br>")
if run=='Thad':
thad_counter+=1
if thad_counter==1:
prec_text+=(" <br>Thad's Run<br>")
color='#ffb3b3'
if str(date)[:10]==str(dt.datetime.now())[:10]: color='#ff3333'
prec_text+=' <span style="background-color: '+color+'">'
prec_text+=('<b>{}</b> - {} ({}) fail {:.2f}%. (of \u00B1{:.2f}) at {}. Obs.={:.4f}, Exp.={:.4f}</span><br>'
.format(site_name, param_dict.get(parameter),phase, diff, allow, date.strftime("%Y-%m-%d %H:%M"), obs, exp))
########################################
#see repeat above for following 56 lines
########################################
prec_warn_df=prec_warn_df[prec_warn_df['datetime']>=pd.to_datetime(cut_date1)]
prec_warn_df=prec_warn_df[prec_warn_df['datetime']<=pd.to_datetime(cut_date2)]
prec_warn_df=prec_warn_df.sort_values(['Run','Site','ParameterCode','PhaseName','AssessmentDate'])
prec_text+='<br>'
kati_counter=0
john_counter=0
shauna_counter=0
luke_counter=0
thad_counter=0
for state, county, site, parameter, phase, date, diff, obs, exp, allow,run in zip(prec_warn_df['State'],
prec_warn_df['County'],
prec_warn_df['Site'],
prec_warn_df['ParameterCode'],
prec_warn_df['PhaseName'],
prec_warn_df['StartDate'],
prec_warn_df['PZS_diff'],
prec_warn_df['Value'],
prec_warn_df['ExpectedValue'],
prec_warn_df['MaxAllowed'],
prec_warn_df['Run']):
site_name=sites_df[(sites_df['County Code']==county)&(sites_df['Site Code']==site)]
site_name=site_name['Site Symbol'].values[0]
if run=='Kati':
kati_counter+=1
if kati_counter==1:
prec_text+=(" <br>Kati's Run<br>")
if run=='John':
john_counter+=1
if john_counter==1:
prec_text+=(" John's Run<br>")
if run=='Shauna':
shauna_counter+=1
if shauna_counter==1:
prec_text+=(" <br>Shauna's Run<br>")
if run=='Luke':
luke_counter+=1
if luke_counter==1:
prec_text+=(" <br>Luke's Run<br>")
if run=='Thad':
thad_counter+=1
if thad_counter==1:
prec_text+=(" <br>Thad's Run<br>")
color='#ffffcc'
if str(date)[:10]==str(dt.datetime.now())[:10]: color='#ffff00'
prec_text+=' <span style="background-color: '+color+'">'
prec_text+=('<b>{}</b> - {} ({}) warning {:.2f}%. (of \u00B1{:.2f}) at {}. Obs.={:.4f}, Exp.={:.4f}</span><br>'
.format(site_name, param_dict.get(parameter),phase, diff, allow, date.strftime("%Y-%m-%d %H:%M"), obs, exp))
'''-------------------------------------------------------------------------'''
''' 5c. Create Zero Email Text '''
'''-------------------------------------------------------------------------'''
########################################
#see repeat above for following 56 lines
########################################
zero_fail_df=zero_fail_df[zero_fail_df['datetime']>=pd.to_datetime(cut_date1)]
zero_fail_df=zero_fail_df[zero_fail_df['datetime']<=pd.to_datetime(cut_date2)]
zero_fail_df=zero_fail_df.sort_values(['Run','Site','ParameterCode','PhaseName','AssessmentDate'])
zero_text='<br><b><u>ZERO FAILURES AND WARNINGS</u></b><br><br>'
kati_counter=0
john_counter=0
shauna_counter=0
luke_counter=0
thad_counter=0
for state, county, site, parameter, phase, date, diff, obs, exp, allow, run in zip(zero_fail_df['State'],
zero_fail_df['County'],
zero_fail_df['Site'],
zero_fail_df['ParameterCode'],
zero_fail_df['PhaseName'],
zero_fail_df['StartDate'],
zero_fail_df['PZS_diff'],
zero_fail_df['Value'],
zero_fail_df['ExpectedValue'],
zero_fail_df['MaxAllowed'],
zero_fail_df['Run']):
site_name=sites_df[(sites_df['County Code']==county)&(sites_df['Site Code']==site)]
site_name=site_name['Site Symbol'].values[0]
if run=='Kati':
kati_counter+=1
if kati_counter==1:
zero_text+=(" <br>Kati's Run<br>")
if run=='John':
john_counter+=1
if john_counter==1:
zero_text+=(" John's Run<br>")
if run=='Shauna':
shauna_counter+=1
if shauna_counter==1:
zero_text+=(" <br>Shauna's Run<br>")
if run=='Luke':
luke_counter+=1
if luke_counter==1:
zero_text+=(" <br>Luke's Run<br>")
if run=='Thad':
thad_counter+=1
if thad_counter==1:
zero_text+=(" <br>Thad's Run<br>")
color='#ffb3b3'
if str(date)[:10]==str(dt.datetime.now())[:10]: color='#ff3333'
zero_text+=' <span style="background-color: '+color+'">'
zero_text+=('<b>{}</b> - {} ({}) fail {:.6f}. (of \u00B1{:.4f}) at {}</span><br>'
.format(site_name, param_dict.get(parameter),phase, obs, zero_dict.get(parameter), date))
kati_counter=0
john_counter=0
shauna_counter=0
luke_counter=0
thad_counter=0
########################################
#see repeat above for following 56 lines
########################################
zero_warn_df=zero_warn_df[zero_warn_df['datetime']>=pd.to_datetime(cut_date1)]
zero_warn_df=zero_warn_df[zero_warn_df['datetime']<=pd.to_datetime(cut_date2)]
zero_warn_df=zero_warn_df.sort_values(['Run','Site','ParameterCode','PhaseName','AssessmentDate'])
zero_text+='<br>'
for state, county, site, parameter, phase, date, diff, obs, exp, allow, run in zip(zero_warn_df['State'],
zero_warn_df['County'],
zero_warn_df['Site'],
zero_warn_df['ParameterCode'],
zero_warn_df['PhaseName'],
zero_warn_df['StartDate'],
zero_warn_df['PZS_diff'],
zero_warn_df['Value'],
zero_warn_df['ExpectedValue'],
zero_warn_df['MaxAllowed'],
zero_warn_df['Run']):
site_name=sites_df[(sites_df['County Code']==county)&(sites_df['Site Code']==site)]
site_name=site_name['Site Symbol'].values[0]
if run=='Kati':
kati_counter+=1
if kati_counter==1:
zero_text+=(" <br>Kati's Run<br>")
if run=='John':
john_counter+=1
if john_counter==1:
zero_text+=(" John's Run<br>")
if run=='Shauna':
shauna_counter+=1
if shauna_counter==1:
zero_text+=(" <br>Shauna's Run<br>")
if run=='Luke':
luke_counter+=1
if luke_counter==1:
zero_text+=(" <br>Luke's Run<br>")
if run=='Thad':
thad_counter+=1
if thad_counter==1:
zero_text+=(" <br>Thad's Run<br>")
color='#ffffcc'
if str(date)[:10]==str(dt.datetime.now())[:10]: color='#ffff00'
zero_text+=' <span style="background-color: '+color+'">'
zero_text+=('<b>{}</b> - {} ({}) warning {:.6f}. (of \u00B1{:.4f}) at {}</span><br>'
.format(site_name, param_dict.get(parameter),phase, obs, zero_dict.get(parameter), date))
'''----------------------------------------------------------------------------
6. Check another way for missings and Add to df
---------------------------------------------------------------------------'''
#df_all = xls_df.merge(zero_df, on=['Station','PhaseName'],