wolfhece 2.1.77__py3-none-any.whl → 2.1.79__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.
@@ -1,379 +0,0 @@
1
- """
2
- Author: HECE - University of Liege, Pierre Archambeau
3
- Date: 2024
4
-
5
- Copyright (c) 2024 University of Liege. All rights reserved.
6
-
7
- This script and its content are protected by copyright law. Unauthorized
8
- copying or distribution of this file, via any medium, is strictly prohibited.
9
- """
10
-
11
- import collections
12
- try:
13
- from collections.abc import Iterable
14
- except ImportError:
15
- from collections import Iterable
16
-
17
- QueryOption = collections.namedtuple('QueryOption', ['wildcard', 'list', 'parser'])
18
-
19
- import pandas as pd
20
- import pytz
21
- import re
22
- import requests
23
- from tabulate import tabulate
24
-
25
- import logging
26
- logger = logging.getLogger(__name__)
27
-
28
- basestring = str
29
-
30
- class KIWISError(Exception):
31
- """
32
- Exception for when the KiWIS service responds with an error.
33
- """
34
- pass
35
-
36
- class NoDataError(Exception):
37
- """
38
- Exception for when there was no data returned by the KiWIS service.
39
- """
40
- pass
41
-
42
- class KIWIS(object):
43
- """
44
- Provides access to the KiWIS API at a specified end point.
45
-
46
- :param server_url: The URL to the KiWIS server.
47
- :type server_url: string
48
- :param strict_mode: Perform validation on query options passed as
49
- kwargs and the return_fields list if True. Otherwise pass
50
- through to the KiWIS API which may result in a 500 error if the
51
- query option/return field isn't valid. Default: True
52
- :type strict_mode: boolean
53
- """
54
-
55
- __method_args = {}
56
- __return_args = {}
57
-
58
- def __init__(self, server_url, strict_mode=True):
59
- self.server_url = server_url
60
- self.__default_args = {
61
- 'service': 'kisters',
62
- 'type': 'QueryServices',
63
- 'format': 'json',
64
- }
65
-
66
- self.strict_mode = strict_mode
67
-
68
- def __parse_date(input_dt):
69
- return pd.to_datetime(input_dt).strftime('%Y-%m-%d')
70
-
71
- def __gen_kiwis_method(cls, method_name, available_query_options, available_return_fields):
72
-
73
- start_snake = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', method_name)
74
- snake_name = re.sub('([a-z0-9])([A-Z])', r'\1_\2', start_snake).lower()
75
-
76
- cls._KIWIS__method_args[method_name] = available_query_options
77
- cls._KIWIS__return_args[method_name] = available_return_fields
78
- def kiwis_method(self, return_fields = None, keep_tz=False, **kwargs):
79
-
80
- if self.strict_mode:
81
- for query_key in kwargs.keys():
82
- if query_key not in self._KIWIS__method_args[method_name].keys():
83
- raise ValueError(query_key)
84
-
85
- if (self._KIWIS__method_args[method_name][query_key].list and
86
- isinstance(kwargs[query_key], Iterable) and
87
- not isinstance(kwargs[query_key], basestring)):
88
- kwargs[query_key] = ','.join(kwargs[query_key])
89
-
90
- if self._KIWIS__method_args[method_name][query_key].parser is not None:
91
- kwargs[query_key] = self._KIWIS__method_args[method_name][query_key].parser(kwargs[query_key])
92
-
93
- if return_fields is not None:
94
- for return_key in return_fields:
95
- if return_key not in self._KIWIS__return_args[method_name]:
96
- raise ValueError(return_key)
97
-
98
- params = self._KIWIS__default_args.copy()
99
- params.update(kwargs)
100
- params['request'] = method_name
101
- if return_fields is not None:
102
- params['returnfields'] = ','.join(return_fields)
103
-
104
-
105
- r = requests.get(self.server_url, params = params,verify=False)
106
- logger.debug(r.url)
107
- logger.debug(r.status_code)
108
- r.raise_for_status() #raise error if service returns an error, i.e. 404, 500 etc.
109
-
110
- json_data = r.json()
111
- if type(json_data) is dict and 'type' in json_data.keys() and json_data['type'] == 'error':
112
- raise KIWISError(
113
- 'KIWIS returned an error:\n\tCode: {0}\n\tMessage: "{1}"'.format(
114
- json_data['code'],
115
- json_data['message']
116
- )
117
- )
118
-
119
- if json_data is None or json_data[0] == "No matches.":
120
- raise NoDataError()
121
-
122
- if method_name in [
123
- 'getParameterList',
124
- 'getParameterTypeList',
125
- 'getSiteList',
126
- 'getStationList',
127
- 'getTimeseriesList'
128
- ]:
129
- return pd.DataFrame(json_data[1:], columns = json_data[0])
130
- elif method_name in ['getTimeseriesValues']:
131
- df = pd.DataFrame(json_data[0]['data'], columns = json_data[0]['columns'].split(','))
132
- if 'Timestamp' in df.columns:
133
- df.set_index('Timestamp', inplace = True)
134
- if keep_tz:
135
- hour_offset, minute_offset = map(int, df.index[0].split('+')[1].split(':'))
136
- logger.debug('Using timezone offset %d hour(s) and %d minute(s)', hour_offset, minute_offset)
137
- df.index = pd.to_datetime(df.index).tz_localize('UTC').tz_convert(pytz.FixedOffset(hour_offset*60+minute_offset))
138
- else:
139
- df.index = pd.to_datetime(df.index)
140
- return df
141
- else:
142
- raise NotImplementedError("Method '{0}' has no return implemented.".format(method_name))
143
-
144
- docstring = {}
145
- docstring['doc_intro'] = "Python method to query the '{0}' KiWIS method.".format(method_name)
146
-
147
- docstring['doc_intro'] += "\n\nKeyword arguments are those available in the 'Query field' name list below. "
148
- docstring['doc_intro'] += "That is the keywords match the Queryfield names used by KiWIS."
149
-
150
- docstring['doc_intro'] += "\n\n:param keep_tz: "
151
- docstring['doc_intro'] += "Set to true to prevent the series datetimes from being converted to UTC."
152
- docstring['doc_intro'] += " This optional argument only applies when the returned data includes data with timestamps."
153
- docstring['doc_intro'] += "\n:type keep_tz: boolean"
154
-
155
- docstring['return_fields'] = ":type return_fields: list(string)\n:param return_fields: Optional keyword argument, which is a list made up from the following available fields:\n\n * {0}.".format(',\n * '.join(available_return_fields))
156
-
157
- doc_map = {
158
- True: 'yes',
159
- False: 'no',
160
- None: 'n/a',
161
- }
162
-
163
- option_list = [['Queryfield name', '\* as wildcard', 'accepts list']]
164
- for option_name, option_details in available_query_options.items():
165
- option_list.append(
166
- [
167
- option_name,
168
- doc_map[option_details.wildcard],
169
- doc_map[option_details.list],
170
- ]
171
- )
172
-
173
- docstring['query_option_table'] = ":param kwargs: Queryfield name for keyword argument. Refer to table:\n\n"
174
- docstring['query_option_table'] += tabulate(option_list, headers = 'firstrow', tablefmt = 'rst')
175
-
176
- docstring['returns'] = ":return: Pandas DataFrame with columns based on the default return from KiWIS or based on the return_fields specified.\n"
177
- docstring['returns'] += ":rtype: pandas.DataFrame"
178
-
179
- kiwis_method.__doc__ = "{doc_intro}\n\n{return_fields}\n\n{query_option_table}\n\n{returns}".format(**docstring)
180
-
181
- setattr(cls, snake_name, kiwis_method)
182
-
183
- __gen_kiwis_method(
184
- KIWIS,
185
- 'getTimeseriesList',
186
- {
187
- 'station_no': QueryOption(True, True, None),
188
- 'station_id': QueryOption(False, True, None),
189
- 'station_name': QueryOption(True, True, None),
190
- 'ts_id': QueryOption(False, True, None),
191
- 'ts_path': QueryOption(True, True, None),
192
- 'ts_name': QueryOption(True, True, None),
193
- 'ts_shortname': QueryOption(True, True, None),
194
- 'ts_type_id': QueryOption(False, True, None),
195
- 'parametertype_id': QueryOption(False, True, None),
196
- 'parametertype_name': QueryOption(True, True, None),
197
- 'stationparameter_name': QueryOption(True, True, None),
198
- 'stationparameter_no': QueryOption(False, True, None),
199
- 'ts_unitname': QueryOption(True, True, None),
200
- 'timeseriesgroup_id': QueryOption(False, False, None),
201
- 'fulltext': QueryOption(True, False, None),
202
- },
203
- [
204
- 'station_no',
205
- 'station_id',
206
- 'station_name',
207
- 'station_latitude',
208
- 'station_longitude',
209
- 'station_carteasting',
210
- 'station_cartnorthing',
211
- 'station_georefsystem',
212
- 'station_longname',
213
- 'ts_id',
214
- 'ts_name',
215
- 'ts_shortname',
216
- 'ts_pat',
217
- 'parametertype_id',
218
- 'parametertype_name',
219
- 'stationparameter_name',
220
- 'stationparameter_longname',
221
- 'ts_unitname',
222
- 'ts_unitsymbol',
223
- 'ts_unitname_abs',
224
- 'ts_unitsymbol_abs',
225
- 'coverage',
226
- 'ts_density',
227
- 'datacart',
228
- ]
229
- )
230
-
231
- __gen_kiwis_method(
232
- KIWIS,
233
- 'getTimeseriesValues',
234
- {
235
- 'ts_id': QueryOption(False, True, None),
236
- 'timeseriesgroup_id': QueryOption(False, True, None),
237
- 'ts_path': QueryOption(True, True, None),
238
- 'from': QueryOption(None, None, __parse_date),
239
- 'to': QueryOption(None, None, __parse_date),
240
- 'period': QueryOption(None, None, None),
241
- 'timezone': QueryOption(False, None, None),
242
- },
243
- [
244
- 'Timestamp',
245
- 'Value',
246
- 'Interpolation Type',
247
- 'Quality Code',
248
- 'Aggregation',
249
- 'Accuracy',
250
- 'Absolute Value',
251
- 'AV Interpolation',
252
- 'Type',
253
- 'AV Quality Code',
254
- 'Runoff Value',
255
- 'RV Interpolation',
256
- 'Type',
257
- 'RV Quality Code',
258
- ]
259
- )
260
-
261
- __gen_kiwis_method(
262
- KIWIS,
263
- 'getStationList',
264
- {
265
- 'station_no': QueryOption(True, True, None),
266
- 'station_id': QueryOption(False, True, None),
267
- 'station_name': QueryOption(True, True, None),
268
- 'catchment_no': QueryOption(False, True, None),
269
- 'catchment_id': QueryOption(False, True, None),
270
- 'catchment_name': QueryOption(True, True, None),
271
- 'site_no': QueryOption(False, True, None),
272
- 'site_id': QueryOption(False, True, None),
273
- 'site_name': QueryOption(False, True, None),
274
- 'stationgroup_id': QueryOption(False, False, None),
275
- 'parametertype_id': QueryOption(False, True, None),
276
- 'parametertype_name': QueryOption(True, True, None),
277
- 'stationparameter_name': QueryOption(True, True, None),
278
- },
279
- [
280
- 'station_no',
281
- 'station_id',
282
- 'station_name',
283
- 'catchment_no',
284
- 'catchment_id',
285
- 'catchment_name',
286
- 'station_latitude',
287
- 'station_longitude',
288
- 'station_carteasting',
289
- 'station_cartnorthing',
290
- 'site_no',
291
- 'site_id',
292
- 'site_name',
293
- 'parametertype_id',
294
- 'parametertype_name',
295
- 'stationparameter_name',
296
- 'object_type',
297
- 'station_georefsystem',
298
- 'station_longname',
299
- 'custom_attributes',
300
- ]
301
- )
302
-
303
- __gen_kiwis_method(
304
- KIWIS,
305
- 'getSiteList',
306
- {
307
- 'site_no': QueryOption(False, True, None),
308
- 'site_id': QueryOption(False, True, None),
309
- 'site_name': QueryOption(False, True, None),
310
- 'parametertype_id': QueryOption(False, True, None),
311
- 'parametertype_name': QueryOption(True, True, None),
312
- 'stationparameter_name': QueryOption(True, True, None),
313
- 'bbox': QueryOption(None, None, None),
314
- },
315
- [
316
- 'site_no',
317
- 'site_id',
318
- 'site_name',
319
- 'site_latitude',
320
- 'site_longitude',
321
- 'site_carteasting',
322
- 'site_cartnorthing',
323
- 'site_type_name',
324
- 'site_type_shortname',
325
- 'parametertype_id',
326
- 'parametertype_name',
327
- 'stationparameter_name',
328
- 'site_georefsystem',
329
- 'custom_attributes',
330
- ]
331
- )
332
-
333
- __gen_kiwis_method(
334
- KIWIS,
335
- 'getParameterList',
336
- {
337
- 'station_no': QueryOption(False, True, None),
338
- 'station_id': QueryOption(False, True, None),
339
- 'station_name': QueryOption(True, True, None),
340
- 'site_False': QueryOption(False, True, None),
341
- 'site_id': QueryOption(False, True, None),
342
- 'site_name': QueryOption(True, True, None),
343
- 'stationparameter_id': QueryOption(False, True, None),
344
- 'stationparameter_name': QueryOption(True, True, None),
345
- 'stationparameter_no': QueryOption(False, True, None),
346
- 'stationparameter_longname': QueryOption(True, True, None),
347
- 'parametertype_id': QueryOption(False, True, None),
348
- 'parametertype_name': QueryOption(True, True, None),
349
- 'parametertype_longname': QueryOption(True, True, None),
350
- },
351
- [
352
- 'station_no',
353
- 'station_id',
354
- 'station_name',
355
- 'site_no',
356
- 'site_id',
357
- 'site_name',
358
- 'stationparameter_id',
359
- 'stationparameter_name',
360
- 'stationparameter_no',
361
- 'stationparameter_longname',
362
- 'parametertype_id',
363
- 'parametertype_name',
364
- 'parametertype_longname',
365
- 'parametertype_shortunitname',
366
- 'parametertype_unitname',
367
- ]
368
- )
369
-
370
- __gen_kiwis_method(
371
- KIWIS,
372
- 'getParameterTypeList',
373
- {
374
- 'parametertype_id': QueryOption(False, True, None),
375
- 'parametertype_name': QueryOption(True, True, None),
376
- },
377
- [
378
- ]
379
- )