mpcaHydro 2.1.0__py3-none-any.whl → 2.2.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mpcaHydro/data/WISKI_QUALITY_CODES.csv +71 -0
- mpcaHydro/data/outlet.duckdb +0 -0
- mpcaHydro/data/stations_EQUIS.gpkg +0 -0
- mpcaHydro/data/stations_wiski.gpkg +0 -0
- mpcaHydro/data_manager.py +172 -292
- mpcaHydro/equis.py +31 -22
- mpcaHydro/etlSWD.py +21 -15
- mpcaHydro/outlets.py +367 -0
- mpcaHydro/reports.py +80 -0
- mpcaHydro/warehouse.py +525 -17
- mpcaHydro/warehouseManager.py +55 -0
- mpcaHydro/{WISKI.py → wiski.py} +97 -17
- mpcaHydro/xref.py +74 -0
- {mpcahydro-2.1.0.dist-info → mpcahydro-2.2.1.dist-info}/METADATA +3 -1
- mpcahydro-2.2.1.dist-info/RECORD +23 -0
- mpcahydro-2.1.0.dist-info/RECORD +0 -15
- {mpcahydro-2.1.0.dist-info → mpcahydro-2.2.1.dist-info}/WHEEL +0 -0
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
quality_code,Text,Description,Active
|
|
2
|
+
0,Unchecked,Unchecked data in progress or data that is not quality coded as part of the workup. Default coding for shifts so the quality codes from Level and Ratings are used for discharges. ,1
|
|
3
|
+
3,Instantaneous,Instantaneous groundwater measurements or sampled date for load stations.,1
|
|
4
|
+
5,Excellent,Discharge measurements that are excellent.,1
|
|
5
|
+
8,Reliable Interpolation,The value of the data point is an interpolation between adjacent points. Code used for filling gaps less than 4 hours or with no change in data trend likely based on reference information.,1
|
|
6
|
+
10,Good,Time series data that tracks well and requires no corrections or corrections of very small magnitude or timeseries data that has been reviewed and accepted for precipitation and groundwater level. Also used for discharge measurements and rating points. ,1
|
|
7
|
+
15,Fair,Time series data that tracks fairly well and requires some corrections of relatively small magnitude. Also used for discharge measurements and rating points. ,1
|
|
8
|
+
20,Poor,Time series data that tracks poorly and requires significant or many corrections. Also used for discharge measurements and rating points. ,1
|
|
9
|
+
27,Questionable,"Timeseries data or discharge measurements that are questionable due to operator error, equipment error, etc). Extra scrutiny should be used for these data. ",1
|
|
10
|
+
28,Unknown data quality,"Unknown quality of time series data, ratings or discharge measurements.",1
|
|
11
|
+
29,Modeled,"Time-series data, rating point or discharge from a reliable mathematical and\or computer model. ",1
|
|
12
|
+
34,Estimated,"Time-series data estimated from reference traces, models or extrapolation of the rating curve using supporting data and up to two times the maximum measured discharge.",1
|
|
13
|
+
35,Unreliable,Time-series data computed with a rating extrapolated without supporting data or beyond two times the maximum measured discharge without a model.,1
|
|
14
|
+
36,Threshold Exceedance,"Time-series data may be beyond the measuring limits of the monitoring equipment, or outside the bounds of historical extremes.",1
|
|
15
|
+
40,Default import code,WISKI default coding for gaugings. ,1
|
|
16
|
+
45,Approved Ext Data,"External data that has been graded externally as ""Approved"".",1
|
|
17
|
+
48,Unknown Ext Data,External data that has been graded internally as “Unknown”.,1
|
|
18
|
+
49,Estimated Ext Data,External data that has been graded externally as “Estimated.” Typically this is finalized ice data.,1
|
|
19
|
+
50,Provisional Ext Data,External data that has been graded internally or externally as “Provisional”.,1
|
|
20
|
+
80,Ice - Estimated,Ice affected time series data. Discharge computed with ice affected stage data is considered estimated.,1
|
|
21
|
+
199,199-Logger Unknown,Initial code for data coming to the system from the logger.,1
|
|
22
|
+
200,200,Initial code for data coming to the system from telemetry or default coding for WISKI timeseries. ,1
|
|
23
|
+
228,Info Parameter,This parameter is collected for informational purposes only. Data has been through a cursory check only. This is stored in the database and available upon request.,1
|
|
24
|
+
255,---,System assigned code for gaps in the data set. Records with null values. ,1
|
|
25
|
+
1,Continuous Data,~Discontinued~ Good TS data that requires no correction.,0
|
|
26
|
+
2,Edited Data,~Discontinued~ TS data that has been edited. Typically used when spikes are removed or when points are edited manual for datum corrections.,0
|
|
27
|
+
3,Instantaneous Data,Final WQ data.,0
|
|
28
|
+
4,Questionable data,~Discontinued~,0
|
|
29
|
+
5,Excellent measurment,Used to indicated discharge measurements that are excellent as well as excellent sections of the rating.,0
|
|
30
|
+
10,Good measurement,Used to indicated discharge measurements and sections of the rating that are good and time series data that tracks well and requires no corrections or corrections of very small magnitude.,0
|
|
31
|
+
12,Modeled measurement,~Discontinued~ Rating point or discharge was obtained from a relizble mathematical and/or computer model. After 3/1/11 use QC148.,0
|
|
32
|
+
15,Fair measurement,Used to indicated discharge measurements and sections of the rating that are fair and time series data that tracks fairly well and requires some corrections of relatively small magnitude.,0
|
|
33
|
+
20,Poor measurement,Used to indicated discharge measurements and sections of the rating that are poor and time series data that tracks poorly and requires significant or many corrections.,0
|
|
34
|
+
25,Unknown measurement,Measurement data not available.,0
|
|
35
|
+
27,Questionable data,"Flow measurement is very poor and should be given extra scrutiny or time series data that is questionable due to operator error, equipment error, etc.",0
|
|
36
|
+
30,Good Archived Daily Value,This code is used for archived daily value data that is considered “Good”.,0
|
|
37
|
+
31,Fair Archived Daily Value,This code is used for archived daily value data that is considered “Fair”.,0
|
|
38
|
+
32,Poor Archived Daily Value,This code is used for archived daily value data that is considered “Poor”.,0
|
|
39
|
+
33,Unknown Archived Daily Value,This code is used for archived daily value data that has unknown quality based on lack of documentation.,0
|
|
40
|
+
34,Estimated Archived Daily Value,This code is used for archived daily value data that has been estimated.,0
|
|
41
|
+
35,Unreliable Archived Daily Value,This code is used for archived daily value data that is unreliable based on the quality of the supporting time series data and/or rating.,0
|
|
42
|
+
45,Good External Data,This code is used for external data that has been graded internally as “Good”.,0
|
|
43
|
+
46,Fair External Data,This code is used for external data that has been graded internally as “Fair”.,0
|
|
44
|
+
47,Poor External Data,This code is used for external data that has been graded internally as “Poor”.,0
|
|
45
|
+
48,Unknown External Data,This code is used for external data that has been graded internally as “Unknown”,0
|
|
46
|
+
49,Estimated External Data,This code is used for external data that has been graded externally as “Estimated.” Typically this is finalized ice data.,0
|
|
47
|
+
50,Provisional External Data,This code is used for external data that has been graded internally as “Provisional”,0
|
|
48
|
+
51,Telemetry data - DCP,This code is used for time-series data when imported into hydstra using an automated telemetry method that accesses a DCP through the GOES network. The “questionable measurement” flag is set through the shef code that accompanies the DCP data.,0
|
|
49
|
+
60,Above rating,~Discontinued~,0
|
|
50
|
+
70,Estimated Data,Value of the data point is estimated.,0
|
|
51
|
+
76,Reliable interpolation,Value of the data point is an interpolation between adjacent points. ,0
|
|
52
|
+
80,Ice,"(DISCONTINUED) Used to indicate ice conditions when the data should not be exported. Use in conjunction with 80 to code 232.00 values, run USDAY to compute daily flow, then recode 232.00 80 values to 180 so unit value export cannot occur.",0
|
|
53
|
+
82,Linear interpolation across a gap in records,~Discontinued~ Points that were added to fill a gap in the data record. The points fall on a straight line between the end points of the gap. This code was changed to 8 in WISKI.,0
|
|
54
|
+
103,Provisional Instantaneous Data,Provisional WQ data.,0
|
|
55
|
+
130,Good Provisional Daily Value,This code is used for archived daily value data that is considered “Good” but Provisional because there is only one year of gaging measurements.,0
|
|
56
|
+
131,Fair Provisional Daily Value,This code is used for archived daily value data that is considered “Fair” but Provisional because there is only one year of gaging measurements.,0
|
|
57
|
+
132,Poor Provisional Daily Value,This code is used for archived daily value data that is considered “Poor” but Provisional because there is only one year of gaging measurements.,0
|
|
58
|
+
133,Unknown Provisional Archived Daily Value,This code is used for archived daily value data that has unknown quality based on lack of documentation but Provisional because there is only one year of gaging measurements.,0
|
|
59
|
+
134,Estimated Provisional Archived Daily Value,This code is used for archived daily value data that has been estimated but Provisional because there is only one year of gaging measurements.,0
|
|
60
|
+
135,Unreliable Provisional Archived Daily Value,This code is used for archived daily value data that is unreliable based on the quality of the supporting time series data and/or rating but Provisional because there is only one year of gaging measurements.,0
|
|
61
|
+
140,Data not yet checked,This code is used for time-series data when it is initially imported into hydstra using manual import methods. ,0
|
|
62
|
+
141,Telemetry data - not yet checked,This code is used for time-series data when it is imported into hydstra using an automated telemetry method.,0
|
|
63
|
+
148,Modeled measurement,Rating point or discharge was obtained from a reliable mathematical and/or computer model.,0
|
|
64
|
+
149,Extrapolated rating point,Rating point accurately extrapolated using supporting data and is less than two times the maxiumum measured discharge.,0
|
|
65
|
+
150,Over-extrapolated rating point,Rating point extrapolated without supporting data or beyone two times the maximum measured discharge without a mathematical model.,0
|
|
66
|
+
151,Data Missing,"This code is used to flag the end of a period of missing time-series data, before the next good data value.",0
|
|
67
|
+
160,Above rating,~Discontinued~,0
|
|
68
|
+
169,Datalogger Hardware Error Code 6999,"This code is used to indicate that a time-series point had a value of 6999 or -6999, a typical hardware error code, and the value was changed.",0
|
|
69
|
+
170,Estimated Data,"Used to indicate estimated data when the data should not be exported. Often used in conjunction with 70 to code 232.00 values, run USDAY to compute daily flow, then recode 232.00 70 values to 170 so unit value export can not occur.",0
|
|
70
|
+
180,Ice,Used to indicate ice conditions.,0
|
|
71
|
+
255,Data Missing,This code is used when data is exported and does not exist for a given time period.,0
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
mpcaHydro/data_manager.py
CHANGED
|
@@ -5,20 +5,20 @@ Created on Fri Jun 3 10:01:14 2022
|
|
|
5
5
|
@author: mfratki
|
|
6
6
|
"""
|
|
7
7
|
|
|
8
|
+
from copy import replace
|
|
8
9
|
import pandas as pd
|
|
9
10
|
#from abc import abstractmethod
|
|
10
11
|
from pathlib import Path
|
|
11
12
|
from mpcaHydro import etlSWD
|
|
12
13
|
from mpcaHydro import equis, wiski, warehouse
|
|
14
|
+
from mpcaHydro import xref
|
|
15
|
+
from mpcaHydro import outlets
|
|
16
|
+
from mpcaHydro.reports import reportManager
|
|
13
17
|
import duckdb
|
|
14
18
|
|
|
15
|
-
|
|
16
|
-
WISKI_EQUIS_XREF = pd.read_csv(Path(__file__).parent/'data/WISKI_EQUIS_XREF.csv')
|
|
17
|
-
#WISKI_EQUIS_XREF = pd.read_csv('C:/Users/mfratki/Documents/GitHub/hspf_tools/WISKI_EQUIS_XREF.csv')
|
|
18
|
-
|
|
19
19
|
AGG_DEFAULTS = {'cfs':'mean',
|
|
20
20
|
'mg/l':'mean',
|
|
21
|
-
'
|
|
21
|
+
'degf': 'mean',
|
|
22
22
|
'lb':'sum'}
|
|
23
23
|
|
|
24
24
|
UNIT_DEFAULTS = {'Q': 'cfs',
|
|
@@ -28,29 +28,15 @@ UNIT_DEFAULTS = {'Q': 'cfs',
|
|
|
28
28
|
'OP' : 'mg/l',
|
|
29
29
|
'TKN': 'mg/l',
|
|
30
30
|
'N' : 'mg/l',
|
|
31
|
-
'WT' : '
|
|
31
|
+
'WT' : 'degf',
|
|
32
32
|
'WL' : 'ft'}
|
|
33
33
|
|
|
34
|
-
def are_lists_identical(nested_list):
|
|
35
|
-
# Sort each sublist
|
|
36
|
-
sorted_sublists = [sorted(sublist) for sublist in nested_list]
|
|
37
|
-
# Compare all sublists to the first one
|
|
38
|
-
return all(sublist == sorted_sublists[0] for sublist in sorted_sublists)
|
|
39
34
|
|
|
40
|
-
def
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
datafiles = folderpath.joinpath('*.csv').as_posix()
|
|
46
|
-
query = '''
|
|
47
|
-
CREATE TABLE observations AS SELECT *
|
|
48
|
-
FROM
|
|
49
|
-
read_csv_auto(?,
|
|
50
|
-
union_by_name = true);
|
|
51
|
-
|
|
52
|
-
'''
|
|
53
|
-
con.execute(query,[datafiles])
|
|
35
|
+
def validate_constituent(constituent):
|
|
36
|
+
assert constituent in ['Q','TSS','TP','OP','TKN','N','WT','DO','WL','CHLA']
|
|
37
|
+
|
|
38
|
+
def validate_unit(unit):
|
|
39
|
+
assert(unit in ['mg/l','lb','cfs','degF'])
|
|
54
40
|
|
|
55
41
|
|
|
56
42
|
def build_warehouse(folderpath):
|
|
@@ -79,315 +65,209 @@ def constituent_summary(db_path):
|
|
|
79
65
|
return res.fetch_df()
|
|
80
66
|
|
|
81
67
|
|
|
68
|
+
|
|
69
|
+
|
|
82
70
|
class dataManager():
|
|
83
71
|
|
|
84
|
-
def __init__(self,folderpath,
|
|
72
|
+
def __init__(self,folderpath, oracle_username = None, oracle_password =None, reset = False):
|
|
85
73
|
|
|
86
74
|
self.data = {}
|
|
87
75
|
self.folderpath = Path(folderpath)
|
|
88
76
|
self.db_path = self.folderpath.joinpath('observations.duckdb')
|
|
89
|
-
self.
|
|
77
|
+
self.oracle_username = oracle_username
|
|
90
78
|
self.oracle_password = oracle_password
|
|
79
|
+
|
|
80
|
+
if not self.db_path.exists() or reset:
|
|
81
|
+
self._build_warehouse()
|
|
82
|
+
|
|
83
|
+
self.xref = xref #TODO: implement xref manager class
|
|
84
|
+
self.outlets = outlets #TODO: implement outlets manager class
|
|
85
|
+
self.reports = reportManager(self.db_path)
|
|
86
|
+
|
|
91
87
|
|
|
92
88
|
def connect_to_oracle(self):
|
|
93
89
|
assert (self.credentials_exist(), 'Oracle credentials not found. Set ORACLE_USER and ORACLE_PASSWORD environment variables or use swd as station_origin')
|
|
94
|
-
equis.connect(user = self.
|
|
90
|
+
equis.connect(user = self.oracle_username, password = self.oracle_password)
|
|
95
91
|
|
|
96
92
|
def credentials_exist(self):
|
|
97
|
-
if (self.
|
|
93
|
+
if (self.oracle_username is not None) & (self.oracle_password is not None):
|
|
98
94
|
return True
|
|
99
95
|
else:
|
|
100
96
|
return False
|
|
101
97
|
|
|
102
|
-
def _reconstruct_database(self):
|
|
103
|
-
construct_database(self.folderpath)
|
|
104
|
-
|
|
105
98
|
def _build_warehouse(self):
|
|
106
|
-
|
|
99
|
+
warehouse.init_db(self.db_path.as_posix(),True)
|
|
100
|
+
|
|
101
|
+
def _process_wiski_data(self,filter_qc_codes = True, data_codes = None, baseflow_method = 'Boughton'):
|
|
102
|
+
with warehouse.connect(self.db_path,read_only = False) as con:
|
|
103
|
+
df = con.execute("SELECT * FROM staging.wiski").df()
|
|
104
|
+
df_transformed = wiski.transform(df, filter_qc_codes, data_codes, baseflow_method)
|
|
105
|
+
warehouse.load_df_to_table(con,df_transformed, 'analytics.wiski')
|
|
106
|
+
warehouse.update_views(con)
|
|
107
|
+
|
|
108
|
+
def _process_equis_data(self):
|
|
109
|
+
with warehouse.connect(self.db_path,read_only = False) as con:
|
|
110
|
+
df = con.execute("SELECT * FROM staging.equis").df()
|
|
111
|
+
df_transformed = equis.transform(df)
|
|
112
|
+
warehouse.load_df_to_table(con,df_transformed, 'analytics.equis')
|
|
113
|
+
warehouse.update_views(con)
|
|
114
|
+
|
|
115
|
+
def _process_data(self,filter_qc_codes = True, data_codes = None, baseflow_method = 'Boughton'):
|
|
116
|
+
self._process_wiski_data(filter_qc_codes, data_codes, baseflow_method)
|
|
117
|
+
self._process_equis_data()
|
|
118
|
+
|
|
119
|
+
def _update_views(self):
|
|
120
|
+
with warehouse.connect(self.db_path,read_only = False) as con:
|
|
121
|
+
warehouse.update_views(con)
|
|
122
|
+
|
|
123
|
+
def _download_wiski_data(self,station_ids,start_year = 1996, end_year = 2030, filter_qc_codes = True, data_codes = None, baseflow_method = 'Boughton'):
|
|
124
|
+
with warehouse.connect(self.db_path,read_only = False) as con:
|
|
125
|
+
df = wiski.download(station_ids,start_year = start_year, end_year = end_year)
|
|
126
|
+
if not df.empty:
|
|
127
|
+
warehouse.load_df_to_table(con,df, 'staging.wiski')
|
|
128
|
+
warehouse.load_df_to_table(con,wiski.transform(df, filter_qc_codes,data_codes,baseflow_method), 'analytics.wiski')
|
|
129
|
+
warehouse.update_views(con)
|
|
130
|
+
else:
|
|
131
|
+
print('No data neccesary for HSPF calibration available from wiski for stations:',station_ids)
|
|
132
|
+
|
|
133
|
+
def _download_equis_data(self,station_ids):
|
|
134
|
+
if self.credentials_exist():
|
|
135
|
+
self.connect_to_oracle()
|
|
136
|
+
print('Connected to Oracle database.')
|
|
137
|
+
with warehouse.connect(self.db_path,read_only = False) as con:
|
|
138
|
+
df = equis.download(station_ids)
|
|
139
|
+
if not df.empty:
|
|
140
|
+
warehouse.load_df_to_table(con,df, 'staging.equis')
|
|
141
|
+
warehouse.load_df_to_table(con,equis.transform(df.copy()), 'analytics.equis')
|
|
142
|
+
warehouse.update_views(con)
|
|
143
|
+
else:
|
|
144
|
+
print('No data neccesary for HSPF calibration available from equis for stations:',station_ids)
|
|
145
|
+
else:
|
|
146
|
+
raise ValueError('Oracle credentials not found. Set ORACLE_USER and ORACLE_PASSWORD environment variables or use swd as station_origin')
|
|
107
147
|
|
|
108
|
-
def constituent_summary(self,constituents = None):
|
|
109
|
-
with duckdb.connect(self.db_path) as con:
|
|
110
|
-
if constituents is None:
|
|
111
|
-
constituents = con.query('''
|
|
112
|
-
SELECT DISTINCT
|
|
113
|
-
constituent
|
|
114
|
-
FROM observations''').to_df()['constituent'].to_list()
|
|
115
148
|
|
|
149
|
+
def _get_equis_template(self):
|
|
150
|
+
with duckdb.connect(self.db_path,read_only=True) as con:
|
|
116
151
|
query = '''
|
|
117
|
-
SELECT
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
COUNT(*) AS sample_count,
|
|
122
|
-
year(MIN(datetime)) AS start_date,
|
|
123
|
-
year(MAX(datetime)) AS end_date
|
|
124
|
-
FROM
|
|
125
|
-
observations
|
|
126
|
-
WHERE
|
|
127
|
-
constituent in (SELECT UNNEST(?))
|
|
128
|
-
GROUP BY
|
|
129
|
-
constituent,station_id,station_origin
|
|
130
|
-
ORDER BY
|
|
131
|
-
constituent,sample_count;'''
|
|
132
|
-
|
|
133
|
-
df = con.execute(query,[constituents]).fetch_df()
|
|
152
|
+
SELECT *
|
|
153
|
+
FROM staging.equis
|
|
154
|
+
LIMIT 0'''
|
|
155
|
+
df = con.execute(query).fetch_df().to_csv(self.folderpath.joinpath('equis_template.csv'), index=False)
|
|
134
156
|
return df
|
|
135
|
-
|
|
136
|
-
def get_wiski_stations(self):
|
|
137
|
-
return list(WISKI_EQUIS_XREF['WISKI_STATION_NO'].unique())
|
|
138
|
-
|
|
139
|
-
def get_equis_stations(self):
|
|
140
|
-
return list(WISKI_EQUIS_XREF['EQUIS_STATION_ID'].unique())
|
|
141
157
|
|
|
142
|
-
def
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
else:
|
|
151
|
-
return equis_ids[0]
|
|
152
|
-
|
|
153
|
-
def wiski_equis_associations(self,wiski_station_id):
|
|
154
|
-
equis_ids = list(WISKI_EQUIS_XREF.loc[WISKI_EQUIS_XREF['WISKI_STATION_NO'] == wiski_station_id,'EQUIS_STATION_ID'].unique())
|
|
155
|
-
equis_ids = [equis_id for equis_id in equis_ids if not pd.isna(equis_id)]
|
|
156
|
-
if len(equis_ids) == 0:
|
|
157
|
-
return []
|
|
158
|
-
else:
|
|
159
|
-
return equis_ids
|
|
160
|
-
|
|
161
|
-
def equis_wiski_associations(self,equis_station_id):
|
|
162
|
-
wiski_ids = list(WISKI_EQUIS_XREF.loc[WISKI_EQUIS_XREF['EQUIS_STATION_ID'] == equis_station_id,'WISKI_STATION_NO'].unique())
|
|
163
|
-
wiski_ids = [wiski_id for wiski_id in wiski_ids if not pd.isna(wiski_id)]
|
|
164
|
-
if len(wiski_ids) == 0:
|
|
165
|
-
return []
|
|
166
|
-
else:
|
|
167
|
-
return wiski_ids
|
|
168
|
-
|
|
169
|
-
def equis_wiski_alias(self,equis_station_id):
|
|
170
|
-
wiski_ids = list(set(WISKI_EQUIS_XREF.loc[WISKI_EQUIS_XREF['WISKI_EQUIS_ID'] == equis_station_id,'WISKI_STATION_NO'].to_list()))
|
|
171
|
-
wiski_ids = [wiski_id for wiski_id in wiski_ids if not pd.isna(wiski_id)]
|
|
172
|
-
if len(wiski_ids) == 0:
|
|
173
|
-
return []
|
|
174
|
-
elif len(wiski_ids) > 1:
|
|
175
|
-
print(f'Too Many WISKI Stations for {equis_station_id}')
|
|
176
|
-
raise
|
|
177
|
-
else:
|
|
178
|
-
return wiski_ids[0]
|
|
179
|
-
|
|
180
|
-
def _equis_wiski_associations(self,equis_station_ids):
|
|
181
|
-
wiski_stations = [self.equis_wiski_associations(equis_station_id) for equis_station_id in equis_station_ids]
|
|
182
|
-
if are_lists_identical(wiski_stations):
|
|
183
|
-
return wiski_stations[0]
|
|
184
|
-
else:
|
|
185
|
-
return []
|
|
186
|
-
|
|
187
|
-
def _stations_by_wid(self,wid_no,station_origin):
|
|
188
|
-
if station_origin in ['wiski','wplmn']:
|
|
189
|
-
station_col = 'WISKI_STATION_NO'
|
|
190
|
-
elif station_origin in ['equis','swd']:
|
|
191
|
-
station_col = 'EQUIS_STATION_ID'
|
|
192
|
-
else:
|
|
193
|
-
raise
|
|
194
|
-
|
|
195
|
-
return list(WISKI_EQUIS_XREF.loc[WISKI_EQUIS_XREF['WID'] == wid_no,station_col].unique())
|
|
158
|
+
def _get_wiski_template(self):
|
|
159
|
+
with duckdb.connect(self.db_path,read_only=True) as con:
|
|
160
|
+
query = '''
|
|
161
|
+
SELECT *
|
|
162
|
+
FROM staging.wiski
|
|
163
|
+
LIMIT 0'''
|
|
164
|
+
df = con.execute(query).fetch_df().to_csv(self.folderpath.joinpath('wiski_template.csv'), index=False)
|
|
165
|
+
return df
|
|
196
166
|
|
|
167
|
+
def get_outlets(self,model_name):
|
|
168
|
+
with duckdb.connect(self.db_path,read_only=True) as con:
|
|
169
|
+
query = '''
|
|
170
|
+
SELECT *
|
|
171
|
+
FROM outlets.station_reach_pairs
|
|
172
|
+
WHERE repository_name = ?
|
|
173
|
+
ORDER BY outlet_id'''
|
|
174
|
+
df = con.execute(query,[model_name]).fetch_df()
|
|
175
|
+
return df
|
|
197
176
|
|
|
198
|
-
def
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
self.download_station_data(station_id,'wplmn',overwrite = overwrite)
|
|
212
|
-
elif station_origin == 'swd':
|
|
213
|
-
self.download_station_data(station_id,'swd',overwrite = overwrite)
|
|
214
|
-
else:
|
|
215
|
-
self.download_station_data(station_id,'equis',overwrite = overwrite)
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
def download_station_data(self,station_id,station_origin,start_year = 1996, end_year = 2030,folderpath=None,overwrite = False,baseflow_method = 'Boughton'):
|
|
221
|
-
assert(station_origin in ['wiski','equis','swd','wplmn'])
|
|
222
|
-
station_id = str(station_id)
|
|
223
|
-
save_name = station_id
|
|
224
|
-
if station_origin == 'wplmn':
|
|
225
|
-
save_name = station_id + '_wplmn'
|
|
226
|
-
|
|
227
|
-
if folderpath is None:
|
|
228
|
-
folderpath = self.folderpath
|
|
229
|
-
else:
|
|
230
|
-
folderpath = Path(folderpath)
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
if (folderpath.joinpath(save_name + '.csv').exists()) & (not overwrite):
|
|
234
|
-
print (f'{station_id} data already downloaded')
|
|
235
|
-
return
|
|
236
|
-
|
|
237
|
-
if station_origin == 'wiski':
|
|
238
|
-
data = wiski.transform(wiski.download([station_id],wplmn=False, baseflow_method = baseflow_method))
|
|
239
|
-
elif station_origin == 'swd':
|
|
240
|
-
data = etlSWD.download(station_id)
|
|
241
|
-
elif station_origin == 'equis':
|
|
242
|
-
assert (self.credentials_exist(), 'Oracle credentials not found. Set ORACLE_USER and ORACLE_PASSWORD environment variables or use swd as station_origin')
|
|
243
|
-
data = equis.transform(equis.download([station_id]))
|
|
244
|
-
else:
|
|
245
|
-
data = wiski.transform(wiski.download([station_id],wplmn=True, baseflow_method = baseflow_method))
|
|
177
|
+
def get_station_ids(self,station_origin = None):
|
|
178
|
+
with duckdb.connect(self.db_path,read_only=True) as con:
|
|
179
|
+
if station_origin is None:
|
|
180
|
+
query = '''
|
|
181
|
+
SELECT DISTINCT station_id, station_origin
|
|
182
|
+
FROM analytics.observations'''
|
|
183
|
+
df = con.execute(query).fetch_df()
|
|
184
|
+
else:
|
|
185
|
+
query = '''
|
|
186
|
+
SELECT DISTINCT station_id
|
|
187
|
+
FROM analytics.observations
|
|
188
|
+
WHERE station_origin = ?'''
|
|
189
|
+
df = con.execute(query,[station_origin]).fetch_df()
|
|
246
190
|
|
|
191
|
+
return df['station_id'].to_list()
|
|
192
|
+
|
|
247
193
|
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
if len(data) > 0:
|
|
251
|
-
data.to_csv(folderpath.joinpath(save_name + '.csv'))
|
|
252
|
-
self.data[station_id] = data
|
|
253
|
-
else:
|
|
254
|
-
print(f'No {station_origin} calibration cata available at Station {station_id}')
|
|
255
|
-
|
|
256
|
-
def _load(self,station_id):
|
|
257
|
-
with duckdb.connect(self.db_path) as con:
|
|
194
|
+
def get_observation_data(self,station_ids,constituent,agg_period = None):
|
|
195
|
+
with duckdb.connect(self.db_path,read_only=True) as con:
|
|
258
196
|
query = '''
|
|
259
197
|
SELECT *
|
|
260
198
|
FROM analytics.observations
|
|
261
|
-
WHERE station_id = ?'''
|
|
262
|
-
df = con.execute(query,[
|
|
263
|
-
df.set_index('datetime',inplace=True)
|
|
264
|
-
self.data[station_id] = df
|
|
265
|
-
return df
|
|
266
|
-
|
|
267
|
-
def _load2(self,station_id):
|
|
268
|
-
df = pd.read_csv(self.folderpath.joinpath(station_id + '.csv'),
|
|
269
|
-
index_col='datetime',
|
|
270
|
-
parse_dates=['datetime'],
|
|
271
|
-
#usecols=['Ts Date','Station number','variable', 'value','reach_id'],
|
|
272
|
-
dtype={'station_id': str, 'value': float, 'variable': str,'constituent':str,'unit':str})
|
|
273
|
-
self.data[station_id] = df
|
|
274
|
-
return df
|
|
275
|
-
|
|
276
|
-
def load(self,station_id):
|
|
277
|
-
try:
|
|
278
|
-
df = self.data[station_id]
|
|
279
|
-
except:
|
|
280
|
-
df = self._load(station_id)
|
|
281
|
-
return df
|
|
282
|
-
|
|
283
|
-
def info(self,constituent):
|
|
284
|
-
return pd.concat([self._load(file.stem) for file in self.folderpath.iterdir() if file.suffix == '.csv'])[['station_id','constituent','value']].groupby(by = ['station_id','constituent']).count()
|
|
285
|
-
|
|
286
|
-
def get_wplmn_data(self,station_id,constituent,unit = 'mg/l', agg_period = 'YE', samples_only = True):
|
|
287
|
-
|
|
288
|
-
assert constituent in ['Q','TSS','TP','OP','TKN','N','WT','DO','WL','CHLA']
|
|
289
|
-
station_id = station_id + '_wplmn'
|
|
290
|
-
dfsub = self._load(station_id)
|
|
291
|
-
|
|
292
|
-
if samples_only:
|
|
293
|
-
dfsub = dfsub.loc[dfsub['quality_id'] == 3]
|
|
294
|
-
agg_func = 'mean'
|
|
199
|
+
WHERE station_id IN ? AND constituent = ?'''
|
|
200
|
+
df = con.execute(query,[station_ids,constituent]).fetch_df()
|
|
295
201
|
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
['value','station_origin']]
|
|
202
|
+
unit = UNIT_DEFAULTS[constituent]
|
|
203
|
+
agg_func = AGG_DEFAULTS[unit]
|
|
299
204
|
|
|
300
|
-
|
|
301
|
-
df = dfsub[['value']].resample(agg_period).agg(agg_func)
|
|
302
|
-
|
|
303
|
-
if df.empty:
|
|
304
|
-
dfsub = df
|
|
305
|
-
else:
|
|
306
|
-
|
|
307
|
-
df['station_origin'] = dfsub['station_origin'].iloc[0]
|
|
308
|
-
|
|
309
|
-
#if (constituent == 'TSS') & (unit == 'lb'): #convert TSS from lbs to us tons
|
|
310
|
-
# dfsub['value'] = dfsub['value']/2000
|
|
311
|
-
|
|
312
|
-
#dfsub = dfsub.resample('H').mean().dropna()
|
|
313
|
-
|
|
205
|
+
df.set_index('datetime',inplace=True)
|
|
314
206
|
df.attrs['unit'] = unit
|
|
315
207
|
df.attrs['constituent'] = constituent
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
208
|
+
if agg_period is not None:
|
|
209
|
+
df = df[['value']].resample(agg_period).agg(agg_func)
|
|
210
|
+
df.attrs['agg_period'] = agg_period
|
|
211
|
+
|
|
212
|
+
df.rename(columns={'value': 'observed'}, inplace=True)
|
|
213
|
+
return df.dropna(subset=['observed'])
|
|
320
214
|
|
|
321
|
-
def
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
215
|
+
def get_outlet_data(self,outlet_id,constituent,agg_period = 'D',to_csv = False):
|
|
216
|
+
with duckdb.connect(self.db_path,read_only=True) as con:
|
|
217
|
+
query = '''
|
|
218
|
+
SELECT *
|
|
219
|
+
FROM analytics.outlet_observations_with_flow
|
|
220
|
+
WHERE outlet_id = ? AND constituent = ?'''
|
|
221
|
+
df = con.execute(query,[outlet_id,constituent]).fetch_df()
|
|
326
222
|
|
|
327
|
-
Parameters
|
|
328
|
-
----------
|
|
329
|
-
station_id : STR
|
|
330
|
-
Station ID as a string
|
|
331
|
-
constituent : TYPE
|
|
332
|
-
Constituent abbreviation used for calibration. Valid options:
|
|
333
|
-
'Q',
|
|
334
|
-
'TSS',
|
|
335
|
-
'TP',
|
|
336
|
-
'OP',
|
|
337
|
-
'TKN',
|
|
338
|
-
'N',
|
|
339
|
-
'WT',
|
|
340
|
-
'DO',
|
|
341
|
-
'WL']
|
|
342
|
-
unit : TYPE, optional
|
|
343
|
-
Units of data. The default is 'mg/l'.
|
|
344
|
-
sample_flag : TYPE, optional
|
|
345
|
-
For WPLMN data this flag determines modeled loads are returned. The default is False.
|
|
346
|
-
|
|
347
|
-
Returns
|
|
348
|
-
-------
|
|
349
|
-
dfsub : Pands.Series
|
|
350
|
-
Pandas series of data. Note that no metadata is returned.
|
|
351
|
-
|
|
352
|
-
'''
|
|
353
|
-
|
|
354
|
-
assert constituent in ['Q','QB','TSS','TP','OP','TKN','N','WT','DO','WL','CHLA']
|
|
355
|
-
|
|
356
223
|
unit = UNIT_DEFAULTS[constituent]
|
|
357
224
|
agg_func = AGG_DEFAULTS[unit]
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
dfsub.index = dfsub.index.tz_localize(None) # Drop timezone info
|
|
361
|
-
#dfsub.set_index('datetime',drop=True,inplace=True)
|
|
362
|
-
dfsub.rename(columns={'source':'station_origin'},inplace=True)
|
|
363
|
-
dfsub = dfsub.loc[(dfsub['constituent'] == constituent) &
|
|
364
|
-
(dfsub['unit'] == unit),
|
|
365
|
-
['value','station_origin']]
|
|
366
|
-
|
|
367
|
-
df = dfsub[['value']].resample(agg_period).agg(agg_func)
|
|
225
|
+
|
|
226
|
+
df.set_index('datetime',inplace=True)
|
|
368
227
|
df.attrs['unit'] = unit
|
|
369
228
|
df.attrs['constituent'] = constituent
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
# convert to desired timzone before stripping timezone information.
|
|
380
|
-
#df.index.tz_convert('UTC-06:00').tz_localize(None)
|
|
381
|
-
|
|
382
|
-
return df['value'].to_frame().dropna()
|
|
229
|
+
if agg_period is not None:
|
|
230
|
+
df = df[['value','flow_value','baseflow_value']].resample(agg_period).agg(agg_func)
|
|
231
|
+
df.attrs['agg_period'] = agg_period
|
|
232
|
+
|
|
233
|
+
df.rename(columns={'value': 'observed',
|
|
234
|
+
'flow_value': 'observed_flow',
|
|
235
|
+
'baseflow_value': 'observed_baseflow'}, inplace=True)
|
|
236
|
+
return df.dropna(subset=['observed'])
|
|
383
237
|
|
|
238
|
+
def get_raw_data(self,station_id,station_origin, to_csv = False):
|
|
239
|
+
with duckdb.connect(self.db_path,read_only=True) as con:
|
|
240
|
+
if station_origin.lower() == 'equis':
|
|
241
|
+
query = '''
|
|
242
|
+
SELECT *
|
|
243
|
+
FROM staging.equis_raw
|
|
244
|
+
WHERE station_id = ?'''
|
|
245
|
+
elif station_origin.lower() == 'wiski':
|
|
246
|
+
query = '''
|
|
247
|
+
SELECT *
|
|
248
|
+
FROM staging.wiski_raw
|
|
249
|
+
WHERE station_id = ?'''
|
|
250
|
+
else:
|
|
251
|
+
raise ValueError(f'Station origin {station_origin} not recognized. Valid options are equis or wiski.')
|
|
252
|
+
|
|
253
|
+
df = con.execute(query,[station_id]).fetch_df()
|
|
384
254
|
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
def validate_unit(unit):
|
|
389
|
-
assert(unit in ['mg/l','lb','cfs','degF'])
|
|
255
|
+
if to_csv:
|
|
256
|
+
df.to_csv(self.folderpath.joinpath(f'{station_id}_raw.csv'), index=False)
|
|
257
|
+
return df
|
|
390
258
|
|
|
259
|
+
def to_csv(self,station_id ,station_origin,folderpath = None):
|
|
260
|
+
if folderpath is None:
|
|
261
|
+
folderpath = self.folderpath
|
|
262
|
+
else:
|
|
263
|
+
folderpath = Path(folderpath)
|
|
264
|
+
df = self.get_station_data([station_id],constituent = 'Q',agg_period = None)
|
|
265
|
+
if len(df) > 0:
|
|
266
|
+
df.to_csv(folderpath.joinpath(station_id + '.csv'))
|
|
267
|
+
else:
|
|
268
|
+
print(f'No {station_id} calibration data available at Station {station_id}')
|
|
269
|
+
|
|
270
|
+
df.to_csv(folderpath.joinpath(station_id + '.csv'))
|
|
391
271
|
|
|
392
272
|
|
|
393
273
|
# class database():
|