-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate_wls.py
339 lines (289 loc) · 11.6 KB
/
generate_wls.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
# ===============================================================================
# Copyright 2020 ross
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===============================================================================
import json
import os
from datetime import datetime
from itertools import groupby
from operator import itemgetter
import requests
from db import execute_query
from util import assemble, r_mkdir
ST = 'https://st.newmexicowaterdata.org/FROST-Server/v1.1'
KIND = 'manual'
KIND = 'non_NMBGMR_cgwmn'
KIND = 'non_MEASURING_AGENCY_cgwmn'
if KIND == 'acoustic':
TABLE = 'WaterLevelsContinuous_Acoustic'
ROOT = 'wlacoustic'
OP_DESCRIPTION = 'continuous acoustic transducer measurement depth to groundwater'
DS_DESCRIPTION = 'calculated depth below ground surface. calibrated to manual measurements'
PID_SQL = '''select L.PointID from WaterLevelsContinuous_Acoustic as T
join Location L on T.PointID = L.PointID
where L.PublicRelease=1 and T.MeasuringAgency='NMBGMR'
group by L.PointID'''
elif KIND == 'pressure':
TABLE = 'WaterLevelsContinuous_Pressure'
ROOT = 'wlpressure'
OP_DESCRIPTION = 'continuous pressure transducer measurement of groundwater head'
DS_DESCRIPTION = 'calculated depth below ground surface. calibrated to manual measurements'
PID_SQL = '''select L.PointID from WaterLevelsContinuous_Pressure as T
join Location L on T.PointID = L.PointID
where L.PublicRelease=1 and T.QCed=1 and T.MeasuringAgency='NMBGMR'
group by L.PointID'''
elif KIND == 'manual':
TABLE = 'WaterLevels'
ROOT = 'wlmanual'
OP_DESCRIPTION = 'manual measurement depth to groundwater'
DS_DESCRIPTION = 'manual measurements'
PID_SQL = '''select L.PointID from WaterLevels as T
join Location L on T.PointID=L.PointID
where L.PublicRelease=1 and T.MeasuringAgency='NMBGMR'
group by L.PointID
order by L.PointID
'''
elif KIND == 'non_NMBGMR_cgwmn':
TABLE = 'WaterLevels'
ROOT = 'cgwmn_wlmanual'
OP_DESCRIPTION = 'manual measurement depth to groundwater'
DS_DESCRIPTION = 'manual measurements'
PID_SQL = '''select L.PointID from ProjectLocations as T
join Location L on T.PointID=L.PointID
join WaterLevels as WL on WL.PointID=L.PointID
where L.PublicRelease=1 and WL.MeasuringAgency!='NMBGMR' and T.ProjectName='Water Level Network'
group by L.PointID
order by L.PointID
'''
elif KIND == 'non_MEASURING_AGENCY_cgwmn':
TABLE = 'WaterLevels'
ROOT = 'cgwmn_wlmanual_manual_pids'
OP_DESCRIPTION = 'manual measurement depth to groundwater'
DS_DESCRIPTION = 'manual measurements'
PID_SQL = '''select L.PointID from ProjectLocations as T
join Location L on T.PointID=L.PointID
join WaterLevels as WL on WL.PointID=L.PointID
where L.PublicRelease=1 and WL.MeasuringAgency is NULL and T.ProjectName='Water Level Network'
group by L.PointID
order by L.PointID
'''
def extract_thing_properties(p):
sql = '''select TOP(1) *,
ludr.MEANING as [DR_Meaning],
lumm.MEANING as [MM_Meaning],
luam.MEANING as [AM_Meaning]
from dbo.{} as P
join Location as L on L.PointID = P.PointID
join dbo.LU_MeasurementMethod as lumm on lumm.Code = P.MeasurementMethod
join dbo.LU_DataReliability as ludr on ludr.Code = L.DataReliability
join dbo.LU_AltitudeMethod as luam on luam.Code = L.AltitudeMethod
where P.PointID=%d '''.format(TABLE)
return execute_query(sql, p)
def extract_data2(p):
sql = '''select *,
L.GEOMETRY.STY as [NorthingGG],
L.GEOMETRY.STX as [EastingGG],
L.GEOMETRY.STSrid as [SRID],
ludr.MEANING as [DR_Meaning],
lumm.MEANING as [MM_Meaning],
CAST(DateMeasured as DateTime) as DateTimeMeasured
from
NM_Aquifer.dbo.{} as P
join Location as L on L.PointID = P.PointID
join dbo.LU_MeasurementMethod as lumm on lumm.Code = P.MeasurementMethod
join dbo.LU_DataReliability as ludr on ludr.Code = L.DataReliability
where P.PointID=%d
order by P.DateMeasured asc '''.format(TABLE)
return execute_query(sql, p)
def extract_data(p):
sql = '''select *,
L.GEOMETRY.STY as [NorthingGG],
L.GEOMETRY.STX as [EastingGG],
L.GEOMETRY.STSrid as [SRID],
ludr.MEANING as [DR_Meaning],
lumm.MEANING as [MM_Meaning],
luam.MEANING as [AM_Meaning],
CAST(DateMeasured as DateTime) as DateTimeMeasured
from
NM_Aquifer.dbo.{} as P
join Location as L on L.PointID = P.PointID
join dbo.LU_MeasurementMethod as lumm on lumm.Code = P.MeasurementMethod
join dbo.LU_DataReliability as ludr on ludr.Code = L.DataReliability
join dbo.LU_AltitudeMethod as luam on luam.Code = L.AltitudeMethod
where P.PointID=%d
order by P.DateMeasured asc '''.format(TABLE)
return execute_query(sql, p)
def get_things(p):
resp = requests.get("{}/Things?$filter=name eq '{}'".format(ST, p))
return resp.json()['value']
def make_location_properties(record):
return {'altitude': record['Altitude'],
'altitude_accuracy': record['AltitudeAccuracy'],
'altitude_datum': record['AltDatum'],
'altitude_method': record.get('AM_Meaning')}
def make_thing_properties(record):
agency_key = 'PointID'
return {'data_reliability': record['DR_Meaning'],
'project': 'CGWMN',
'measuring_agency': record['MeasuringAgency'],
'organization': 'NMBGMR',
'organization_id': record[agency_key],
'organization_key': agency_key}
def make_sensor(record):
return record['MM_Meaning']
def generate_wl(pid, op):
records = extract_data(pid)
if not records:
records = extract_data2(pid)
if not records:
print('not records for {}'.format(pid))
return
def result(record):
v = record['DepthToWaterBGS']
if v is not None:
return round(v, 2)
location_name = 'NMWDI-$autoinc'
thingid = pid
try:
obj = assemble(location_name, thingid, records, {'n': 'NorthingGG',
'e': 'EastingGG',
'srid': 'SRID',
'time': 'DateTimeMeasured',
'result': result,
'sensor': make_sensor,
'location_properties': make_location_properties,
'observed_property_description': OP_DESCRIPTION,
'datastream_description': DS_DESCRIPTION,
'thing_properties': make_thing_properties})
obj['destination'] = 'https://st.newmexicowaterdata.org/FROST-Server/v1.1'
with open(op, 'w') as wfile:
json.dump(obj, wfile, indent=2)
print('wrote {}. nrecords={}'.format(op, len(records)))
return True
except BaseException as e:
print('Failed making {}. {}'.format(op, e))
def get_pointids():
return [pid['PointID'] for pid in execute_query(PID_SQL)]
def generate_wls():
badpids = []
for pid in ['NM-27127', 'WL-0163', 'WL-0167', 'WL-0168', 'WL-0171',
'WL-0192', 'WL-0195', 'WL-0204', 'WL-0205', 'WL-0206', 'WL-0207']:
# for pid in get_pointids():
# print('pid', pid)
group = pid.split('-')[0]
root = 'data/{}/orig/{}'.format(ROOT, group)
r_mkdir(root)
op = '{}/{}.json'.format(root, pid)
if not os.path.isfile(op):
print('generating {}'.format(pid))
if not generate_wl(pid, op):
badpids.append(pid)
print('badpids', badpids)
def reduce_wls(subdir='orig', tag=None):
for p in get_pointids():
pp = p
if tag:
pp = '{}.{}'.format(p, tag)
path = 'data/{}/{}/{}.json'.format(ROOT, subdir, pp)
if not os.path.isfile(path):
continue
with open(path, 'r') as rfile:
yd = json.load(rfile)
obs = yd['observations']
def convert(o):
t, r = o.split(',')
t = datetime.fromisoformat(t[:-5])
return t
timemask = [(convert(o), i, o.split(',')[0], float(o.split(',')[1])) for i, o in enumerate(obs)]
def key(i):
return i[0].date()
nobs = []
for group, items in groupby(sorted(timemask, key=key), key=key):
# print(group, list(items))
items = sorted(items, key=itemgetter(3))
item = list(items)[0]
nobs.append('{}, {:0.2f}'.format(item[2], item[3]))
print('reduced: {}/{}'.format(len(nobs), len(obs)))
yd['observations'] = nobs
with open('data/{}/reduced/{}.reduced.json'.format(ROOT, p), 'w') as wfile:
json.dump(yd, wfile, indent=2)
# def delete_duplicates():
# for pid in get_pointids():
# things = get_things(pid)
# if len(things) > 1:
# print('thi', things)
# iots = [i['@iot.id'] for i in things]
# print(iots)
#
#
def main():
"""
:return:
"""
# patch_wls()
generate_wls()
# reduce_wls('patched', tag='patched')
# fix_wls()
# patch_wls()
# delete_duplicates()
if __name__ == '__main__':
main()
# ============= EOF =============================================
# def patch_wls():
# for pid in get_pointids():
# print('patching: {}'.format(pid))
# record = extract_thing_properties(pid)[0]
# path = 'data/{}/orig/{}.json'.format(ROOT, pid)
# if not os.path.isfile(path):
# print('not a file. {}'.format(path))
# continue
#
# with open(path, 'r') as rfile:
# yd = json.load(rfile)
#
# location = yd['location']
# location['properties'] = make_location_properties(record)
#
# thing = yd['thing']
# thing['properties'] = make_thing_properties(record)
#
# yd['location'] = location
# yd['thing'] = thing
# yd['sensor'] = {'name': make_sensor(record), 'description': 'No Description'}
#
# path = 'data/{}/patched/{}.patched.json'.format(ROOT, pid)
# with open(path, 'w') as wfile:
# json.dump(yd, wfile, indent=2)
# def sort_wls():
# for p in get_pointids():
# if p == 'AR-0028':
# continue
#
# path = 'data/{}/{}.json'.format(ROOT, p)
# if not os.path.isfile(path):
# continue
#
# with open(path, 'r') as rfile:
# yd = json.load(rfile)
#
# obs = yd['observations']
#
# def skey(obs):
# t, r = obs.split(',')
# t = t.strip()
# return datetime.fromisoformat(t[:-1])
#
# yd['observations'] = sorted(obs, key=skey)
# with open('data/{}/sorted/{}.sorted.json'.format(ROOT, p), 'w') as wfile:
# json.dump(yd, wfile)