-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget-data.py
370 lines (270 loc) · 12.8 KB
/
get-data.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
import os
import sys
import time
import json
from unicodedata import numeric
from pytz import timezone
import requests
from datetime import datetime
from datetime import timedelta
import pandas as pd
from io import StringIO
from urllib.request import urlopen
import xmltodict
import numpy as np
import warnings
from sqlalchemy import create_engine
import inspect
import traceback
########################
# Utility functions #
########################
# override print so each statement is timestamped
old_print = print
def timestamped_print(*args, **kwargs):
old_print(datetime.now(), *args, **kwargs)
print = timestamped_print
def slicer(my_str,sub):
index=my_str.find(sub)
if index !=-1 :
return my_str[index:]
else :
raise Exception('Sub string not found!')
def postgres_upsert(table, conn, keys, data_iter):
from sqlalchemy.dialects.postgresql import insert
data = [dict(zip(keys, row)) for row in data_iter]
insert_statement = insert(table.table).values(data)
upsert_statement = insert_statement.on_conflict_do_update(
constraint=f"{table.table.name}_pkey",
set_={c.key: c for c in insert_statement.excluded},
)
conn.execute(upsert_statement)
#############################
# Method-specific functions #
#############################
def get_fiman_data(id, sensor, begin_date, end_date):
"""Retrieve data from specified sensor from the FIMAN API
Args:
id (str): Station id
sensor (str): Requested sensor at station
begin_date (str): Beginning date of requested time period. Format: %Y%m%d %H:%M
end_date (str): End date of requested time period. Format: %Y%m%d %H:%M
Returns:
r_df (pd.DataFrame): DataFrame of requested data from specified station and time range. Dates in UTC
"""
print(inspect.stack()[0][3]) # print the name of the function we just entered
#
# It looks like if the data are not long enough (date-wise), the query to fiman will not return anything
# at which point this will fail.
#
fiman_gauge_keys = pd.read_csv("data/fiman_gauge_key.csv").query("site_id == @id & Sensor == @sensor")
new_begin_date = pd.to_datetime(begin_date, utc=True) - timedelta(seconds = 3600)
new_end_date = pd.to_datetime(end_date, utc=True) + timedelta(seconds = 3600)
query = {'site_id' : fiman_gauge_keys.iloc[0]["site_id"],
'data_start' : new_begin_date.strftime('%Y-%m-%d %H:%M:%S'),
'end_date' : new_end_date.strftime('%Y-%m-%d %H:%M:%S'),
'format_datetime' : '%Y-%m-%d %H:%M:%S',
'tz' : 'utc',
'show_raw' : True,
'show_quality' : True,
'sensor_id' : fiman_gauge_keys.iloc[0]["sensor_id"]}
print(query) # FOR DEBUGGING
# try:
r = requests.get(os.environ.get("FIMAN_URL"), params=query, timeout=120)
# except requests.exceptions.Timeout:
# return pd.DataFrame()
j = r.content
doc = xmltodict.parse(j)
print(doc)
unnested = doc["onerain"]["response"]["general"]["row"]
r_df = pd.DataFrame.from_dict(unnested)
r_df["date"] = pd.to_datetime(r_df["data_time"], utc=True);
r_df["id"] = str(id);
r_df["notes"] = "FIMAN"
r_df["type"] = "water_level" if sensor == "Water Elevation" else "pressure"
r_df = r_df.loc[:,["id","date","data_value","notes", "type"]].rename(columns = {"data_value":"value", "notes": "api_name"})
return r_df.drop_duplicates(subset=['id', 'date'])
def get_noaa_data(id, type, begin_date, end_date):
"""Retrieve data from the NOAA tides and currents API
Args:
id (str): Station id
begin_date (str): Beginning date of requested time period. Format: %Y%m%d %H:%M
end_date (str): End date of requested time period. Format: %Y%m%d %H:%M
Returns:
r_df (pd.DataFrame): DataFrame of requested data from specified station and time range. Dates in UTC
"""
print(inspect.stack()[0][3]) # print the name of the function we just entered
query = {'station' : str(id),
'begin_date' : begin_date.strftime("%Y%m%d %H:%M"),
'end_date' : end_date.strftime("%Y%m%d %H:%M"),
'product' : type,
'units' : 'english',
'datum': "NAVD",
'time_zone' : 'gmt',
'format' : 'json',
'application' : 'Sunny_Day_Flooding_project, https://github.com/sunny-day-flooding-project'}
print(query)
r = requests.get('https://api.tidesandcurrents.noaa.gov/api/prod/datagetter/', params=query)
j = r.json()
if type == 'water_level':
r_df = pd.DataFrame.from_dict(j["data"])
else:
r_df = pd.DataFrame.from_dict(j["predictions"])
r_df['v'].replace('', np.nan, inplace=True)
r_df["t"] = pd.to_datetime(r_df["t"], utc=True)
r_df["id"] = str(id)
r_df["type"] = type
r_df["api_name"] = "NOAA"
r_df = r_df.loc[:,["id","t","v","type","api_name"]].rename(columns = {"id":"id","t":"date","v":"value"})
return r_df.dropna()
def get_hohonu_data(id, begin_date, end_date):
"""Retrieve data from specified sensor from the Hohonu API
Args:
id (str): Station id
begin_date (str): Beginning date of requested time period. Format: %Y%m%d %H:%M
end_date (str): End date of requested time period. Format: %Y%m%d %H:%M
Returns:
r_df (pd.DataFrame): DataFrame of requested data from specified station and time range. Dates in UTC
"""
print(inspect.stack()[0][3]) # print the name of the function we just entered
new_begin_date = pd.to_datetime(begin_date, utc=True) - timedelta(seconds = 3600)
new_end_date = pd.to_datetime(end_date, utc=True) + timedelta(seconds = 3600)
query = {'datum' : 'NAVD',
'from' : new_begin_date.strftime('%Y-%m-%d'),
'to' : new_end_date.strftime('%Y-%m-%d'),
'format' : 'json',
'tz': '0',
'cleaned': 'true'
}
print(query) # FOR DEBUGGING
url = "https://dashboard.hohonu.io/api/v1/stations/" + id + "/statistic"
r = requests.get(url, params=query, timeout=120, headers={'Authorization': os.environ.get('HOHONU_API_TOKEN')})
j = json.loads(r.content)
r_df = pd.DataFrame({'timestamp': j['data'][0], 'value': j['data'][1]}).dropna()
r_df["date"] = pd.to_datetime(r_df["timestamp"], utc=True);
r_df["id"] = str(id);
r_df["api_name"] = "Hohonu"
r_df["type"] = "water_level"
r_df = r_df.loc[:,["id","date","value","api_name", "type"]]
return r_df.drop_duplicates(subset=['id', 'date'])
def main():
print("Entering main of process_pressure.py")
# from env_vars import set_env_vars
# set_env_vars()
########################
# Establish DB engine #
########################
SQLALCHEMY_DATABASE_URL = "postgresql://" + os.environ.get('POSTGRESQL_USER') + ":" + os.environ.get(
'POSTGRESQL_PASSWORD') + "@" + os.environ.get('POSTGRESQL_HOSTNAME') + "/" + os.environ.get('POSTGRESQL_DATABASE')
engine = create_engine(SQLALCHEMY_DATABASE_URL)
#####################
# Collect new data #
#####################
now = pd.Timestamp("now", tz="UTC")
# Get water level data
# FIMAN
stations = pd.read_sql_query("SELECT DISTINCT wl_id FROM sensor_surveys WHERE wl_src='FIMAN'", engine)
stations = stations.to_numpy()
for wl_id in stations:
print("Querying FIMAN site " + wl_id[0] + "...")
query = f"SELECT MAX(date) FROM api_data WHERE api_name='FIMAN' AND id='{wl_id[0]}' AND type='water_level'"
start_date = pd.to_datetime(pd.read_sql_query(query, engine).iloc[0]['max'])
date_limit = pd.to_datetime(now - pd.Timedelta(days=21))
# Don't go further than 21 days back
if (start_date is None or start_date < date_limit):
start_date = date_limit
end_date = start_date + pd.Timedelta(hours=12)
if (end_date > now):
end_date = now
new_data = get_fiman_data(wl_id[0], 'Water Elevation', start_date, end_date)
if new_data.shape[0] == 0:
warnings.warn("- No new raw data!")
return
print(new_data.shape[0] , "new records!")
new_data.to_sql("api_data", engine, if_exists = "append", method=postgres_upsert, index=False)
time.sleep(10)
# Hohonu
stations = pd.read_sql_query("SELECT DISTINCT wl_id FROM sensor_surveys WHERE wl_src='Hohonu'", engine)
stations = stations.to_numpy()
for wl_id in stations:
print("Querying Hohonu site " + wl_id[0] + "...")
query = f"SELECT MAX(date) FROM api_data WHERE api_name='Hohonu' AND id='{wl_id[0]}' AND type='water_level'"
start_date = pd.to_datetime(pd.read_sql_query(query, engine).iloc[0]['max'])
date_limit = pd.to_datetime(now - pd.Timedelta(days=21))
# Don't go further than 21 days back
if (start_date is None or start_date < date_limit):
start_date = date_limit
end_date = start_date + pd.Timedelta(hours=24)
if (end_date > now):
end_date = now
new_data = get_hohonu_data(wl_id[0], start_date, end_date)
if new_data.shape[0] == 0:
warnings.warn("- No new raw data!")
return
print(new_data.shape[0] , "new records!")
new_data.to_sql("api_data", engine, if_exists = "append", method=postgres_upsert, index=False)
time.sleep(10)
# NOAA
stations = pd.read_sql_query("SELECT DISTINCT wl_id FROM sensor_surveys WHERE wl_src='NOAA'", engine)
stations = stations.to_numpy()
for wl_id in stations:
print("Querying NOAA site " + wl_id[0] + "...")
# Observed data
query = f"SELECT MAX(date) FROM api_data WHERE api_name='NOAA' AND id='{wl_id[0]}' AND type='water_level'"
start_date = pd.to_datetime(pd.read_sql_query(query, engine).iloc[0]['max'])
date_limit = pd.to_datetime(now - pd.Timedelta(days=21))
# Don't go further than 21 days back
if (start_date is None or start_date < date_limit):
start_date = date_limit
end_date = start_date + pd.Timedelta(hours=12)
if (end_date > now):
end_date = now
new_data = get_noaa_data(wl_id[0], 'water_level', start_date, end_date)
if new_data.shape[0] == 0:
warnings.warn("- No new raw data!")
return
print(new_data.shape[0] , "new records!")
new_data.to_sql("api_data", engine, if_exists = "append", method=postgres_upsert, index=False)
time.sleep(10)
# Predictions
query = f"SELECT MAX(date) FROM api_data WHERE api_name='NOAA' AND id='{wl_id[0]}' AND type='predictions'"
start_date = pd.to_datetime(pd.read_sql_query(query, engine).iloc[0]['max'])
date_limit = pd.to_datetime(now - pd.Timedelta(days=21))
# Don't go further than 21 days back
if (start_date is None or start_date < date_limit):
start_date = date_limit
end_date = start_date + pd.Timedelta(hours=12)
if (end_date > now):
end_date = now
new_data = get_noaa_data(wl_id[0], 'predictions', start_date, end_date)
if new_data.shape[0] == 0:
warnings.warn("- No new raw data!")
return
print(new_data.shape[0] , "new records!")
new_data.to_sql("api_data", engine, if_exists = "append", method=postgres_upsert, index=False)
time.sleep(10)
# Get atm_pressure data
# FIMAN
stations = pd.read_sql_query("SELECT DISTINCT atm_station_id FROM sensor_surveys WHERE atm_data_src='FIMAN'", engine)
stations = stations.to_numpy()
for atm_station_id in stations:
print("Querying FIMAN site " + atm_station_id[0] + "...")
query = f"SELECT MAX(date) FROM api_data WHERE api_name='FIMAN' AND id='{atm_station_id[0]}' AND type='pressure'"
start_date = pd.to_datetime(pd.read_sql_query(query, engine).iloc[0]['max'])
date_limit = pd.to_datetime(now - pd.Timedelta(days=21))
# Don't go further than 21 days back
if (start_date is None or start_date < date_limit):
start_date = date_limit
end_date = start_date + pd.Timedelta(hours=12)
if (end_date > now):
end_date = now
new_data = get_fiman_data(atm_station_id[0], 'Barometric Pressure', start_date, end_date)
if new_data.shape[0] == 0:
warnings.warn("- No new raw data!")
return
print(new_data.shape[0] , "new records!")
new_data.to_sql("api_data", engine, if_exists = "append", method=postgres_upsert, index=False)
time.sleep(10)
engine.dispose()
if __name__ == "__main__":
main()