python-eigen-ingenuity-nocli 0.5.6__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/__init__.py +29 -0
- eigeningenuity/assetmodel.py +433 -0
- eigeningenuity/auth.py +178 -0
- eigeningenuity/core/__init__.py +236 -0
- eigeningenuity/elastic.py +171 -0
- eigeningenuity/events.py +88 -0
- eigeningenuity/historian.py +786 -0
- eigeningenuity/historianmulti.py +481 -0
- eigeningenuity/settings.py +87 -0
- eigeningenuity/smartdash.py +103 -0
- eigeningenuity/sql.py +132 -0
- eigeningenuity/util.py +548 -0
- modelbuilder/__init__.py +7 -0
- modelbuilder/src/__init__.py +0 -0
- modelbuilder/src/assetmodelbuilder.py +164 -0
- modelbuilder/src/assetmodelcsvwriter.py +31 -0
- modelbuilder/src/assetmodelutilities.py +51 -0
- modelbuilder/src/configmanager.py +500 -0
- modelbuilder/src/connectors/__init__.py +0 -0
- modelbuilder/src/connectors/boltconnector.py +108 -0
- modelbuilder/src/connectors/dbconnectors.py +40 -0
- modelbuilder/src/connectors/genericconnector.py +30 -0
- modelbuilder/src/connectors/httpsconnector.py +132 -0
- modelbuilder/src/csvcontentsmanager.py +135 -0
- modelbuilder/src/csvwriter.py +305 -0
- modelbuilder/src/fileanalyser.py +91 -0
- modelbuilder/src/filemanager.py +400 -0
- modelbuilder/src/messages.py +61 -0
- modelbuilder/src/processors/__init__.py +0 -0
- modelbuilder/src/processors/cypherfileprocessor.py +73 -0
- modelbuilder/src/processors/labelmanager.py +133 -0
- modelbuilder/src/processors/nodefileprocessor.py +282 -0
- modelbuilder/src/processors/propertymanager.py +129 -0
- modelbuilder/src/processors/relationshipfileprocessor.py +285 -0
- modelbuilder/src/processors/relationshipmanager.py +31 -0
- modelbuilder/src/queries/__init__.py +0 -0
- modelbuilder/src/queries/cypherbuilder.py +323 -0
- modelbuilder/src/queries/query.py +82 -0
- modelbuilder/src/queries/typedefs.py +180 -0
- modelbuilder/src/versionmanager.py +356 -0
- python_eigen_ingenuity_nocli-0.5.6.dist-info/METADATA +30 -0
- python_eigen_ingenuity_nocli-0.5.6.dist-info/RECORD +44 -0
- python_eigen_ingenuity_nocli-0.5.6.dist-info/WHEEL +5 -0
- python_eigen_ingenuity_nocli-0.5.6.dist-info/top_level.txt +2 -0
eigeningenuity/sql.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Eigen Ingenuity - SQL
|
|
2
|
+
|
|
3
|
+
This package deals with the Eigen Ingenuity SQL database.
|
|
4
|
+
|
|
5
|
+
To retrieve data execute a custom query with
|
|
6
|
+
|
|
7
|
+
from eigeningenuity.assetmodel import matchNode
|
|
8
|
+
from time import gmtime, asctime
|
|
9
|
+
|
|
10
|
+
h = get_historian("Demo-influxdb","demo.eigen.co")
|
|
11
|
+
|
|
12
|
+
cmd = "EXECUTE"
|
|
13
|
+
db = "aveva-db",
|
|
14
|
+
query = '''
|
|
15
|
+
SELECT TAG_TISLOCATIONCODE, TAG_TISLOCATIONNAME, TAG_NUMBER, TAG_DESC, TAG_STATUS, TAG_STATUSDESC, TAG_BARRIERCODE, TAG_BARRIERNAME, TAG_BARRIERISACTIVE, TAG_BARRIERPERFORMANCESTD, TAG_BARRIERVERIFICATIONACT
|
|
16
|
+
FROM VT_TAGBARRIER
|
|
17
|
+
WHERE (ROWNUM <= 10)
|
|
18
|
+
'''
|
|
19
|
+
|
|
20
|
+
response = h.executeRawQuery(cmd,db,query)
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from eigeningenuity import EigenServer
|
|
24
|
+
from urllib.parse import quote as urlquote
|
|
25
|
+
from eigeningenuity.util import _do_eigen_json_request
|
|
26
|
+
from eigeningenuity.core import get_default_server
|
|
27
|
+
import requests, json
|
|
28
|
+
import pandas as pd
|
|
29
|
+
import datetime as dt
|
|
30
|
+
|
|
31
|
+
from urllib3.exceptions import InsecureRequestWarning
|
|
32
|
+
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
|
|
33
|
+
|
|
34
|
+
class sqlConnection (object):
|
|
35
|
+
"""An elasticsearch instance which talks the Eigen elastic endpoint.
|
|
36
|
+
"""
|
|
37
|
+
def __init__(self, baseurl, auth):
|
|
38
|
+
"""This is a constructor. It takes in a URL like http://demo.eigen.co/eigen-webtools-servlet/sqlquery"""
|
|
39
|
+
self.baseurl = baseurl
|
|
40
|
+
self.auth = auth
|
|
41
|
+
|
|
42
|
+
def _testConnection(self):
|
|
43
|
+
"""Preflight Request to verify connection"""
|
|
44
|
+
try:
|
|
45
|
+
status = requests.get(self.baseurl, verify=False).status_code
|
|
46
|
+
except ConnectionError:
|
|
47
|
+
raise ConnectionError("Failed to connect to ingenuity instance at " + self.baseurl + ". Please check the url is correct and the instance is up.")
|
|
48
|
+
|
|
49
|
+
def _doJsonRequest(self,cmd,params):
|
|
50
|
+
url = self.baseurl + "?cmd=" + urlquote(cmd)
|
|
51
|
+
return _do_eigen_json_request(url, self.auth, **params)
|
|
52
|
+
|
|
53
|
+
def executeRawQuery(self,cmd:str,db:str,query:str,output:str="json",filepath:str=None):
|
|
54
|
+
"""
|
|
55
|
+
Run a user composed raw SQL query against an ingenuity SQL database
|
|
56
|
+
|
|
57
|
+
Args:
|
|
58
|
+
cmd: Command to run against the database e.g. EXECUTE
|
|
59
|
+
db: Name of the SQL database to query
|
|
60
|
+
query: The Body of the SQL query
|
|
61
|
+
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; "file" - Writes the response to a .json file in the local directory. Defaults to "json"
|
|
62
|
+
filepath: (Optional) Name and path to the .json file that will be created/overwritten. If omitted, will create a file in the current directory with an auto-generated name. Has no effect unless output is "file".
|
|
63
|
+
|
|
64
|
+
Returns:
|
|
65
|
+
The SQL response to the given query, the format is dependent on the output parameter
|
|
66
|
+
"""
|
|
67
|
+
args = {}
|
|
68
|
+
args['db'] = db
|
|
69
|
+
args['query'] = query
|
|
70
|
+
response = self._doJsonRequest(cmd,args)["results"]
|
|
71
|
+
|
|
72
|
+
if output == "raw" or output == "json":
|
|
73
|
+
return response
|
|
74
|
+
elif output == "string":
|
|
75
|
+
return json.dumps(response)
|
|
76
|
+
elif output == "df":
|
|
77
|
+
return pd.DataFrame(response)
|
|
78
|
+
elif output == "file":
|
|
79
|
+
if filepath is None:
|
|
80
|
+
filepath = "eigenSQLResponse-" + db + "-" + str(dt.datetime.now().strftime("%Y-%m-%dT%H:%M:%S"))
|
|
81
|
+
with open(filepath + ".json", "w") as f:
|
|
82
|
+
f.write(json.dumps(response, indent=4))
|
|
83
|
+
return None
|
|
84
|
+
|
|
85
|
+
def listDatabases(self):
|
|
86
|
+
"""
|
|
87
|
+
Get the available SQL Databases on the server
|
|
88
|
+
|
|
89
|
+
Args:
|
|
90
|
+
None
|
|
91
|
+
Returns:
|
|
92
|
+
A list of SQL databases that allow this library to access them
|
|
93
|
+
"""
|
|
94
|
+
args = {}
|
|
95
|
+
cmd = "LISTDBS"
|
|
96
|
+
response = self._doJsonRequest(cmd,args)["results"]
|
|
97
|
+
|
|
98
|
+
return response
|
|
99
|
+
|
|
100
|
+
def listTables(self,db):
|
|
101
|
+
"""
|
|
102
|
+
A list of Tables from within a provided database
|
|
103
|
+
|
|
104
|
+
Args:
|
|
105
|
+
db: Name of the SQL database to query
|
|
106
|
+
|
|
107
|
+
Returns:
|
|
108
|
+
The list of tables available for the user to query within the given database
|
|
109
|
+
"""
|
|
110
|
+
args = {}
|
|
111
|
+
cmd = "LIST"
|
|
112
|
+
args["db"] = db
|
|
113
|
+
response = self._doJsonRequest(cmd,args)["results"]
|
|
114
|
+
|
|
115
|
+
return response
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def get_sql(eigenserver:EigenServer = None):
|
|
119
|
+
"""Instantiate an SQL connection for the given EigenServer.
|
|
120
|
+
|
|
121
|
+
Args:
|
|
122
|
+
eigenserver: (Optional) An EigenServer Object linked to the ingenuity url containing the elasticsearch. Can be omitted if environmental variable "EIGENSERVER" exists and contains the Ingenuity base url
|
|
123
|
+
|
|
124
|
+
Returns:
|
|
125
|
+
An Object that can be used to query SQL databases connected to the ingenuity.
|
|
126
|
+
"""
|
|
127
|
+
if eigenserver is None:
|
|
128
|
+
eigenserver = get_default_server()
|
|
129
|
+
elif type(eigenserver) == str:
|
|
130
|
+
eigenserver = EigenServer(eigenserver)
|
|
131
|
+
|
|
132
|
+
return sqlConnection(eigenserver.getEigenServerUrl() + "eigen-webtools-servlet/sqlquery", eigenserver.auth)
|
eigeningenuity/util.py
ADDED
|
@@ -0,0 +1,548 @@
|
|
|
1
|
+
|
|
2
|
+
import sys, os, json, time, requests, csv, logging
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from dateparser import parse
|
|
5
|
+
import pandas as pd
|
|
6
|
+
from collections import ChainMap
|
|
7
|
+
from urllib.parse import urlsplit, quote as urlquote
|
|
8
|
+
|
|
9
|
+
from requests.exceptions import ConnectionError
|
|
10
|
+
|
|
11
|
+
from eigeningenuity.auth import _authenticate_azure_user
|
|
12
|
+
import eigeningenuity.settings as settings
|
|
13
|
+
|
|
14
|
+
def _do_eigen_json_request(requesturl,auth,**params):
|
|
15
|
+
|
|
16
|
+
headers = {}
|
|
17
|
+
|
|
18
|
+
if settings._azure_tenant_id_ and settings._azure_client_id_ and settings._azure_auth_enabled_ and auth:
|
|
19
|
+
headers = _authenticate_azure_user('/'.join(requesturl.split("/")[0:3]))
|
|
20
|
+
|
|
21
|
+
if settings._api_token_value_:
|
|
22
|
+
headers['X-Api-Key'] = settings._api_token_value_
|
|
23
|
+
|
|
24
|
+
if params:
|
|
25
|
+
if "?" in requesturl:
|
|
26
|
+
sep = "&"
|
|
27
|
+
else:
|
|
28
|
+
sep = "?"
|
|
29
|
+
|
|
30
|
+
for k,v in params.items():
|
|
31
|
+
if v is None:
|
|
32
|
+
pass
|
|
33
|
+
else:
|
|
34
|
+
for e in force_list(v):
|
|
35
|
+
if not isinstance(e, str):
|
|
36
|
+
if isinstance(e, str):
|
|
37
|
+
e = e.encode("utf8")
|
|
38
|
+
else:
|
|
39
|
+
e = str(e)
|
|
40
|
+
requesturl += sep + urlquote(k) + "=" + urlquote(e.encode("UTF8"))
|
|
41
|
+
|
|
42
|
+
sep = "&"
|
|
43
|
+
|
|
44
|
+
try:
|
|
45
|
+
data = requests.get(requesturl, headers=headers, verify=False)
|
|
46
|
+
except ConnectionError as e:
|
|
47
|
+
# sys.tracebacklimit = 0
|
|
48
|
+
raise EigenException("No Response from ingenuity instance at https://" + requesturl.split("/")[2] + ". Please check this is correct url and that the instance is currently running") from None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
if data.text.startswith("ERROR:"):
|
|
52
|
+
if "UNKNOWN TAG" in data.text:
|
|
53
|
+
raise RemoteServerException(data.text)
|
|
54
|
+
raise RemoteServerException(data.text.split("\n")[1], requesturl)
|
|
55
|
+
elif data.text.startswith("EXCEPT:") and data.status_code != 200:
|
|
56
|
+
raise RemoteServerException( data.text.split("\n")[0], "API could not parse request, check query syntax is correct",)
|
|
57
|
+
else:
|
|
58
|
+
try:
|
|
59
|
+
ret = data.json()
|
|
60
|
+
except ValueError:
|
|
61
|
+
ret = data.text
|
|
62
|
+
try:
|
|
63
|
+
if "Sign in to your account" in ret:
|
|
64
|
+
if not settings._azure_auth_enabled_ or not (settings._azure_tenant_id_ and settings._azure_client_id_):
|
|
65
|
+
msg = "This resource requires authentication with an Azure account. Use set_azure_tenant_id and set_azure_client_id to set the server parameters."
|
|
66
|
+
else:
|
|
67
|
+
msg = "Authentication failed, check the resource you are querying matches the azure parameters set"
|
|
68
|
+
raise EigenException(f"{msg}")
|
|
69
|
+
except:
|
|
70
|
+
pass
|
|
71
|
+
return ret
|
|
72
|
+
|
|
73
|
+
def _do_eigen_post_request(requesturl,payload,auth):
|
|
74
|
+
headers = {}
|
|
75
|
+
if settings._azure_tenant_id_ and settings._azure_client_id_ and settings._azure_auth_enabled_ and auth:
|
|
76
|
+
headers = _authenticate_azure_user('/'.join(requesturl.split("/")[0:3]))
|
|
77
|
+
|
|
78
|
+
if settings._api_token_value_:
|
|
79
|
+
headers['X-Api-Key'] = settings._api_token_value_
|
|
80
|
+
|
|
81
|
+
if not str(requests.post(requesturl,json=payload, headers=headers, verify=False)).startswith("2"):
|
|
82
|
+
logging.warning("Failed to push")
|
|
83
|
+
return False
|
|
84
|
+
return True
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _do_chunked_eigen_post_request(requesturl,data,label,auth):
|
|
88
|
+
headers = {}
|
|
89
|
+
if settings._azure_tenant_id_ and settings._azure_client_id_ and settings._azure_auth_enabled_ and auth:
|
|
90
|
+
headers = _authenticate_azure_user('/'.join(requesturl.split("/")[0:3]))
|
|
91
|
+
|
|
92
|
+
if settings._api_token_value_:
|
|
93
|
+
headers['X-Api-Key'] = settings._api_token_value_
|
|
94
|
+
|
|
95
|
+
chunks = list(divide_chunks(data, 500))
|
|
96
|
+
failures = []
|
|
97
|
+
for chunk in chunks:
|
|
98
|
+
payload = {label: chunk}
|
|
99
|
+
resp = requests.post(requesturl, json=payload, verify=False, headers=headers)
|
|
100
|
+
if not str(resp.status_code).startswith("2"):
|
|
101
|
+
failures.append(payload)
|
|
102
|
+
if failures:
|
|
103
|
+
logging.warning("Some events failed to push")
|
|
104
|
+
return failures
|
|
105
|
+
return False
|
|
106
|
+
|
|
107
|
+
def is_list(x):
|
|
108
|
+
return type(x) in (list, tuple, set)
|
|
109
|
+
|
|
110
|
+
def force_list(x):
|
|
111
|
+
if is_list(x):
|
|
112
|
+
return x
|
|
113
|
+
else:
|
|
114
|
+
return [x]
|
|
115
|
+
|
|
116
|
+
def number_to_string(n):
|
|
117
|
+
if type(n) == float:
|
|
118
|
+
return format(n, '^12.5f')
|
|
119
|
+
else:
|
|
120
|
+
return n
|
|
121
|
+
|
|
122
|
+
def time_to_epoch_millis(t):
|
|
123
|
+
if type(t) == datetime:
|
|
124
|
+
epochmillis = t.timestamp()
|
|
125
|
+
elif (type(t) == int or type(t) == float):
|
|
126
|
+
if t > 100000000000:
|
|
127
|
+
epochmillis = int(t)
|
|
128
|
+
else:
|
|
129
|
+
epochmillis = int(t*1000)
|
|
130
|
+
elif type(t) == str:
|
|
131
|
+
if "ago" in t or "now" in t:
|
|
132
|
+
return t
|
|
133
|
+
else:
|
|
134
|
+
epochmillis = parse(t).timestamp()
|
|
135
|
+
else:
|
|
136
|
+
raise EigenException("Unknown time format " + str(type(t)))
|
|
137
|
+
return int(round(epochmillis))
|
|
138
|
+
|
|
139
|
+
def get_time_tuple(floatingpointepochsecs):
|
|
140
|
+
time_tuple = time.gmtime(floatingpointepochsecs)
|
|
141
|
+
return time_tuple
|
|
142
|
+
|
|
143
|
+
def get_timestamp_string(t):
|
|
144
|
+
pattern = '%Y-%m-%d %H:%M:%S UTC'
|
|
145
|
+
s = datetime.fromtimestamp(t).strftime(pattern)
|
|
146
|
+
return s
|
|
147
|
+
|
|
148
|
+
def get_timestamp(t):
|
|
149
|
+
if type(t) == str:
|
|
150
|
+
try:
|
|
151
|
+
epochmillis = parse(t).timestamp()
|
|
152
|
+
except ValueError:
|
|
153
|
+
try:
|
|
154
|
+
pattern = '%Y-%m-%d %H:%M:%S.%f'
|
|
155
|
+
epochmillis = int(time.mktime(time.strptime(t, pattern)))
|
|
156
|
+
except ValueError:
|
|
157
|
+
try:
|
|
158
|
+
pattern = '%Y-%m-%dT%H:%M:%S.%f%z'
|
|
159
|
+
epochmillis = int(time.mktime(time.strptime(t, pattern)))
|
|
160
|
+
except ValueError:
|
|
161
|
+
try:
|
|
162
|
+
pattern = '%Y-%m-%d %H:%M:%S'
|
|
163
|
+
epochmillis = int(time.mktime(time.strptime(t, pattern)))
|
|
164
|
+
except ValueError:
|
|
165
|
+
try:
|
|
166
|
+
pattern = '%Y-%m-%d'
|
|
167
|
+
epochmillis = int(time.mktime(time.strptime(t, pattern)))
|
|
168
|
+
except ValueError:
|
|
169
|
+
try:
|
|
170
|
+
epochmillis = int(t)
|
|
171
|
+
except ValueError:
|
|
172
|
+
raise EigenException("Unknown time format " + str(type(t)))
|
|
173
|
+
|
|
174
|
+
else:
|
|
175
|
+
return(time_to_epoch_millis(t))
|
|
176
|
+
return int(round(epochmillis))
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def get_datetime(t):
|
|
181
|
+
timestamp = get_timestamp(t)
|
|
182
|
+
return datetime.fromtimestamp(timestamp)
|
|
183
|
+
|
|
184
|
+
def pythonTimeToServerTime(ts):
|
|
185
|
+
# where ts may be supplied as time tuple, datetime or floating point seconds, and server time is (obviously) millis.
|
|
186
|
+
if type(ts) == datetime:
|
|
187
|
+
epochmillis = time.mktime(ts.timetuple()) * 1000
|
|
188
|
+
elif type(ts) == tuple:
|
|
189
|
+
epochmillis = time.mktime(ts) * 1000
|
|
190
|
+
elif type(ts) == float:
|
|
191
|
+
epochmillis = int(ts * 1000)
|
|
192
|
+
else:
|
|
193
|
+
raise EigenException("Unknown python time format " + str(type(ts)))
|
|
194
|
+
return int(round(epochmillis))
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def serverTimeToPythonTime(ts):
|
|
198
|
+
# where ts is millis and the returned value is consistently whatever we're using internally in the python library (i.e. floating secs)
|
|
199
|
+
return ts / 1000.0
|
|
200
|
+
|
|
201
|
+
def pythonTimeToFloatingSecs(ts):
|
|
202
|
+
# where ts may be supplied as time tuple, datetime or floating point seconds
|
|
203
|
+
if type(ts) == datetime:
|
|
204
|
+
return time.mktime(ts.timetuple())
|
|
205
|
+
elif type(ts) == tuple:
|
|
206
|
+
return time.mktime(ts)
|
|
207
|
+
elif type(ts) == float or type(ts) == int:
|
|
208
|
+
return ts
|
|
209
|
+
else:
|
|
210
|
+
raise EigenException("Unknown python time format " + str(type(ts)))
|
|
211
|
+
|
|
212
|
+
def pythonTimeToTuple(ts):
|
|
213
|
+
# where ts may be supplied as time tuple, datetime or floating point seconds
|
|
214
|
+
if type(ts) == datetime:
|
|
215
|
+
return ts.timetuple()
|
|
216
|
+
elif type(ts) == tuple:
|
|
217
|
+
return ts
|
|
218
|
+
elif type(ts) == float:
|
|
219
|
+
return ts
|
|
220
|
+
else:
|
|
221
|
+
raise EigenException("Unknown python time format " + str(type(ts)))
|
|
222
|
+
|
|
223
|
+
def pythonTimeToDateTime(ts):
|
|
224
|
+
# where ts may be supplied as time tuple, datetime or floating point seconds
|
|
225
|
+
if type(ts) == datetime:
|
|
226
|
+
return ts
|
|
227
|
+
elif type(ts) == tuple:
|
|
228
|
+
epochmillis = time.mktime(ts) * 1000
|
|
229
|
+
return datetime.fromtimestamp(epochmillis)
|
|
230
|
+
elif type(ts) == float:
|
|
231
|
+
return time.gmtime(ts)
|
|
232
|
+
else:
|
|
233
|
+
raise EigenException("Unknown python time format " + str(type(ts)))
|
|
234
|
+
|
|
235
|
+
def map_java_exception(myExceptionName, params):
|
|
236
|
+
if myExceptionName == "urllib2.HTTPError":
|
|
237
|
+
return RemoteServerException(params)
|
|
238
|
+
# elif: ...
|
|
239
|
+
else:
|
|
240
|
+
return EigenException(myExceptionName)
|
|
241
|
+
|
|
242
|
+
def parse_duration(timeWindow):
|
|
243
|
+
unit = timeWindow[-1:]
|
|
244
|
+
value = timeWindow[:-1]
|
|
245
|
+
|
|
246
|
+
def seconds():
|
|
247
|
+
int(value)
|
|
248
|
+
|
|
249
|
+
def minutes():
|
|
250
|
+
return int(value) * 60
|
|
251
|
+
|
|
252
|
+
def hours():
|
|
253
|
+
return int(value) * 3600
|
|
254
|
+
|
|
255
|
+
def days():
|
|
256
|
+
return int(value) * 3600 * 24
|
|
257
|
+
|
|
258
|
+
def months():
|
|
259
|
+
return int(value) * 3600 * 24 * 30
|
|
260
|
+
|
|
261
|
+
def years(): int(value) * 3600 * 24 * 365
|
|
262
|
+
|
|
263
|
+
options = {"s" : seconds,
|
|
264
|
+
"m" : minutes,
|
|
265
|
+
"h" : hours,
|
|
266
|
+
"d" : days,
|
|
267
|
+
"M" : months,
|
|
268
|
+
"y" : years,
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
duration = options[unit]()*1000
|
|
272
|
+
|
|
273
|
+
return duration
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def divide_chunks(l, n):
|
|
277
|
+
for i in range(0, len(l), n):
|
|
278
|
+
yield l[i:i + n]
|
|
279
|
+
|
|
280
|
+
def cypherRespMap(resp):
|
|
281
|
+
return resp["m"]
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def jsonToDf(json,transpose:bool=False):
|
|
285
|
+
p = {}
|
|
286
|
+
keys = json.keys()
|
|
287
|
+
if "unknown" in keys: keys.remove("unknown")
|
|
288
|
+
for key in keys:
|
|
289
|
+
if type(json[key]) == list:
|
|
290
|
+
m = list(map(dataMap,json[key]))
|
|
291
|
+
n = dict(ChainMap(*m))
|
|
292
|
+
else:
|
|
293
|
+
n = dataMap(json[key])
|
|
294
|
+
p[key] = n
|
|
295
|
+
try:
|
|
296
|
+
df = pd.DataFrame(p)
|
|
297
|
+
if transpose:
|
|
298
|
+
df = df.T
|
|
299
|
+
return(df[::-1])
|
|
300
|
+
except ValueError:
|
|
301
|
+
return(pd.Series(p))
|
|
302
|
+
|
|
303
|
+
def dataMap(j):
|
|
304
|
+
try:
|
|
305
|
+
h = {datetime.fromtimestamp(j["timestamp"] / 1000): j["value"]}
|
|
306
|
+
except:
|
|
307
|
+
h = j
|
|
308
|
+
return h
|
|
309
|
+
|
|
310
|
+
def flattenList(list):
|
|
311
|
+
return [item for sublist in list for item in sublist]
|
|
312
|
+
|
|
313
|
+
def flattenDict(nestedDict):
|
|
314
|
+
points = []
|
|
315
|
+
keys = nestedDict.keys()
|
|
316
|
+
for key in keys:
|
|
317
|
+
values = nestedDict[key]
|
|
318
|
+
for value in force_list(values):
|
|
319
|
+
tag = {"tag": key}
|
|
320
|
+
tag.update(value)
|
|
321
|
+
points.append(tag)
|
|
322
|
+
return points
|
|
323
|
+
|
|
324
|
+
def aggMap(x):
|
|
325
|
+
for k in x[1]:
|
|
326
|
+
k["tag"] = x[0]
|
|
327
|
+
return x[1]
|
|
328
|
+
|
|
329
|
+
def aggToDf(x,cols):
|
|
330
|
+
y = flattenList(list(map(aggMap,x.items())))
|
|
331
|
+
if cols is None:
|
|
332
|
+
cols = ["tag", "start", "end", "min", "max", "avg", "var", "stddev", "numgood", "numbad"]
|
|
333
|
+
else:
|
|
334
|
+
cols = ["tag", "start", "end"] + cols
|
|
335
|
+
df = pd.DataFrame(y)
|
|
336
|
+
df = df[cols]
|
|
337
|
+
try:
|
|
338
|
+
df["start"] = pd.to_datetime(df["start"], unit="ms")
|
|
339
|
+
df["end"] = pd.to_datetime(df["end"], unit="ms")
|
|
340
|
+
except ValueError:
|
|
341
|
+
df["start"] = pd.to_datetime(df["start"], format="ISO8601")
|
|
342
|
+
df["end"] = pd.to_datetime(df["end"], format="ISO8601")
|
|
343
|
+
df.sort_values(by='start', inplace=True)
|
|
344
|
+
return(df)
|
|
345
|
+
|
|
346
|
+
def get_eigenserver(url):
|
|
347
|
+
split_url = urlsplit(url)
|
|
348
|
+
return split_url.scheme + "://" + split_url.netloc
|
|
349
|
+
|
|
350
|
+
def constructURL(y,x):
|
|
351
|
+
if "//" not in x["url"]:
|
|
352
|
+
x["url"] = y + x["url"]
|
|
353
|
+
k = {"fileName": x["fileName"], "description": x["description"], "url": x["url"]}
|
|
354
|
+
return k
|
|
355
|
+
|
|
356
|
+
def parseEvents(events):
|
|
357
|
+
if type(events) == dict or type(events) == list:
|
|
358
|
+
events = events
|
|
359
|
+
elif type(events) == str:
|
|
360
|
+
try:
|
|
361
|
+
with open(events,"r") as f:
|
|
362
|
+
events = json.loads(f.read())
|
|
363
|
+
except FileNotFoundError:
|
|
364
|
+
try:
|
|
365
|
+
events = json.loads(events)
|
|
366
|
+
except json.decoder.JSONDecodeError:
|
|
367
|
+
raise EigenException("Could not parse input, enter the path to a file, or a json/dict object")
|
|
368
|
+
try:
|
|
369
|
+
events = events["events"]
|
|
370
|
+
except:
|
|
371
|
+
pass
|
|
372
|
+
events = force_list(events)
|
|
373
|
+
return events
|
|
374
|
+
|
|
375
|
+
def parse_properties(x):
|
|
376
|
+
return x["graphapi"]["properties"]
|
|
377
|
+
|
|
378
|
+
def csvWriter(data,historian,filepath,multi_csv,functionName,order=None,headers=False):
|
|
379
|
+
if "Agg" in functionName:
|
|
380
|
+
timeField = 'start'
|
|
381
|
+
else:
|
|
382
|
+
timeField = 'timestamp'
|
|
383
|
+
if multi_csv:
|
|
384
|
+
for item in data:
|
|
385
|
+
sortedDicts=[]
|
|
386
|
+
for entry in force_list(data[item]):
|
|
387
|
+
if order is not None:
|
|
388
|
+
entry = (dict(sorted(entry.items(), key=lambda item: order.index(item[0]))))
|
|
389
|
+
sortedDicts.append(dict(entry.items()))
|
|
390
|
+
sortedList = sorted(sortedDicts, key=lambda d: (d[timeField]))
|
|
391
|
+
keys = sortedList[0].keys()
|
|
392
|
+
if filepath is None:
|
|
393
|
+
filepath = item + "-" + functionName + "-" + str(round(datetime.now().timestamp())) + ".csv"
|
|
394
|
+
elif filepath[-1] == "/":
|
|
395
|
+
filepath += item + "-" + functionName + "-" + str(round(datetime.now().timestamp())) + ".csv"
|
|
396
|
+
else:
|
|
397
|
+
filepath = item + "-" + functionName + "-" + str(round(datetime.now().timestamp())) + ".csv"
|
|
398
|
+
|
|
399
|
+
with open(filepath, 'w', newline='') as output_file:
|
|
400
|
+
dict_writer = csv.DictWriter(output_file, keys)
|
|
401
|
+
if headers:
|
|
402
|
+
dict_writer.writeheader()
|
|
403
|
+
dict_writer.writerows(sortedList)
|
|
404
|
+
return True
|
|
405
|
+
else:
|
|
406
|
+
sortedDicts = []
|
|
407
|
+
points = flattenDict(data)
|
|
408
|
+
for entry in points:
|
|
409
|
+
if order is not None:
|
|
410
|
+
entry = dict(sorted(entry.items(), key=lambda item: order.index(item[0])))
|
|
411
|
+
sortedDicts.append(entry)
|
|
412
|
+
sortedList = sorted(sortedDicts, key=lambda d: (d['tag'], d[timeField]))
|
|
413
|
+
keys = sortedList[0].keys()
|
|
414
|
+
if filepath is None:
|
|
415
|
+
filepath = historian + "-" + functionName + "-" + str(round(datetime.now().timestamp())) + ".csv"
|
|
416
|
+
elif filepath[-1] == "/":
|
|
417
|
+
filepath += historian + "-" + functionName + "-" + str(round(datetime.now().timestamp())) + ".csv"
|
|
418
|
+
|
|
419
|
+
with open(filepath, 'w', newline='') as output_file:
|
|
420
|
+
dict_writer = csv.DictWriter(output_file, keys)
|
|
421
|
+
if headers:
|
|
422
|
+
dict_writer.writeheader()
|
|
423
|
+
dict_writer.writerows(sortedList)
|
|
424
|
+
return True
|
|
425
|
+
|
|
426
|
+
def process_datapoint(data_dict,key,datapoint):
|
|
427
|
+
tag_name = key
|
|
428
|
+
timestamp = datapoint['timestamp']
|
|
429
|
+
value_data = datapoint['value']
|
|
430
|
+
|
|
431
|
+
# Check if timestamp is already a key in the dictionary
|
|
432
|
+
if timestamp not in data_dict:
|
|
433
|
+
data_dict[timestamp] = {}
|
|
434
|
+
|
|
435
|
+
# Add data to the dictionary
|
|
436
|
+
data_dict[timestamp][tag_name] = value_data
|
|
437
|
+
|
|
438
|
+
return data_dict
|
|
439
|
+
|
|
440
|
+
# Function to convert timestamp to a consistent format
|
|
441
|
+
def convert_df_timestamp_header(timestamp):
|
|
442
|
+
# Convert to datetime object and then format as string
|
|
443
|
+
dt = datetime.fromisoformat(timestamp)
|
|
444
|
+
return dt.strftime("%Y-%m-%d %H:%M:%S")
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def multi_response_to_df(api_response):
|
|
448
|
+
data_dict = {}
|
|
449
|
+
|
|
450
|
+
# Iterate through the response
|
|
451
|
+
for key, value in api_response.items():
|
|
452
|
+
if "dataPoints" in value.keys():
|
|
453
|
+
for datapoint in value["dataPoints"]:
|
|
454
|
+
data_dict = process_datapoint(data_dict,key,datapoint)
|
|
455
|
+
|
|
456
|
+
elif "dataPoint" in value.keys():
|
|
457
|
+
datapoint = value["dataPoint"]
|
|
458
|
+
data_dict = process_datapoint(data_dict,key,datapoint)
|
|
459
|
+
|
|
460
|
+
# Create DataFrame
|
|
461
|
+
df = pd.DataFrame(data_dict)
|
|
462
|
+
df.columns = [convert_df_timestamp_header(col) for col in df.columns]
|
|
463
|
+
df = df.T # Transpose the DataFrame
|
|
464
|
+
|
|
465
|
+
# Convert timestamp index to datetime format
|
|
466
|
+
df.index = pd.to_datetime(df.index)
|
|
467
|
+
|
|
468
|
+
return df
|
|
469
|
+
|
|
470
|
+
def merge_tags_from_response(response):
|
|
471
|
+
merged_response = {}
|
|
472
|
+
|
|
473
|
+
for key, value in response.items():
|
|
474
|
+
# Extract the header by removing the suffix (e.g., '-0' or '-1')
|
|
475
|
+
header = key.rsplit('-', 1)[0]
|
|
476
|
+
|
|
477
|
+
# If the header is not already in the merged_response, initialize it
|
|
478
|
+
if header not in merged_response:
|
|
479
|
+
merged_response[header] = {'dataPoints': []}
|
|
480
|
+
|
|
481
|
+
# Append the dataPoint to the list of dataPoints under the header
|
|
482
|
+
merged_response[header]['dataPoints'].append(value['dataPoint'])
|
|
483
|
+
|
|
484
|
+
return merged_response
|
|
485
|
+
|
|
486
|
+
def update_keys(my_dict, historian):
|
|
487
|
+
# Use dictionary comprehension to update keys
|
|
488
|
+
return {
|
|
489
|
+
(historian + key if "/" not in key else key): value
|
|
490
|
+
for key, value in my_dict.items()
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
def _do_historian_multi_request(url,body,auth,write_request=False,get_request=False):
|
|
494
|
+
|
|
495
|
+
headers = {}
|
|
496
|
+
|
|
497
|
+
if settings._azure_tenant_id_ and settings._azure_client_id_ and settings._azure_auth_enabled_ and auth:
|
|
498
|
+
headers = _authenticate_azure_user('/'.join(url.split("/")[0:3]))
|
|
499
|
+
|
|
500
|
+
if settings._api_token_value_:
|
|
501
|
+
headers['X-Api-Key'] = settings._api_token_value_
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
if get_request:
|
|
505
|
+
resp = requests.get(url, verify=False, headers=headers).json()
|
|
506
|
+
|
|
507
|
+
else:
|
|
508
|
+
resp = requests.post(url, json=body, verify=False, headers=headers).json()
|
|
509
|
+
|
|
510
|
+
if write_request:
|
|
511
|
+
return resp['message']
|
|
512
|
+
|
|
513
|
+
return resp
|
|
514
|
+
|
|
515
|
+
def _reformat_multi_response(original_dict):
|
|
516
|
+
reformatted_dict = {}
|
|
517
|
+
|
|
518
|
+
for key, value in original_dict.items():
|
|
519
|
+
# Extract the list of data points from either 'dataPoints' or 'dataPoint' key
|
|
520
|
+
data_points = value.get('dataPoints') or value.get('dataPoint')
|
|
521
|
+
# Assign the data points list directly to the top-level key
|
|
522
|
+
reformatted_dict[key] = data_points
|
|
523
|
+
|
|
524
|
+
return reformatted_dict
|
|
525
|
+
|
|
526
|
+
def format_output(output,response,tags,timestamps=False):
|
|
527
|
+
if not timestamps:
|
|
528
|
+
items = response['results']
|
|
529
|
+
else:
|
|
530
|
+
items = response
|
|
531
|
+
|
|
532
|
+
if output == "raw":
|
|
533
|
+
return response
|
|
534
|
+
elif output == "json":
|
|
535
|
+
if len(tags) == 1 and (not timestamps or len(timestamps) == 1):
|
|
536
|
+
return _reformat_multi_response(items[tags[0]])
|
|
537
|
+
else:
|
|
538
|
+
return _reformat_multi_response(items)
|
|
539
|
+
elif output == "string":
|
|
540
|
+
return json.dumps(items,indent=4)
|
|
541
|
+
elif output == "df":
|
|
542
|
+
return multi_response_to_df(items)
|
|
543
|
+
|
|
544
|
+
raise EigenException("Unrecognised Output Type. Must be one of ['raw','json','string','df']")
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
class EigenException (Exception): pass
|
|
548
|
+
class RemoteServerException (EigenException): pass
|
modelbuilder/__init__.py
ADDED
|
File without changes
|