python-eigen-ingenuity 0.4.37b5__py3-none-any.whl → 0.4.38b1__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.
- eigeningenuity/historianmulti.py +155 -466
- eigeningenuity/util.py +89 -18
- modelbuilder/src/assetmodelbuilder.py +2 -2
- {python_eigen_ingenuity-0.4.37b5.dist-info → python_eigen_ingenuity-0.4.38b1.dist-info}/METADATA +2 -1
- {python_eigen_ingenuity-0.4.37b5.dist-info → python_eigen_ingenuity-0.4.38b1.dist-info}/RECORD +8 -8
- {python_eigen_ingenuity-0.4.37b5.dist-info → python_eigen_ingenuity-0.4.38b1.dist-info}/WHEEL +0 -0
- {python_eigen_ingenuity-0.4.37b5.dist-info → python_eigen_ingenuity-0.4.38b1.dist-info}/entry_points.txt +0 -0
- {python_eigen_ingenuity-0.4.37b5.dist-info → python_eigen_ingenuity-0.4.38b1.dist-info}/top_level.txt +0 -0
eigeningenuity/historianmulti.py
CHANGED
|
@@ -29,10 +29,8 @@ from datetime import datetime
|
|
|
29
29
|
from requests.exceptions import ConnectionError
|
|
30
30
|
from urllib.error import URLError
|
|
31
31
|
from eigeningenuity.core import get_default_server, EigenServer
|
|
32
|
-
from eigeningenuity.util import
|
|
33
|
-
|
|
34
|
-
serverTimeToPythonTime, pythonTimeToServerTime, get_time_tuple, parse_duration, jsonToDf, \
|
|
35
|
-
aggToDf, divide_chunks, flattenDict, csvWriter, multi_response_to_df
|
|
32
|
+
from eigeningenuity.util import force_list, time_to_epoch_millis, EigenException, \
|
|
33
|
+
multi_response_to_df, merge_tags_from_response, update_keys, _do_historian_multi_request, format_output
|
|
36
34
|
|
|
37
35
|
from urllib3.exceptions import InsecureRequestWarning
|
|
38
36
|
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
|
|
@@ -42,11 +40,16 @@ class HistorianMulti (object):
|
|
|
42
40
|
"""A Historian which talks the Eigen Historian Json Bridge protocol.
|
|
43
41
|
"""
|
|
44
42
|
|
|
45
|
-
def __init__(self,
|
|
43
|
+
def __init__(self, baseurl, auth, historian):
|
|
46
44
|
"""This is a constructor. It takes in a URL like http://infra:8080/historian-servlet/jsonbridge/Demo-influxdb"""
|
|
47
|
-
self.
|
|
48
|
-
self.
|
|
45
|
+
self.baseurl = baseurl
|
|
46
|
+
self.serverurl = baseurl + "multi/"
|
|
47
|
+
self.writeurl = baseurl + "write/points"
|
|
49
48
|
self.auth = auth
|
|
49
|
+
self.historian = ""
|
|
50
|
+
if historian:
|
|
51
|
+
self.historian = historian + "/"
|
|
52
|
+
|
|
50
53
|
|
|
51
54
|
def _testConnection(self):
|
|
52
55
|
try:
|
|
@@ -57,12 +60,15 @@ class HistorianMulti (object):
|
|
|
57
60
|
except (URLError, ConnectionError):
|
|
58
61
|
raise ConnectionError ("Failed to connect to ingenuity instance at " + self.serverurl + ". Please check the url is correct and the instance is up.")
|
|
59
62
|
|
|
60
|
-
def getCurrentDataPoints(self,tags: Union[str, list], output: str = "json"
|
|
63
|
+
def getCurrentDataPoints(self,tags: Union[str, list], output: str = "json"):
|
|
64
|
+
tags = force_list(tags)
|
|
61
65
|
body = {
|
|
62
66
|
"requests": {}
|
|
63
67
|
}
|
|
64
68
|
|
|
65
69
|
for tag in tags:
|
|
70
|
+
if "/" not in tag:
|
|
71
|
+
tag = self.historian + tag
|
|
66
72
|
request = {
|
|
67
73
|
"type": "CURRENT_POINT",
|
|
68
74
|
"tag": tag,
|
|
@@ -71,14 +77,14 @@ class HistorianMulti (object):
|
|
|
71
77
|
|
|
72
78
|
body["requests"][tag] = request
|
|
73
79
|
|
|
74
|
-
response =
|
|
75
|
-
|
|
80
|
+
response = _do_historian_multi_request(self.serverurl,body,self.auth)
|
|
81
|
+
|
|
76
82
|
|
|
77
83
|
if output == "raw":
|
|
78
84
|
return response
|
|
79
85
|
elif output == "json":
|
|
80
|
-
if len(
|
|
81
|
-
return items[tags]
|
|
86
|
+
if len(tags) == 1:
|
|
87
|
+
return items[tags[0]]
|
|
82
88
|
else:
|
|
83
89
|
return items
|
|
84
90
|
elif output == "string":
|
|
@@ -89,13 +95,13 @@ class HistorianMulti (object):
|
|
|
89
95
|
|
|
90
96
|
|
|
91
97
|
def getInterpolatedPoints(self, tags: Union[str, list], timestamps: Union[list, int, float, str, datetime],
|
|
92
|
-
output: str = "json"
|
|
98
|
+
output: str = "json"):
|
|
93
99
|
"""
|
|
94
100
|
Return a specified number of interpolated datapoints between a start and end timestamp for one or more datatags
|
|
95
101
|
|
|
96
102
|
Args:
|
|
97
|
-
tags: A datatag, or list of datatags
|
|
98
|
-
timestamps: One or more timestamps for which to return a datapoint. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
|
|
103
|
+
tags: A datatag (string), or list of datatags
|
|
104
|
+
timestamps: One (string) or more (list) timestamps for which to return a datapoint. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
|
|
99
105
|
output (Optional): The format in which to return the data. Accepts one of: "raw" - The raw json returned by the API, "json" - A processed version of the json response, "df" - A formatted pandas dataframe object. Defaults to "json".
|
|
100
106
|
|
|
101
107
|
Returns:
|
|
@@ -111,45 +117,40 @@ class HistorianMulti (object):
|
|
|
111
117
|
"requests": {}
|
|
112
118
|
}
|
|
113
119
|
|
|
120
|
+
tags = force_list(tags)
|
|
121
|
+
timestamps = force_list(timestamps)
|
|
122
|
+
timestamps = [time_to_epoch_millis(timestamp) for timestamp in timestamps]
|
|
123
|
+
|
|
114
124
|
for tag in tags:
|
|
115
|
-
|
|
125
|
+
if "/" not in tag:
|
|
126
|
+
tag = self.historian + tag
|
|
127
|
+
for index, timestamp in enumerate(timestamps):
|
|
116
128
|
request = {
|
|
117
|
-
"type": "
|
|
129
|
+
"type": "HISTORICAL_POINT",
|
|
118
130
|
"tag": tag,
|
|
119
131
|
"details": {
|
|
120
132
|
"at": timestamp
|
|
121
133
|
}
|
|
122
134
|
}
|
|
123
135
|
|
|
124
|
-
body[tag +"-"+
|
|
136
|
+
body["requests"][tag.split("/")[1] + "-" + str(index)] = request
|
|
125
137
|
|
|
126
138
|
|
|
127
|
-
response =
|
|
128
|
-
items = response["results"]
|
|
139
|
+
response = _do_historian_multi_request(self.serverurl,body,self.auth)
|
|
140
|
+
items = merge_tags_from_response(response["results"])
|
|
129
141
|
|
|
130
|
-
|
|
131
|
-
return response
|
|
132
|
-
elif output == "json":
|
|
133
|
-
if len(force_list(tags)) == 1:
|
|
134
|
-
return items[tags]
|
|
135
|
-
else:
|
|
136
|
-
return items
|
|
137
|
-
elif output == "string":
|
|
138
|
-
return json.dumps(items)
|
|
139
|
-
elif output == "df":
|
|
140
|
-
return multi_response_to_df(items)
|
|
141
|
-
return None
|
|
142
|
+
return format_output(output,items,tags,timestamps)
|
|
142
143
|
|
|
143
144
|
|
|
144
|
-
def
|
|
145
|
-
|
|
146
|
-
"""Return
|
|
145
|
+
def getInterpolatedRange(self, tags: Union[str, list], start: Union[int, float, str, datetime],
|
|
146
|
+
end: Union[int, float, str, datetime], count: int = 1000, output: str = "json"):
|
|
147
|
+
"""Return a specified number of interpolated datapoints between a start and end timestamp for one or more datatags
|
|
147
148
|
|
|
148
149
|
Args:
|
|
149
150
|
tags: A datatag, or list of datatags
|
|
150
151
|
start: Start of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
|
|
151
152
|
end: End of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
|
|
152
|
-
|
|
153
|
+
count (Optional): Number of points to return, evenly spaced across the given time range. Defaults to 1000
|
|
153
154
|
output (Optional): The format in which to return the data. Accepts one of: "raw" - The raw json returned by the API, "json" - A processed version of the json response, "df" - A formatted pandas dataframe object. Defaults to "json".
|
|
154
155
|
|
|
155
156
|
Returns:
|
|
@@ -161,48 +162,41 @@ class HistorianMulti (object):
|
|
|
161
162
|
RemoteServerException: When the provided historian could not be found, or the API response contains an error
|
|
162
163
|
RunTimeError/HTTPError: No response from the API
|
|
163
164
|
"""
|
|
164
|
-
validOutputTypes = ["raw", "json", "df", "csv", "string"]
|
|
165
|
-
if output not in validOutputTypes:
|
|
166
|
-
raise ValueError("output must be one of %r." % validOutputTypes)
|
|
167
|
-
args = {}
|
|
168
|
-
args['tag'] = force_list(tags)
|
|
169
|
-
args['start'] = time_to_epoch_millis(start)
|
|
170
|
-
args['end'] = time_to_epoch_millis(end)
|
|
171
|
-
args['maxpoints'] = maxpoints
|
|
172
|
-
response = self._doJsonRequest("getraw", args)
|
|
173
|
-
items = response["items"]
|
|
174
|
-
|
|
175
|
-
if response['unknown'] != []:
|
|
176
|
-
if items == {}:
|
|
177
|
-
raise EigenException("None of the provided tags could be found in historian " + self.historian)
|
|
178
|
-
logging.warning("Could not find tags: " + str(response["unknown"]) + " in historian " + self.historian)
|
|
179
165
|
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
if len(force_list(tags)) == 1:
|
|
184
|
-
return items[tags]
|
|
185
|
-
else:
|
|
186
|
-
return items
|
|
187
|
-
elif output == "string":
|
|
188
|
-
return json.dumps(items)
|
|
189
|
-
elif output == "df":
|
|
190
|
-
return jsonToDf(items)
|
|
191
|
-
elif output == "csv":
|
|
192
|
-
return csvWriter(items,self.historian,filepath,multi_csv,"GetRaw")
|
|
193
|
-
return None
|
|
166
|
+
body = {
|
|
167
|
+
"requests": {}
|
|
168
|
+
}
|
|
194
169
|
|
|
170
|
+
tags = force_list(tags)
|
|
195
171
|
|
|
172
|
+
for tag in tags:
|
|
173
|
+
if "/" not in tag:
|
|
174
|
+
tag = self.historian + tag
|
|
175
|
+
request = {
|
|
176
|
+
"type": "INTERPOLATED_POINTS",
|
|
177
|
+
"tag": tag,
|
|
178
|
+
"details": {
|
|
179
|
+
"from": time_to_epoch_millis(start),
|
|
180
|
+
"to": time_to_epoch_millis(end),
|
|
181
|
+
"count": count
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
body["requests"][tag.split("/")[1]] = request
|
|
196
186
|
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
187
|
+
response = _do_historian_multi_request(self.serverurl,body,self.auth)
|
|
188
|
+
|
|
189
|
+
return format_output(output,response,tags)
|
|
190
|
+
|
|
191
|
+
def getRawDatapoints(self, tags: Union[str, list], start: Union[int, float, str, datetime],
|
|
192
|
+
end: Union[int, float, str, datetime], maxpoints: int = 1000, output: str = "json"):
|
|
193
|
+
"""Return up to a specified number of raw datapoints between a start and end timestamp for one or more datatags
|
|
200
194
|
|
|
201
195
|
Args:
|
|
202
196
|
tags: A datatag, or list of datatags
|
|
203
197
|
start: Start of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
|
|
204
198
|
end: End of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
|
|
205
|
-
|
|
199
|
+
maxPoints (Optional): Max number of points to return. The query will return raw points in sequence from the first raw point in the timespan, until the end, or the point limit is reached. Defaults to 1000
|
|
206
200
|
output (Optional): The format in which to return the data. Accepts one of: "raw" - The raw json returned by the API, "json" - A processed version of the json response, "df" - A formatted pandas dataframe object. Defaults to "json".
|
|
207
201
|
|
|
208
202
|
Returns:
|
|
@@ -214,449 +208,144 @@ class HistorianMulti (object):
|
|
|
214
208
|
RemoteServerException: When the provided historian could not be found, or the API response contains an error
|
|
215
209
|
RunTimeError/HTTPError: No response from the API
|
|
216
210
|
"""
|
|
217
|
-
validOutputTypes = ["raw", "json", "df", "csv", "string"]
|
|
218
|
-
if output not in validOutputTypes:
|
|
219
|
-
raise ValueError("output must be one of %r." % validOutputTypes)
|
|
220
|
-
args = {}
|
|
221
|
-
args['tag'] = force_list(tags)
|
|
222
|
-
args['start'] = time_to_epoch_millis(start)
|
|
223
|
-
args['end'] = time_to_epoch_millis(end)
|
|
224
|
-
args['count'] = count
|
|
225
|
-
response = self._doJsonRequest("getrange", args)
|
|
226
|
-
items = response["items"]
|
|
227
|
-
|
|
228
|
-
if response['unknown'] != []:
|
|
229
|
-
if items == {}:
|
|
230
|
-
raise EigenException("None of the provided tags could be found in historian " + self.historian)
|
|
231
|
-
logging.warning("Could not find tags: " + str(response["unknown"]) + " in historian " + self.historian)
|
|
232
211
|
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
if len(force_list(tags)) == 1:
|
|
237
|
-
return items[tags]
|
|
238
|
-
else:
|
|
239
|
-
return items
|
|
240
|
-
elif output == "string":
|
|
241
|
-
return json.dumps(items)
|
|
242
|
-
elif output == "df":
|
|
243
|
-
return jsonToDf(items)
|
|
244
|
-
elif output == "csv":
|
|
245
|
-
return csvWriter(items,self.historian,filepath,multi_csv,"GetInterpolatedRange")
|
|
246
|
-
return None
|
|
247
|
-
|
|
248
|
-
def getAggregates(self, tags: Union[str, list], start: Union[int, float, str, datetime],
|
|
249
|
-
end: Union[int, float, str, datetime], fields: Union[str, list] = None, count: int = 1,
|
|
250
|
-
output: str = "json", filepath:str=None, multi_csv:bool=False):
|
|
251
|
-
"""
|
|
252
|
-
Return specified aggregates of tags over a given time window, optionally divided into equal parts
|
|
253
|
-
|
|
254
|
-
Args:
|
|
255
|
-
tags: A datatag, or list of datatags
|
|
256
|
-
start: Start of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
|
|
257
|
-
end: End of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
|
|
258
|
-
fields (Optional): The aggregates to be calculated, accepts any subset of ["min","max","mean","stddev","var","numgood","numbad"]. Defaults to all aggregates.
|
|
259
|
-
count (Optional): Number of intervals to split the time window into, returning aggregates over each interval. Defaults to 1
|
|
260
|
-
output (Optional): The format in which to return the data. Accepts one of: "raw" - The raw json returned by the API, "json" - A processed version of the json response, "df" - A formatted pandas dataframe object. Defaults to "json".
|
|
261
|
-
|
|
262
|
-
Returns:
|
|
263
|
-
Timestamps, values and statuses for each datapoint returned, the format is dependent on the output parameter
|
|
212
|
+
body = {
|
|
213
|
+
"requests": {}
|
|
214
|
+
}
|
|
264
215
|
|
|
265
|
-
|
|
266
|
-
ValueError: When invalid Output Type is given
|
|
267
|
-
URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
|
|
268
|
-
RemoteServerException: When the provided historian could not be found, or the API response contains an error
|
|
269
|
-
RunTimeError/HTTPError: No response from the API
|
|
270
|
-
"""
|
|
271
|
-
validOutputTypes = ["raw", "json", "df", "csv", "string"]
|
|
272
|
-
if output not in validOutputTypes:
|
|
273
|
-
raise ValueError("output must be one of %r." % validOutputTypes)
|
|
274
|
-
args = {}
|
|
275
|
-
args['tag'] = force_list(tags)
|
|
276
|
-
args['start'] = time_to_epoch_millis(start)
|
|
277
|
-
args['end'] = time_to_epoch_millis(end)
|
|
278
|
-
args['count'] = count
|
|
279
|
-
args['aggfields'] = fields
|
|
280
|
-
|
|
281
|
-
response = self._doJsonRequest("getagg", args)
|
|
282
|
-
|
|
283
|
-
keys = set(response.keys())
|
|
284
|
-
missing = [x for x in args['tag'] if x not in keys]
|
|
285
|
-
|
|
286
|
-
if missing != []:
|
|
287
|
-
if response == {}:
|
|
288
|
-
raise EigenException("None of the provided tags could be found in historian " + self.historian)
|
|
289
|
-
logging.warning("Could not find tags: " + str(missing) + " in historian " + self.historian)
|
|
216
|
+
tags = force_list(tags)
|
|
290
217
|
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
return None
|
|
218
|
+
for tag in tags:
|
|
219
|
+
if "/" not in tag:
|
|
220
|
+
tag = self.historian + tag
|
|
221
|
+
request = {
|
|
222
|
+
"type": "RAW_POINTS",
|
|
223
|
+
"tag": tag,
|
|
224
|
+
"details": {
|
|
225
|
+
"from": time_to_epoch_millis(start),
|
|
226
|
+
"to": time_to_epoch_millis(end),
|
|
227
|
+
"maxPoints": maxpoints
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
body["requests"][tag.split("/")[1]] = request
|
|
306
232
|
|
|
233
|
+
response = _do_historian_multi_request(self.serverurl,body,self.auth)
|
|
307
234
|
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
"""
|
|
312
|
-
Return specified aggregates of tags over a given time window, optionally divided into equal parts
|
|
235
|
+
return format_output(output,response,tags)
|
|
236
|
+
|
|
237
|
+
def writeToTag(self, tag:str, points: Union[dict, list]):
|
|
238
|
+
"""Write one or more points to a single tag
|
|
313
239
|
|
|
314
240
|
Args:
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
end: End of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
|
|
318
|
-
window (Optional): Sub-interval of time to divide the timeframe into as a multiple of seconds,minutes,hours,days or years. (e.g. "1d" for 1 day or "2h" for 2 hours etc). Defaults to the entire timeframe.
|
|
319
|
-
fields (Optional): The aggregates to be calculated, accepts any subset of ["min","max","mean","stddev","var","numgood","numbad"]. Defaults to all aggregates.
|
|
320
|
-
output (Optional): The format in which to return the data. Accepts one of: "raw" - The raw json returned by the API, "json" - A processed version of the json response, "df" - A formatted pandas dataframe object. Defaults to "json".
|
|
241
|
+
tag: A datatag
|
|
242
|
+
points: A dict, or list of dicts of the form {"value": x, "timestamp": y}. Where x is an int/double and y is a python datetime, iso datetime string, or epoch timestamp
|
|
321
243
|
|
|
322
244
|
Returns:
|
|
323
|
-
|
|
245
|
+
A dict with keys: success (bool) representing the success of the request. message (str) forwarded from the api.
|
|
324
246
|
|
|
325
247
|
Raises:
|
|
326
|
-
ValueError: When invalid Output Type is given
|
|
327
248
|
URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
|
|
328
249
|
RemoteServerException: When the provided historian could not be found, or the API response contains an error
|
|
329
250
|
RunTimeError/HTTPError: No response from the API
|
|
330
251
|
"""
|
|
331
|
-
|
|
332
|
-
if
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
252
|
+
points = force_list(points)
|
|
253
|
+
if "/" not in tag:
|
|
254
|
+
tag = self.historian + tag
|
|
255
|
+
|
|
256
|
+
for point in points:
|
|
257
|
+
if "status" not in point.keys():
|
|
258
|
+
point['status'] = "OK"
|
|
259
|
+
point['timestamp'] = time_to_epoch_millis(point['timestamp'])
|
|
260
|
+
|
|
261
|
+
body = {
|
|
262
|
+
"points": {
|
|
263
|
+
tag: points
|
|
264
|
+
},
|
|
265
|
+
"createTags": True
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
message = _do_historian_multi_request(self.writeurl,body,self.auth,True)
|
|
269
|
+
|
|
270
|
+
if message == 'All points written!':
|
|
271
|
+
ret = {"success": True, "message": message}
|
|
343
272
|
else:
|
|
344
|
-
|
|
345
|
-
if count > 1000:
|
|
346
|
-
logging.warning(
|
|
347
|
-
"getAggregateIntervals is only designed to return up to 1000 aggregate sets, currently returning " + str(
|
|
348
|
-
count) + " sets. This may return overlapping intervals")
|
|
349
|
-
|
|
350
|
-
args = {}
|
|
351
|
-
args['tag'] = force_list(tags)
|
|
352
|
-
args['start'] = epoch_ms_start
|
|
353
|
-
args['end'] = epoch_ms_end
|
|
354
|
-
args['count'] = count
|
|
355
|
-
args['aggfields'] = fields
|
|
356
|
-
response = self._doJsonRequest("getagg", args)
|
|
357
|
-
|
|
358
|
-
keys = set(response.keys())
|
|
359
|
-
missing = [x for x in args['tag'] if x not in keys]
|
|
360
|
-
|
|
361
|
-
if missing != []:
|
|
362
|
-
if response == {}:
|
|
363
|
-
raise EigenException("None of the provided tags could be found in historian " + self.historian)
|
|
364
|
-
logging.warning("Could not find tags: " + str(missing) + " in historian " + self.historian)
|
|
273
|
+
ret = {"success": False, "message": message}
|
|
365
274
|
|
|
366
|
-
|
|
367
|
-
return response
|
|
368
|
-
elif output == "json":
|
|
369
|
-
if len(force_list(tags)) == 1:
|
|
370
|
-
return response[tags]
|
|
371
|
-
else:
|
|
372
|
-
return response
|
|
373
|
-
elif output == "string":
|
|
374
|
-
return json.dumps(response)
|
|
375
|
-
elif output == "df":
|
|
376
|
-
return aggToDf(response,fields)
|
|
377
|
-
elif output == "csv":
|
|
378
|
-
order = ["tag","start","end","min","max","avg","var","stddev","count","numgood","numbad"]
|
|
379
|
-
return csvWriter(response,self.historian,filepath,multi_csv,"GetAggregateIntervals",order,True)
|
|
275
|
+
return ret
|
|
380
276
|
|
|
381
277
|
|
|
382
|
-
def
|
|
383
|
-
"""
|
|
384
|
-
Return the number of raw points of tags over a given time window
|
|
278
|
+
def writeToMultipleTags(self, data:Union[dict,list]):
|
|
279
|
+
"""Write one or more points to multiple tags
|
|
385
280
|
|
|
386
281
|
Args:
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
end: End of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
|
|
390
|
-
output (Optional): The format in which to return the data. Accepts one of: "raw" - The raw json returned by the API, "json" - A processed version of the json response, "df" - A formatted pandas dataframe object. Defaults to "json".
|
|
391
|
-
|
|
282
|
+
payloads: A dict (or list of dicts) of the form {tag1: [{"value": x, "timestamp": y}, ...], tag2: [...], ...}
|
|
283
|
+
|
|
392
284
|
Returns:
|
|
393
|
-
|
|
285
|
+
None
|
|
394
286
|
|
|
395
287
|
Raises:
|
|
396
|
-
ValueError: When invalid Output Type is given
|
|
397
288
|
URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
|
|
398
289
|
RemoteServerException: When the provided historian could not be found, or the API response contains an error
|
|
399
290
|
RunTimeError/HTTPError: No response from the API
|
|
400
291
|
"""
|
|
401
|
-
|
|
402
|
-
if output not in validOutputTypes:
|
|
403
|
-
raise ValueError("output must be one of %r." % validOutputTypes)
|
|
404
|
-
ret = {}
|
|
405
|
-
aggs = self.getAggregates(force_list(tags), start, end, "COUNT", 1, "raw")
|
|
406
|
-
for tag in aggs.keys():
|
|
407
|
-
ret[tag] = aggs[tag][0]["count"]
|
|
408
|
-
|
|
409
|
-
response = self._matchArgumentCardinality(tags, ret)
|
|
410
|
-
|
|
411
|
-
if output == "raw" or output == "json":
|
|
412
|
-
return response
|
|
413
|
-
elif output == "string":
|
|
414
|
-
return json.dumps(response)
|
|
415
|
-
elif output == "df":
|
|
416
|
-
df = jsonToDf({"No. of Points": response})
|
|
417
|
-
return df
|
|
418
|
-
return None
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
def _writeDataPoints(self, data) -> bool:
|
|
422
|
-
rawdata = {}
|
|
423
|
-
for tag in list(data.keys()):
|
|
424
|
-
rawdps = []
|
|
425
|
-
for dp in force_list(data[tag]):
|
|
426
|
-
rawdps.append([int(dp.getTimestamp() * 1000), dp.getValue(), dp.getStatus()])
|
|
427
|
-
rawdata[tag] = rawdps
|
|
428
|
-
|
|
429
|
-
return self._doJsonRequest("write", {'write': json.dumps(rawdata)})
|
|
430
|
-
|
|
431
|
-
def createDataTag(self, tag:str, units:str, description:str) -> bool:
|
|
432
|
-
"""
|
|
433
|
-
Create a new tag, or update the metadata of an existing tag
|
|
434
|
-
|
|
435
|
-
Args:
|
|
436
|
-
tag: The unique identifier of the tag
|
|
437
|
-
units: The unit of the values stored in the tag
|
|
438
|
-
description: A short explanation of the tags purpose or content
|
|
292
|
+
data = force_list(data)
|
|
439
293
|
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
ret. If proto is a single value, it extracts that key from ret and
|
|
457
|
-
returns that instead.
|
|
458
|
-
The intention is that:
|
|
459
|
-
getTagThing("myTag") returns Thing for myTag
|
|
460
|
-
getTagThing(["myTag", "myOtherTag"]) returns {'myTag': Thing, 'myOtherTag': OtherThing}
|
|
461
|
-
and for clarification:
|
|
462
|
-
getTagThing(["myTag"]) returns {'myTag': Thing}
|
|
463
|
-
"""
|
|
464
|
-
try:
|
|
465
|
-
badTags = []
|
|
466
|
-
if is_list(proto):
|
|
467
|
-
if ret != {}:
|
|
468
|
-
if len(ret) < len(proto):
|
|
469
|
-
for i in proto:
|
|
470
|
-
if i not in ret:
|
|
471
|
-
badTags.append(i)
|
|
472
|
-
return ret
|
|
473
|
-
else:
|
|
474
|
-
raise KeyError
|
|
475
|
-
return ret[proto]
|
|
476
|
-
except KeyError:
|
|
477
|
-
raise KeyError("Could not find tag(s): " + str(proto))
|
|
294
|
+
payload = {}
|
|
295
|
+
tags = []
|
|
296
|
+
|
|
297
|
+
for item in data:
|
|
298
|
+
if set(item.keys()).intersection(set(tags)):
|
|
299
|
+
for tag in set(item.keys()).intersection(set(tags)):
|
|
300
|
+
payload[tag] += item[tag]
|
|
301
|
+
item.pop(tag)
|
|
302
|
+
payload = payload | item
|
|
303
|
+
tags += item.keys()
|
|
304
|
+
|
|
305
|
+
for key in payload.keys():
|
|
306
|
+
for datapoint in payload[key]:
|
|
307
|
+
if "status" not in datapoint.keys():
|
|
308
|
+
datapoint['status'] = "OK"
|
|
309
|
+
datapoint['timestamp'] = time_to_epoch_millis(datapoint['timestamp'])
|
|
478
310
|
|
|
479
|
-
|
|
480
|
-
"""
|
|
481
|
-
Writes point data to a single existing tag.
|
|
311
|
+
payload = update_keys(payload, self.historian)
|
|
482
312
|
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
313
|
+
body = {
|
|
314
|
+
"points": payload,
|
|
315
|
+
"createTags": True
|
|
316
|
+
}
|
|
486
317
|
|
|
487
|
-
|
|
488
|
-
Success: A boolean representing the successful push of data.
|
|
489
|
-
"""
|
|
490
|
-
points = force_list(points)
|
|
318
|
+
message = _do_historian_multi_request(self.writeurl,body,self.auth,True)
|
|
491
319
|
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
datapoints[tag].append(DataPoint(point["value"],point["timestamp"],point["status"]))
|
|
320
|
+
if message == 'All points written!':
|
|
321
|
+
ret = {"success": True, "message": message}
|
|
322
|
+
else:
|
|
323
|
+
ret = {"success": False, "message": message}
|
|
497
324
|
|
|
498
|
-
return
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
def batchCSVImport(self, filepaths: Union[str,list]) -> bool:
|
|
502
|
-
"""
|
|
503
|
-
Writes tag data from one or more csv file to Ingenuity. Will create a tag if it does not exist.
|
|
325
|
+
return ret
|
|
504
326
|
|
|
505
|
-
Args:
|
|
506
|
-
filepaths: The paths to one or more csv files. CSV Layouts must be as follows, with one point per line: tag,value,timestamp,status,units,description
|
|
507
327
|
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
"""
|
|
511
|
-
success = []
|
|
512
|
-
for filepath in force_list(filepaths):
|
|
513
|
-
with open(filepath, "r") as file:
|
|
514
|
-
csv_reader = csv.reader(file, delimiter=',')
|
|
515
|
-
data = list(csv_reader)
|
|
516
|
-
# Upload in batches of 500 to avoid API timeouts/throttling
|
|
517
|
-
chunks = divide_chunks(data, 500)
|
|
518
|
-
for chunk in chunks:
|
|
519
|
-
datapoints = {}
|
|
520
|
-
for item in chunk:
|
|
521
|
-
|
|
522
|
-
self.createDataTag(item[0], item[4], item[5])
|
|
523
|
-
try:
|
|
524
|
-
datapoints[item[0]].append(DataPoint(item[1], int(item[2]), item[3]))
|
|
525
|
-
except KeyError:
|
|
526
|
-
datapoints[item[0]] = [DataPoint(item[1], int(item[2]), item[3])]
|
|
527
|
-
success.append(self._writeDataPoints(datapoints))
|
|
528
|
-
file.close()
|
|
529
|
-
return all(success)
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
def batchJsonImport(self, data:Union[dict,list]) -> bool:
|
|
533
|
-
"""
|
|
534
|
-
Writes datapoints from dict objects to tags in the Ingenuity historian.
|
|
328
|
+
def createPoint(value:Union[int,float],timestamp:Union[int,str,datetime],status:str="OK"):
|
|
329
|
+
"""Quickly Create a dict of the format required to push data to historians
|
|
535
330
|
|
|
536
331
|
Args:
|
|
537
|
-
|
|
332
|
+
value: The value to be pushed
|
|
333
|
+
timestamp: The timestamp to assign the value to. Accepts formats of epoch milliseconds, python datetimes, and iso format datetime strings
|
|
334
|
+
status: (Optional) Indicates the quality of the data, accepts "OK" or "BAD". Defaults to "OK"
|
|
538
335
|
|
|
539
336
|
Returns:
|
|
540
|
-
A
|
|
541
|
-
"""
|
|
542
|
-
success = []
|
|
543
|
-
data = force_list(data)
|
|
544
|
-
for datum in data:
|
|
545
|
-
datapoints = {}
|
|
546
|
-
totalPoints = 0
|
|
547
|
-
tags = datum.keys()
|
|
548
|
-
for tag in tags:
|
|
549
|
-
# Upload in batches of 500 to avoid API timeouts/throttling
|
|
550
|
-
if totalPoints >= 500:
|
|
551
|
-
self._writeDataPoints(datapoints)
|
|
552
|
-
datapoints = {}
|
|
553
|
-
totalPoints = 0
|
|
554
|
-
|
|
555
|
-
for item in datum[tag]:
|
|
556
|
-
try:
|
|
557
|
-
datapoints[tag].append(DataPoint(item["value"],item["timestamp"],item["status"]))
|
|
558
|
-
except:
|
|
559
|
-
datapoints[tag] = [DataPoint(item["value"], item["timestamp"], item["status"])]
|
|
560
|
-
totalPoints += len(datapoints[tag])
|
|
561
|
-
|
|
562
|
-
success.append(self._writeDataPoints(datapoints))
|
|
563
|
-
return all(success)
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
class DataPoint(object): # LEGACY OBJECT
|
|
567
|
-
"""This class represents a data point which has a value and a python timestamp, and optionally a status of 'OK' or 'BAD'.
|
|
568
|
-
Timestamp is stored in epochseconds. The constructor will convert datetime and tuples into floating point epoch seconds.
|
|
569
|
-
"""
|
|
570
|
-
|
|
571
|
-
def __init__(self, value, timestamp, status = 'OK'):
|
|
572
|
-
"""This constructor takes in a value, a python timestamp (epoch floating point seconds or datetime or tuple)
|
|
573
|
-
and an optional status. Status is either "OK" or "BAD" and will default to "OK"
|
|
337
|
+
A structured dict for use in the WriteToTag method
|
|
574
338
|
"""
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
if status is None:
|
|
579
|
-
self.status = "OK"
|
|
580
|
-
elif status == "OK" or status == "BAD":
|
|
581
|
-
self.status = status
|
|
582
|
-
else:
|
|
583
|
-
raise EigenException("Unrecognised Status")
|
|
584
|
-
|
|
585
|
-
# Convert timestamp from python datetime or tuple into python floating point epoch seconds
|
|
586
|
-
self.datetime = datetime.fromtimestamp(time_to_epoch_millis(timestamp)/1000)
|
|
587
|
-
self.timestamp = pythonTimeToFloatingSecs(time_to_epoch_millis(timestamp)/1000)
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
def __str__(self):
|
|
591
|
-
"""Return a nicely formatted version of the datapoint"""
|
|
592
|
-
val = self.value
|
|
593
|
-
if type(val) != str:
|
|
594
|
-
val = str(number_to_string(val))
|
|
595
|
-
else:
|
|
596
|
-
val = val.ljust(12)
|
|
597
|
-
return val + " @ " + get_timestamp_string(self.timestamp) + " - " + self.status
|
|
598
|
-
|
|
599
|
-
def __repr__(self):
|
|
600
|
-
return "DataPoint[" + str(self) + "]"
|
|
601
|
-
|
|
602
|
-
def getValue(self):
|
|
603
|
-
"""Return the value of the datapoint"""
|
|
604
|
-
return self.value
|
|
605
|
-
|
|
606
|
-
def getTimestamp(self):
|
|
607
|
-
"""Return the timestamp of the datapoint in python floating point epoch seconds"""
|
|
608
|
-
return self.timestamp
|
|
609
|
-
|
|
610
|
-
def getTimestampMillis(self):
|
|
611
|
-
"""Return the timestamp of the datapoint in epochmillis"""
|
|
612
|
-
return pythonTimeToServerTime(self.timestamp)
|
|
613
|
-
|
|
614
|
-
def getTimestampAsDatetime(self):
|
|
615
|
-
"""Return the timestamp of the datapoint as Datetime"""
|
|
616
|
-
return get_datetime(self.timestamp)
|
|
617
|
-
|
|
618
|
-
def getTimestampAsTuple(self):
|
|
619
|
-
"""Return the timestamp of the datapoint as Tuple"""
|
|
620
|
-
return get_time_tuple(self.timestamp)
|
|
621
|
-
|
|
622
|
-
def getStatus(self):
|
|
623
|
-
"""Return the status of the datapoint - either 'OK' or 'BAD'"""
|
|
624
|
-
return self.status
|
|
625
|
-
|
|
626
|
-
def isBad(self):
|
|
627
|
-
"""Returns either True if status = "BAD" or false if status = "OK" """
|
|
628
|
-
return self.status != "OK"
|
|
629
|
-
|
|
630
|
-
def __eq__(self, other):
|
|
631
|
-
if isinstance(other, self.__class__):
|
|
632
|
-
return self.__dict__ == other.__dict__
|
|
633
|
-
else:
|
|
634
|
-
return False
|
|
635
|
-
|
|
636
|
-
def getAsJson(self):
|
|
637
|
-
"""Return as a json map with the timestamp in milliseconds"""
|
|
638
|
-
return "{" + "\"value\":" + str(self.value) + ",\"timestamp\":" + self.getTimestampMillis(
|
|
639
|
-
self) + ",\"status\":\"" + self.status + "\"}"
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
def get_datapoint(dp):
|
|
643
|
-
tag = dp["tag"]
|
|
644
|
-
value = dp["value"]
|
|
645
|
-
timestamp = dp["timestamp"]
|
|
646
|
-
timestampinmillis = dp["timestamp"]
|
|
647
|
-
timestamp = serverTimeToPythonTime(timestampinmillis)
|
|
648
|
-
status = dp["status"]
|
|
649
|
-
return DataPoint(tag, value, timestamp, status)
|
|
650
|
-
|
|
651
|
-
def createPoint(value:Union[str,int,float],timestamp:int,status:str):
|
|
339
|
+
if status not in ["OK","BAD"]:
|
|
340
|
+
raise EigenException("Bad Status Parameter, must be 'OK' or 'BAD'")
|
|
652
341
|
return {"value": value, "timestamp": timestamp, "status": status}
|
|
653
342
|
|
|
654
|
-
def get_historian_multi(eigenserver: EigenServer = None) -> HistorianMulti:
|
|
343
|
+
def get_historian_multi(eigenserver: EigenServer = None, default_historian = None) -> HistorianMulti:
|
|
655
344
|
"""Instantiate a historian object for the given instance.
|
|
656
345
|
|
|
657
346
|
Args:
|
|
658
|
-
instance (Optional): The name of the historian to connect to. Defaults to the default historian of the EigenServer.
|
|
659
347
|
eigenserver (Optional): An EigenServer Object linked to the ingenuity url containing the historian. Can be omitted if environmental variable "EIGENSERVER" exists and is equal to the Ingenuity base url
|
|
348
|
+
default_historian (Optional): The name of the historian to be used if none is passed with a tag. Defaults to None, and will not hanbdle tags without historians.
|
|
660
349
|
|
|
661
350
|
Returns:
|
|
662
351
|
An Object that can be used to query historian data.
|
|
@@ -667,6 +356,6 @@ def get_historian_multi(eigenserver: EigenServer = None) -> HistorianMulti:
|
|
|
667
356
|
elif type(eigenserver) == str:
|
|
668
357
|
eigenserver = EigenServer(eigenserver)
|
|
669
358
|
|
|
670
|
-
return HistorianMulti(eigenserver.getEigenServerUrl() + "historian
|
|
359
|
+
return HistorianMulti(eigenserver.getEigenServerUrl() + "historian" + "/", eigenserver.auth, default_historian)
|
|
671
360
|
|
|
672
361
|
|
eigeningenuity/util.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
|
|
2
2
|
import sys, os, json, time, requests, csv, logging
|
|
3
3
|
from datetime import datetime
|
|
4
|
+
from dateparser import parse
|
|
4
5
|
import pandas as pd
|
|
5
6
|
from collections import ChainMap
|
|
6
7
|
from urllib.parse import urlsplit, quote as urlquote
|
|
@@ -135,7 +136,7 @@ def time_to_epoch_millis(t):
|
|
|
135
136
|
if "ago" in t or "now" in t:
|
|
136
137
|
return t
|
|
137
138
|
else:
|
|
138
|
-
epochmillis =
|
|
139
|
+
epochmillis = parse(t)
|
|
139
140
|
else:
|
|
140
141
|
raise EigenException("Unknown time format " + str(type(t)))
|
|
141
142
|
return int(round(epochmillis))
|
|
@@ -152,25 +153,28 @@ def get_timestamp_string(t):
|
|
|
152
153
|
def get_timestamp(t):
|
|
153
154
|
if type(t) == str:
|
|
154
155
|
try:
|
|
155
|
-
|
|
156
|
-
epochmillis = int(time.mktime(time.strptime(t, pattern)))
|
|
156
|
+
epochmillis = parse(t)
|
|
157
157
|
except ValueError:
|
|
158
158
|
try:
|
|
159
|
-
pattern = '%Y-%m-%
|
|
159
|
+
pattern = '%Y-%m-%d %H:%M:%S.%f'
|
|
160
160
|
epochmillis = int(time.mktime(time.strptime(t, pattern)))
|
|
161
161
|
except ValueError:
|
|
162
162
|
try:
|
|
163
|
-
pattern = '%Y-%m-%
|
|
163
|
+
pattern = '%Y-%m-%dT%H:%M:%S.%f%z'
|
|
164
164
|
epochmillis = int(time.mktime(time.strptime(t, pattern)))
|
|
165
165
|
except ValueError:
|
|
166
166
|
try:
|
|
167
|
-
pattern = '%Y-%m-%d'
|
|
167
|
+
pattern = '%Y-%m-%d %H:%M:%S'
|
|
168
168
|
epochmillis = int(time.mktime(time.strptime(t, pattern)))
|
|
169
169
|
except ValueError:
|
|
170
170
|
try:
|
|
171
|
-
|
|
171
|
+
pattern = '%Y-%m-%d'
|
|
172
|
+
epochmillis = int(time.mktime(time.strptime(t, pattern)))
|
|
172
173
|
except ValueError:
|
|
173
|
-
|
|
174
|
+
try:
|
|
175
|
+
epochmillis = int(t)
|
|
176
|
+
except ValueError:
|
|
177
|
+
raise EigenException("Unknown time format " + str(type(t)))
|
|
174
178
|
|
|
175
179
|
else:
|
|
176
180
|
return(time_to_epoch_millis(t))
|
|
@@ -424,31 +428,98 @@ def csvWriter(data,historian,filepath,multi_csv,functionName,order=None,headers=
|
|
|
424
428
|
dict_writer.writerows(sortedList)
|
|
425
429
|
return True
|
|
426
430
|
|
|
431
|
+
def process_datapoint(data_dict,key,datapoint):
|
|
432
|
+
tag_name = key
|
|
433
|
+
timestamp = datapoint['timestamp']
|
|
434
|
+
value_data = datapoint['value']
|
|
435
|
+
|
|
436
|
+
# Check if timestamp is already a key in the dictionary
|
|
437
|
+
if timestamp not in data_dict:
|
|
438
|
+
data_dict[timestamp] = {}
|
|
439
|
+
|
|
440
|
+
# Add data to the dictionary
|
|
441
|
+
data_dict[timestamp][tag_name] = value_data
|
|
442
|
+
|
|
443
|
+
return data_dict
|
|
444
|
+
|
|
427
445
|
def multi_response_to_df(api_response):
|
|
428
446
|
data_dict = {}
|
|
429
447
|
|
|
430
448
|
# Iterate through the response
|
|
431
449
|
for key, value in api_response.items():
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
450
|
+
if "dataPoints" in value.keys():
|
|
451
|
+
for datapoint in value["dataPoints"]:
|
|
452
|
+
data_dict = process_datapoint(data_dict,key,datapoint)
|
|
435
453
|
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
data_dict
|
|
439
|
-
|
|
440
|
-
# Add data to the dictionary
|
|
441
|
-
data_dict[timestamp][tag_name] = value_data
|
|
454
|
+
elif "dataPoint" in value.keys():
|
|
455
|
+
datapoint = value["dataPoint"]
|
|
456
|
+
data_dict = process_datapoint(data_dict,key,datapoint)
|
|
442
457
|
|
|
443
458
|
# Create DataFrame
|
|
444
|
-
df = pd.DataFrame(data_dict).T # Transpose the DataFrame
|
|
459
|
+
df = pd.DataFrame(data_dict,format="ISO8601").T # Transpose the DataFrame
|
|
445
460
|
|
|
446
461
|
# Convert timestamp index to datetime format
|
|
447
462
|
df.index = pd.to_datetime(df.index)
|
|
448
463
|
|
|
449
464
|
return df
|
|
450
465
|
|
|
466
|
+
def merge_tags_from_response(response):
|
|
467
|
+
merged_response = {}
|
|
468
|
+
|
|
469
|
+
for key, value in response.items():
|
|
470
|
+
# Extract the header by removing the suffix (e.g., '-0' or '-1')
|
|
471
|
+
header = key.rsplit('-', 1)[0]
|
|
472
|
+
|
|
473
|
+
# If the header is not already in the merged_response, initialize it
|
|
474
|
+
if header not in merged_response:
|
|
475
|
+
merged_response[header] = {'dataPoints': []}
|
|
451
476
|
|
|
477
|
+
# Append the dataPoint to the list of dataPoints under the header
|
|
478
|
+
merged_response[header]['dataPoints'].append(value['dataPoint'])
|
|
479
|
+
|
|
480
|
+
return merged_response
|
|
481
|
+
|
|
482
|
+
def update_keys(my_dict, historian):
|
|
483
|
+
# Use dictionary comprehension to update keys
|
|
484
|
+
return {
|
|
485
|
+
(historian + key if "/" not in key else key): value
|
|
486
|
+
for key, value in my_dict.items()
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
def _do_historian_multi_request(url,body,auth,write_request=False):
|
|
490
|
+
|
|
491
|
+
headers = {}
|
|
492
|
+
|
|
493
|
+
if settings._azure_tenant_id_ and settings._azure_client_id_ and settings._azure_auth_enabled_ and auth:
|
|
494
|
+
headers = _authenticate_azure_user('/'.join(url.split("/")[0:3]))
|
|
495
|
+
|
|
496
|
+
if settings._api_token_value_:
|
|
497
|
+
headers['X-Api-Key'] = settings._api_token_value_
|
|
498
|
+
|
|
499
|
+
resp = requests.post(url, json=body, verify=False, headers=headers).json()
|
|
500
|
+
|
|
501
|
+
if write_request:
|
|
502
|
+
return resp['message']
|
|
503
|
+
|
|
504
|
+
return resp
|
|
505
|
+
|
|
506
|
+
def format_output(output,response,tags,timestamps=False):
|
|
507
|
+
if not timestamps:
|
|
508
|
+
items = response['results']
|
|
509
|
+
|
|
510
|
+
if output == "raw":
|
|
511
|
+
return response
|
|
512
|
+
elif output == "json":
|
|
513
|
+
if len(tags) == 1 and (not timestamps or len(timestamps) == 1):
|
|
514
|
+
return items[tags[0]]
|
|
515
|
+
else:
|
|
516
|
+
return items
|
|
517
|
+
elif output == "string":
|
|
518
|
+
return json.dumps(items,indent=4)
|
|
519
|
+
elif output == "df":
|
|
520
|
+
return multi_response_to_df(items)
|
|
521
|
+
|
|
522
|
+
raise EigenException("Unrecognised Output Type. Must be one of ['raw','json','string','df']")
|
|
452
523
|
|
|
453
524
|
|
|
454
525
|
class EigenException (Exception): pass
|
|
@@ -63,7 +63,7 @@ def _convert_sys_argv_(func):
|
|
|
63
63
|
@_convert_sys_argv_
|
|
64
64
|
def build(path:str='.', config:str='config.ini', file:str='', query:list=[], preprocess:list=[], postprocess:list=[], delete_all:list=[], separator:str=';',
|
|
65
65
|
start_from:int=1, end_at:int=1, no_versions:bool=False, no_system_properties:bool=False, ignore_nodes:bool=False, skip_duplicates:bool=False,
|
|
66
|
-
no_duplicates:bool=False, allow_blanks:
|
|
66
|
+
no_duplicates:bool=False, allow_blanks:list=[], batch:int=0, auth:bool=False, order:str='qnrc', primary_property:str='', required_labels:list=[],
|
|
67
67
|
required_properties:list=[], database:str='0', verify:bool=False, summarise:bool=False, show_queries:bool=False, show_returns:bool=False,
|
|
68
68
|
write_queries:str='', write_returns:str='', display_rate='auto', create_node_csv_file:bool=False, node_labels:list=[], node_properties:list=[],
|
|
69
69
|
csv_file_suffix:str='', create_relationship_csv_file:bool=False, csv_to_labels:list=[], csv_to_properties:str=''):
|
|
@@ -88,7 +88,7 @@ def build(path:str='.', config:str='config.ini', file:str='', query:list=[], pre
|
|
|
88
88
|
no_system_properties: Suppress creation of system properties on nodes and relationships. Implies -nov
|
|
89
89
|
ignore_nodes: Treat node columns in relationship files as relationship properties
|
|
90
90
|
skip_duplicates: Don't create a version node if there are no changes. Same as -nod
|
|
91
|
-
allow_blanks:
|
|
91
|
+
allow_blanks: List of properties to create even if blank
|
|
92
92
|
batch: Number of queries to batch together when processing a node .csv file, significantly improves performance
|
|
93
93
|
auth: Enable Azure Authentication
|
|
94
94
|
order: Order in which to process the input files. Default is qnrc
|
{python_eigen_ingenuity-0.4.37b5.dist-info → python_eigen_ingenuity-0.4.38b1.dist-info}/METADATA
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: python-eigen-ingenuity
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.38b1
|
|
4
4
|
Summary: A python library used to query data from the Eigen Ingenuity system
|
|
5
5
|
Home-page: https://www.eigen.co/
|
|
6
6
|
Author: Murray Callander
|
|
@@ -18,6 +18,7 @@ Requires-Dist: keyring
|
|
|
18
18
|
Requires-Dist: pyarrow
|
|
19
19
|
Requires-Dist: neo4j >=5.17.0
|
|
20
20
|
Requires-Dist: requests >=2.31.0
|
|
21
|
+
Requires-Dist: dateparser
|
|
21
22
|
|
|
22
23
|
CONTENTS <!-- omit in toc -->
|
|
23
24
|
============
|
{python_eigen_ingenuity-0.4.37b5.dist-info → python_eigen_ingenuity-0.4.38b1.dist-info}/RECORD
RENAMED
|
@@ -4,15 +4,15 @@ eigeningenuity/auth.py,sha256=SPD5HXycsG5SBb2yf1pR5vee6gwG_UkWLkzmP02sWlY,6565
|
|
|
4
4
|
eigeningenuity/elastic.py,sha256=WG4nlsJXNs_-m76jtj46UfgvLgWLvn6d6QW2dk7LBI4,6648
|
|
5
5
|
eigeningenuity/events.py,sha256=wUc1TkT7047gduNuNfzkSO5tK13ErJdeI2K5cPXhNCY,3336
|
|
6
6
|
eigeningenuity/historian.py,sha256=YGAwaSMSdDAB_czQUCE0POxzYkU5ywsIrhl_abGl7rk,36341
|
|
7
|
-
eigeningenuity/historianmulti.py,sha256=
|
|
7
|
+
eigeningenuity/historianmulti.py,sha256=haARyAeRDB0dGNpg6Xiu7kWXKSvkgbN3NCYemF0TT20,14959
|
|
8
8
|
eigeningenuity/settings.py,sha256=ImYplpNINf1dYaUdarZaxvwf3zHSjE1CG7bOEUqnLT0,2794
|
|
9
9
|
eigeningenuity/smartdash.py,sha256=spzoRXO4tu7cDAd4cwbyxo9RBnYvjbJoXQq8zbXkMEw,3009
|
|
10
10
|
eigeningenuity/sql.py,sha256=y-IMu1fdZjMGFcg7ue7Ubhr0-BDTiUW01x8I7tSR700,5059
|
|
11
|
-
eigeningenuity/util.py,sha256=
|
|
11
|
+
eigeningenuity/util.py,sha256=b9b8qeNG-lhsrQ-Ke3ier45ohS3cYtAmjybCTxNmelE,17285
|
|
12
12
|
eigeningenuity/core/__init__.py,sha256=u3wAldyaivF-E2HzMftBNFPWUGNf0ZxGmdMUY6Em6nA,8439
|
|
13
13
|
modelbuilder/__init__.py,sha256=HSsHItu5BbGQiHYTG00QPMNDbC3RkRUaaN50YpksIUA,171
|
|
14
14
|
modelbuilder/src/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
15
|
-
modelbuilder/src/assetmodelbuilder.py,sha256=
|
|
15
|
+
modelbuilder/src/assetmodelbuilder.py,sha256=On0ndiJQQQ52vv-mo8pO2nsG5yMAk933kuBf4S8WQYg,8080
|
|
16
16
|
modelbuilder/src/assetmodelcsvwriter.py,sha256=GKNi_fw7AlY-UG2XhwFIS34Ff3XiVRss-o5MUzyJSV0,1071
|
|
17
17
|
modelbuilder/src/assetmodelutilities.py,sha256=KwyP8-2EfpRHKmGasPJLV74EGYBjSHgxHBAy8xuvh6k,1743
|
|
18
18
|
modelbuilder/src/configmanager.py,sha256=o_kDcup2DwCupOMlovcs_QqXt4PzH50QVamDrsWH5Dw,23158
|
|
@@ -38,8 +38,8 @@ modelbuilder/src/queries/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZ
|
|
|
38
38
|
modelbuilder/src/queries/cypherbuilder.py,sha256=XHChyxnTyJegfVhN949UU0T3t3Lf1CKgN0yCN8Cx8cM,10384
|
|
39
39
|
modelbuilder/src/queries/query.py,sha256=gN69uwsf-0F6_dGx9cxLGuM17960_FV58pyimJ9usxY,2472
|
|
40
40
|
modelbuilder/src/queries/typedefs.py,sha256=8uAnLfE_EyAfrdMZuotfu_YHqORXhWfgPG3Yltvyr5A,6129
|
|
41
|
-
python_eigen_ingenuity-0.4.
|
|
42
|
-
python_eigen_ingenuity-0.4.
|
|
43
|
-
python_eigen_ingenuity-0.4.
|
|
44
|
-
python_eigen_ingenuity-0.4.
|
|
45
|
-
python_eigen_ingenuity-0.4.
|
|
41
|
+
python_eigen_ingenuity-0.4.38b1.dist-info/METADATA,sha256=neOXDq8qRcuEZF5DDLARsjBEyz2w7Y9BVOZYXRmEBLE,32147
|
|
42
|
+
python_eigen_ingenuity-0.4.38b1.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
|
|
43
|
+
python_eigen_ingenuity-0.4.38b1.dist-info/entry_points.txt,sha256=G3LjFQX5xKaN4mqtqCL8uaC-gRbP5T5x9r0gBTJTXXA,70
|
|
44
|
+
python_eigen_ingenuity-0.4.38b1.dist-info/top_level.txt,sha256=lFiZ43CY_1bmdtRidIXbA6rrY2d92Rs-9tH8pcgI-XU,28
|
|
45
|
+
python_eigen_ingenuity-0.4.38b1.dist-info/RECORD,,
|
{python_eigen_ingenuity-0.4.37b5.dist-info → python_eigen_ingenuity-0.4.38b1.dist-info}/WHEEL
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|