python-eigen-ingenuity 0.5.22b1__py3-none-any.whl → 0.5.22b2__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.
@@ -18,6 +18,7 @@ eigeningenuity.core) or a full URL to a JSON Bridge Historian instance.
18
18
  """
19
19
 
20
20
  import requests
21
+ import re
21
22
  from typing import Union
22
23
  from datetime import datetime
23
24
 
@@ -309,6 +310,179 @@ class HistorianMulti(object):
309
310
  output, items, tags, timestamps, timestamp_format=self.timestamp_format
310
311
  )
311
312
 
313
+ # SECTION - Tag Aggregation Requests
314
+
315
+ def getAggregates(
316
+ self,
317
+ tags: Union[str, list],
318
+ start: Union[int, float, str, datetime],
319
+ end: Union[int, float, str, datetime],
320
+ intervals: int = 1,
321
+ aggregates: Union[str, list] = None,
322
+ output: str = "json",
323
+ ):
324
+ """Get aggregates/statistics for one or more tags over a time range
325
+
326
+ Args:
327
+ tags: A datatag, or list of datatags
328
+ start: Start of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
329
+ end: End of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
330
+ intervals (Optional): Number of equal time intervals to split the time range into. One aggregate will be returned per interval. Defaults to 1
331
+ aggregates (Optional): A string, or list of strings of the aggregates to return. Allowed values are: "FIRST", "AVG", "NUMGOOD", "MAX", "LAST", "VAR", "MEDIAN", "NUMBAD", "MIN", "COUNT", "STDDEV". Defaults to all aggregates.
332
+ output (Optional): The format in which to return the data. Accepts one of:
333
+ - "raw" - The raw json returned by the API
334
+ - "json" - A processed version of the json response
335
+ - "df" - A formatted pandas dataframe object. Defaults to "json".
336
+ Returns:
337
+ An Object that can be used to query historian data.
338
+ """
339
+ body = {"requests": {}}
340
+ allowed_aggregates = [
341
+ "FIRST",
342
+ "AVG",
343
+ "NUMGOOD",
344
+ "MAX",
345
+ "LAST",
346
+ "VAR",
347
+ "MEDIAN",
348
+ "NUMBAD",
349
+ "MIN",
350
+ "COUNT",
351
+ "STDDEV",
352
+ ]
353
+
354
+ if aggregates is None:
355
+ aggregates = allowed_aggregates
356
+ aggregates = list(map(lambda x: x.upper(), aggregates))
357
+ aggregates = list(filter(lambda x: x in allowed_aggregates, aggregates))
358
+
359
+ if aggregates == []:
360
+ raise EigenException(
361
+ "No valid aggregates provided. Allowed aggregates are: "
362
+ + ", ".join(allowed_aggregates)
363
+ )
364
+
365
+ tags = force_list(tags)
366
+ aggregates = force_list(aggregates)
367
+
368
+ for tag in tags:
369
+ fulltag = tag
370
+ if "/" not in tag:
371
+ fulltag = self.historian + tag
372
+ request = {
373
+ "type": "MULTIPLE_AGGREGATED_POINTS",
374
+ "tag": fulltag,
375
+ "details": {
376
+ "from": time_to_epoch_millis(start),
377
+ "to": time_to_epoch_millis(end),
378
+ "aggregates": aggregates,
379
+ "count": intervals,
380
+ },
381
+ }
382
+
383
+ body["requests"][tag] = request
384
+
385
+ response = _do_historian_multi_request(self.serverurl, body, self.auth)
386
+
387
+ return format_output(
388
+ output,
389
+ response,
390
+ tags,
391
+ timestamp_format=self.timestamp_format,
392
+ is_aggregate=True,
393
+ aggregates=aggregates,
394
+ )
395
+
396
+ def getAggregateIntervals(
397
+ self,
398
+ tags: Union[str, list],
399
+ start: Union[int, float, str, datetime],
400
+ end: Union[int, float, str, datetime],
401
+ interval_size: str = None,
402
+ aggregates: Union[str, list] = None,
403
+ final_interval_behavior: str = "EXCLUDE",
404
+ output: str = "json",
405
+ ):
406
+ """Get aggregates/statistics for one or more tags, split into specified time intervals, over a time range
407
+
408
+ Args:
409
+ tags: A datatag, or list of datatags
410
+ start: Start of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
411
+ end: End of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
412
+ interval_size (Optional): Duration of each sub time interval to calculate aggregates for. Format like e.g. ["1s", "1m", "1h", "1w", "1y"]. Defaults to the entire time range
413
+ final_interval_behavior (Optional): Behavior for the final interval if it would extend beyond the total window. Options include "INCLUDE", "EXCLUDE", etc. Defaults to "EXCLUDE".
414
+ aggregates (Optional): A string, or list of strings of the aggregates to return. Allowed values are: "FIRST", "AVG", "NUMGOOD", "MAX", "LAST", "VAR", "MEDIAN", "NUMBAD", "MIN", "COUNT", "STDDEV". Defaults to all aggregates.
415
+ output (Optional): The format in which to return the data. Accepts one of:
416
+ - "raw" - The raw json returned by the API
417
+ - "json" - A processed version of the json response
418
+ - "df" - A formatted pandas dataframe object. Defaults to "json".
419
+ Returns:
420
+ An Object that can be used to query historian data.
421
+ """
422
+ start_ms = time_to_epoch_millis(start)
423
+ end_ms = time_to_epoch_millis(end)
424
+
425
+ allowed_final_interval_behaviors = ["INCLUDE", "EXCLUDE"]
426
+ final_interval_behavior = final_interval_behavior.upper()
427
+ if final_interval_behavior not in allowed_final_interval_behaviors:
428
+ raise EigenException(
429
+ f"final_interval_behavior must be one of: {', '.join(allowed_final_interval_behaviors)}"
430
+ )
431
+
432
+ # Calculate window duration in ms
433
+ window_duration_ms = end_ms - start_ms
434
+
435
+ # Parse interval_size (e.g., "1h", "30m", "5s")
436
+ match = re.match(r"(\d+)(s|m|h|d|w|y)", interval_size)
437
+ if not match:
438
+ raise ValueError(f"Invalid interval_size format: {interval_size}")
439
+
440
+ amount, unit = int(match.group(1)), match.group(2)
441
+
442
+ # Convert interval to milliseconds
443
+ unit_to_ms = {
444
+ "s": 1000,
445
+ "m": 60 * 1000,
446
+ "h": 60 * 60 * 1000,
447
+ "d": 24 * 60 * 60 * 1000,
448
+ "w": 7 * 24 * 60 * 60 * 1000,
449
+ "y": 365 * 24 * 60 * 60 * 1000, # approximate
450
+ }
451
+ interval_ms = amount * unit_to_ms[unit]
452
+
453
+ # Calculate number of intervals
454
+ num_intervals = window_duration_ms / interval_ms
455
+
456
+ # Adjust based on final_interval_behavior
457
+ if final_interval_behavior == "INCLUDE":
458
+ num_intervals = int(num_intervals) + (
459
+ 1 if num_intervals % 1 > 0 else 0
460
+ ) # Ceiling
461
+ elif final_interval_behavior == "EXCLUDE":
462
+ num_intervals = int(num_intervals) # Floor
463
+
464
+ adjusted_end_ms = start_ms + (num_intervals * interval_ms)
465
+
466
+ if num_intervals <= 0:
467
+ raise EigenException(
468
+ "Calculated number of intervals is zero or negative. Please check the interval_size and time range."
469
+ )
470
+ elif num_intervals > 1000:
471
+ raise EigenException(
472
+ f"Calculated number of intervals exceeds maximum limit of 1,000 ({num_intervals}). Please increase interval_size or reduce time range."
473
+ )
474
+
475
+ return self.getAggregates(
476
+ tags,
477
+ start_ms,
478
+ adjusted_end_ms,
479
+ intervals=num_intervals,
480
+ aggregates=aggregates,
481
+ output=output,
482
+ )
483
+
484
+ # SECTION - Tag Metadata Requests
485
+
312
486
  def listDataTags(self, historian: str = None, limit: int = 100, match: str = ""):
313
487
  """List all tags in a historian, or those matching a wildcard
314
488
 
@@ -389,8 +563,6 @@ class HistorianMulti(object):
389
563
 
390
564
  return metadata
391
565
 
392
- # SECTION - Tag Metadata Requests
393
-
394
566
  def createTag(
395
567
  self,
396
568
  tag: str,
eigeningenuity/util.py CHANGED
@@ -166,7 +166,7 @@ def number_to_string(n):
166
166
 
167
167
  def time_to_epoch_millis(t):
168
168
  if type(t) == datetime:
169
- epochmillis = t.timestamp()
169
+ epochmillis = t.timestamp() * 1000
170
170
  elif type(t) == int or type(t) == float:
171
171
  if t > 100000000000:
172
172
  epochmillis = int(t)
@@ -613,7 +613,9 @@ def _do_historian_multi_request(
613
613
  return resp
614
614
 
615
615
 
616
- def _reformat_multi_response(original_dict):
616
+ def _reformat_multi_response(original_dict, is_aggregate=False):
617
+ if is_aggregate:
618
+ return original_dict
617
619
  reformatted_dict = {}
618
620
 
619
621
  for key, value in original_dict.items():
@@ -625,15 +627,37 @@ def _reformat_multi_response(original_dict):
625
627
  continue
626
628
  else:
627
629
  # Extract the list of data points from either 'dataPoints' or 'dataPoint' key
628
- data_points = value.get("dataPoints") or value.get("dataPoint") or value
630
+ data_points = (
631
+ value.get("dataPoints", None) or value.get("dataPoint", None) or value
632
+ )
629
633
  # Assign the data points list directly to the top-level key
630
634
  reformatted_dict[key] = data_points
631
635
 
632
636
  return reformatted_dict
633
637
 
634
638
 
635
- def format_output(output, response, tags, timestamps=False, timestamp_format="iso"):
636
- if not timestamps:
639
+ def format_output(
640
+ output,
641
+ response,
642
+ tags,
643
+ timestamps=False,
644
+ timestamp_format="iso",
645
+ is_aggregate=False,
646
+ aggregates=[],
647
+ ):
648
+ if is_aggregate:
649
+ items = {}
650
+ aggregates_lower = [agg.lower() for agg in aggregates]
651
+ for tag, data in response["results"].items():
652
+ items[tag] = []
653
+ for agg in data["aggregates"]:
654
+ filtered_agg = {
655
+ k: v
656
+ for k, v in agg.items()
657
+ if k.lower() in ["from", "to", "tag", *aggregates_lower]
658
+ }
659
+ items[tag].append(filtered_agg)
660
+ elif not timestamps:
637
661
  items = response["results"]
638
662
  else:
639
663
  items = response
@@ -642,19 +666,32 @@ def format_output(output, response, tags, timestamps=False, timestamp_format="is
642
666
  return response
643
667
  elif output == "json":
644
668
  if len(tags) == 1 and (not timestamps or len(timestamps) == 1):
645
- return _reformat_multi_response(items[tags[0]])
669
+ return _reformat_multi_response(items[tags[0]], is_aggregate)
646
670
  else:
647
- return _reformat_multi_response(items)
671
+ return _reformat_multi_response(items, is_aggregate)
648
672
  elif output == "string":
649
673
  return json.dumps(items, indent=4)
650
674
  elif output == "df":
651
- return multi_response_to_df(items)
675
+ if is_aggregate:
676
+ return aggregate_response_to_df(items)
677
+ else:
678
+ return multi_response_to_df(items)
652
679
 
653
680
  raise EigenException(
654
681
  "Unrecognised Output Type. Must be one of ['raw','json','string','df']"
655
682
  )
656
683
 
657
684
 
685
+ def aggregate_response_to_df(items):
686
+ rows = []
687
+ for tag, data in items.items():
688
+ data = force_list(data)
689
+ for entry in data:
690
+ rows.append({"tag": tag, **entry})
691
+ df = pd.DataFrame(rows).set_index("tag")
692
+ return df
693
+
694
+
658
695
  class EigenException(Exception):
659
696
  pass
660
697
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-eigen-ingenuity
3
- Version: 0.5.22b1
3
+ Version: 0.5.22b2
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
@@ -5,10 +5,10 @@ eigeningenuity/commonmenu.py,sha256=G-l5fhOnLNpxJpMeek373zEyS26G9-HBH4VtzmRCT3E,
5
5
  eigeningenuity/elastic.py,sha256=RC9BZ_DZJsVzW1Sd5F9-ziCLGImCGLMt94VAqpdRM5A,7272
6
6
  eigeningenuity/events.py,sha256=I2W5SMvDQA5dwW9mjzOpv6CGEbVhYD42t36i5m6Ljas,12911
7
7
  eigeningenuity/historian.py,sha256=ByjGqD-70DQUTDFo88gWyoFOrGMXf-OUYzR8rWSnODI,39843
8
- eigeningenuity/historianmulti.py,sha256=mw0i_lQf65QndCIuRKiC_brOV9_YY9zeKWm_P_IofXA,28213
8
+ eigeningenuity/historianmulti.py,sha256=h85jaKVaw1EmS0jaX5YCNC5q1_BhQKiUR4Jl2tx6nag,35479
9
9
  eigeningenuity/settings.py,sha256=sCY7AONBrc0IWSa3D37Scu_JapQoEBfJbRbY7BdDoBM,4212
10
10
  eigeningenuity/sql.py,sha256=r9kHjOymZxKY2HpAT3jYSr77oSDyT8UK-DLSaSDk7zI,5063
11
- eigeningenuity/util.py,sha256=qJI3a4ioKfXMeH1T5bv0eTr6qH1kD4f_1n3xXkByspM,21694
11
+ eigeningenuity/util.py,sha256=ZCJwJ2WlvqzEM3mSmRkZarhFtvlNYVFRu2TdPkMtOh4,22732
12
12
  eigeningenuity/core/__init__.py,sha256=4MmgxGtq_sDKdBaaCinlkHvkeAUOqT18kyrc0ol_dAc,4499
13
13
  local-tests/__init__.py,sha256=oe1wRdOprjUbn027t5ybBBo5T9_byi-burZFgv64ND4,149
14
14
  local-tests/common.py,sha256=dIMBplH4P4T-BlhODjD5_RLhK2uA18MxEesiIMslsG0,1766
@@ -86,8 +86,8 @@ regressiontests/eigeningenuity/historian-multi/test_getRawDatapoints.py,sha256=f
86
86
  regressiontests/eigeningenuity/historian-multi/test_listDataTags.py,sha256=TcceNSjCKoiK5SJcgTH2JXfKLYxIHdQdwZWlkpGnEVM,2006
87
87
  regressiontests/eigeningenuity/historian-multi/test_tagManagement.py,sha256=ylInBt453d1RaSih1eTTxGPZmb60UK4vMwI3UW-U1JY,4830
88
88
  regressiontests/eigeningenuity/historian-multi/test_writePoints.py,sha256=51tfUSLUqLKcCKJ1EyhjfzoC_4OP6n1oL3zgTSkXu4s,2696
89
- python_eigen_ingenuity-0.5.22b1.dist-info/METADATA,sha256=Zvw4mgiqfk0fUlWSog-wpEO-rfByhV82zdZ1IiS7u-4,38421
90
- python_eigen_ingenuity-0.5.22b1.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
91
- python_eigen_ingenuity-0.5.22b1.dist-info/entry_points.txt,sha256=G3LjFQX5xKaN4mqtqCL8uaC-gRbP5T5x9r0gBTJTXXA,70
92
- python_eigen_ingenuity-0.5.22b1.dist-info/top_level.txt,sha256=oDWOSmlNPKNBlIEKP8_JaV01O60jTcUIt2tDkq3OD18,56
93
- python_eigen_ingenuity-0.5.22b1.dist-info/RECORD,,
89
+ python_eigen_ingenuity-0.5.22b2.dist-info/METADATA,sha256=TnuNd5XMmQA6TtCtpsA9yoyUGm8Dxnsul73jmbb2ON8,38421
90
+ python_eigen_ingenuity-0.5.22b2.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
91
+ python_eigen_ingenuity-0.5.22b2.dist-info/entry_points.txt,sha256=G3LjFQX5xKaN4mqtqCL8uaC-gRbP5T5x9r0gBTJTXXA,70
92
+ python_eigen_ingenuity-0.5.22b2.dist-info/top_level.txt,sha256=oDWOSmlNPKNBlIEKP8_JaV01O60jTcUIt2tDkq3OD18,56
93
+ python_eigen_ingenuity-0.5.22b2.dist-info/RECORD,,