python-eigen-ingenuity 0.5.30b4__py3-none-any.whl → 0.5.31__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.
@@ -17,22 +17,23 @@ eigeningenuity.core) or a full URL to a JSON Bridge Historian instance.
17
17
  print(asctime(time.gmtime(dp['timestamp'])), dp['value'])
18
18
  """
19
19
 
20
- import requests
21
20
  import re
22
- from typing import Union
23
21
  from datetime import datetime
22
+ from typing import Union
23
+ from urllib.error import URLError
24
24
 
25
+ import requests
25
26
  from requests.exceptions import ConnectionError
26
- from urllib.error import URLError
27
- from eigeningenuity.core import get_default_server, EigenServer
27
+
28
+ from eigeningenuity.core import EigenServer, get_default_server
28
29
  from eigeningenuity.util import (
29
- force_list,
30
- time_to_epoch_millis,
31
30
  EigenException,
32
- merge_tags_from_response,
33
- update_keys,
34
31
  _do_historian_multi_request,
32
+ force_list,
35
33
  format_output,
34
+ merge_tags_from_response,
35
+ time_to_epoch_millis,
36
+ update_keys,
36
37
  )
37
38
 
38
39
 
@@ -88,7 +89,7 @@ class HistorianMulti(object):
88
89
  RemoteServerException: If the historian cannot be found or the API returns an error.
89
90
  RuntimeError: If no response is received from the API.
90
91
  HTTPError: If the API request fails.
91
-
92
+
92
93
  Docs:
93
94
  https://docs.eigeningenuity.co/developing-with-eigen/python-library/historian-multi/reading-data/getcurrentdatapoints
94
95
  """
@@ -132,7 +133,7 @@ class HistorianMulti(object):
132
133
  RemoteServerException: If the historian cannot be found or the API returns an error.
133
134
  RuntimeError: If no response is received from the API.
134
135
  HTTPError: If the API request fails.
135
-
136
+
136
137
  Docs:
137
138
  https://docs.eigeningenuity.co/developing-with-eigen/python-library/historian-multi/reading-data/getinterpolatedpoints
138
139
  """
@@ -188,7 +189,7 @@ class HistorianMulti(object):
188
189
  RemoteServerException: If the historian cannot be found or the API returns an error.
189
190
  RuntimeError: If no response is received from the API.
190
191
  HTTPError: If the API request fails.
191
-
192
+
192
193
  Docs:
193
194
  https://docs.eigeningenuity.co/developing-with-eigen/python-library/historian-multi/reading-data/getinterpolatedrange
194
195
  """
@@ -245,7 +246,7 @@ class HistorianMulti(object):
245
246
  RemoteServerException: If the historian cannot be found or the API returns an error.
246
247
  RuntimeError: If no response is received from the API.
247
248
  HTTPError: If the API request fails.
248
-
249
+
249
250
  Docs:
250
251
  https://docs.eigeningenuity.co/developing-with-eigen/python-library/historian-multi/reading-data/getrawdatapoints
251
252
  """
@@ -285,24 +286,24 @@ class HistorianMulti(object):
285
286
  ):
286
287
  """Get the closest raw point to one or more timestamps.
287
288
 
288
- Args:
289
- tags (Union[str, list]): Tag name or list of tags to query.
290
- timestamps (Union[int, float, str, datetime, list]): One or more timestamps to find closest raw points for.
291
- before_or_after (str, optional): Selection rule for closest point. Defaults to "AFTER_OR_AT".
292
- output (str, optional): Output format selector. Accepts "json", "df", "raw", "string". Defaults to "json".
293
-
294
- Returns:
295
- dict|list|pandas.DataFrame|str: Closest raw points to the timestamps. Format depends on output parameter.
296
-
297
- Raises:
298
- ValueError: When invalid Output Type is given
299
- URLError: If no Ingenuity instance can be reached or no internet connection is available.
300
- RemoteServerException: If the historian cannot be found or the API returns an error.
301
- RuntimeError: If no response is received from the API.
302
- HTTPError: If the API request fails.
303
-
304
- Docs:
305
- https://docs.eigeningenuity.co/developing-with-eigen/python-library/historian-multi/reading-data/getclosestrawpoint
289
+ Args:
290
+ tags (Union[str, list]): Tag name or list of tags to query.
291
+ timestamps (Union[int, float, str, datetime, list]): One or more timestamps to find closest raw points for.
292
+ before_or_after (str, optional): Selection rule for closest point. Defaults to "AFTER_OR_AT".
293
+ output (str, optional): Output format selector. Accepts "json", "df", "raw", "string". Defaults to "json".
294
+
295
+ Returns:
296
+ dict|list|pandas.DataFrame|str: Closest raw points to the timestamps. Format depends on output parameter.
297
+
298
+ Raises:
299
+ ValueError: When invalid Output Type is given
300
+ URLError: If no Ingenuity instance can be reached or no internet connection is available.
301
+ RemoteServerException: If the historian cannot be found or the API returns an error.
302
+ RuntimeError: If no response is received from the API.
303
+ HTTPError: If the API request fails.
304
+
305
+ Docs:
306
+ https://docs.eigeningenuity.co/developing-with-eigen/python-library/historian-multi/reading-data/getclosestrawpoint
306
307
  """
307
308
  before_or_after = before_or_after.upper()
308
309
 
@@ -374,7 +375,7 @@ class HistorianMulti(object):
374
375
  RemoteServerException: If the historian cannot be found or the API returns an error.
375
376
  RuntimeError: If no response is received from the API.
376
377
  HTTPError: If the API request fails.
377
-
378
+
378
379
  Docs:
379
380
  https://docs.eigeningenuity.co/developing-with-eigen/python-library/historian-multi/reading-data/getaggregates
380
381
  """
@@ -465,7 +466,7 @@ class HistorianMulti(object):
465
466
  RemoteServerException: If the historian cannot be found or the API returns an error.
466
467
  RuntimeError: If no response is received from the API.
467
468
  HTTPError: If the API request fails.
468
-
469
+
469
470
  Docs:
470
471
  https://docs.eigeningenuity.co/developing-with-eigen/python-library/historian-multi/reading-data/getaggregateintervals
471
472
  """
@@ -549,7 +550,7 @@ class HistorianMulti(object):
549
550
  RemoteServerException: If the historian cannot be found or the API returns an error.
550
551
  RuntimeError: If no response is received from the API.
551
552
  HTTPError: If the API request fails.
552
-
553
+
553
554
  Docs:
554
555
  https://docs.eigeningenuity.co/developing-with-eigen/python-library/historian-multi/metadata/listdatatags
555
556
  """
@@ -559,14 +560,20 @@ class HistorianMulti(object):
559
560
 
560
561
  return tags
561
562
 
562
- def getMetaData(self, historian: str = None, limit: int = 100, match: str = ""):
563
+ def getMetaData(
564
+ self,
565
+ historian: str = None,
566
+ limit: int = 100,
567
+ match: str = "",
568
+ output: str = "json",
569
+ ):
563
570
  """Fetch tag metadata for a historian, optionally filtered with a wildcard.
564
571
 
565
572
  Args:
566
573
  historian (str, optional): Historian name to search.
567
574
  limit (int, optional): Max number of tags returned. Defaults to 100.
568
575
  match (str, optional): Wildcard pattern for tag names. Defaults to "".
569
-
576
+ output (str, optional): Output format selector. Accepts "json", "raw". Defaults to "json".
570
577
  Returns:
571
578
  list[dict]: List of metadata dictionaries for each tag.
572
579
 
@@ -575,12 +582,16 @@ class HistorianMulti(object):
575
582
  RemoteServerException: If the historian cannot be found or the API returns an error.
576
583
  RuntimeError: If no response is received from the API.
577
584
  HTTPError: If the API request fails.
578
-
585
+
579
586
  Docs:
580
587
  https://docs.eigeningenuity.co/developing-with-eigen/python-library/historian-multi/metadata/getmetadata
581
588
  """
582
- if historian is None:
583
- historian = self.historian
589
+ if "/" in historian and match == "":
590
+ split_hist = historian.split("/")
591
+ match = split_hist[1]
592
+ historian = split_hist[0]
593
+ elif historian is None:
594
+ historian = self.historian[0:-1]
584
595
 
585
596
  resp = _do_historian_multi_request(
586
597
  self.searchurl + f"?historian={historian}&limit={limit}&search={match}",
@@ -590,7 +601,12 @@ class HistorianMulti(object):
590
601
  )
591
602
  metadata = resp["tags"]
592
603
 
593
- return metadata
604
+ if output == "raw":
605
+ return metadata
606
+ elif output == "json":
607
+ return {tag["tagName"]: tag for tag in metadata}
608
+ else:
609
+ raise ValueError(f"Invalid output format: {output}")
594
610
 
595
611
  def listHistorians(self, writable):
596
612
  """Retrieve all historians available on the Ingenuity instance.
@@ -608,7 +624,7 @@ class HistorianMulti(object):
608
624
  RemoteServerException: If the historian cannot be found or the API returns an error.
609
625
  RuntimeError: If no response is received from the API.
610
626
  HTTPError: If the API request fails.
611
-
627
+
612
628
  Docs:
613
629
  https://docs.eigeningenuity.co/developing-with-eigen/python-library/historian-multi/metadata/listhistorians
614
630
  """
@@ -619,9 +635,9 @@ class HistorianMulti(object):
619
635
  self.auth,
620
636
  get_request=True,
621
637
  )
622
-
638
+
623
639
  historians = resp["historians"]
624
-
640
+
625
641
  metadata = [x["name"] for x in historians]
626
642
 
627
643
  return metadata
@@ -651,7 +667,7 @@ class HistorianMulti(object):
651
667
  RemoteServerException: If the historian cannot be found or the API returns an error.
652
668
  RuntimeError: If no response is received from the API.
653
669
  HTTPError: If the API request fails.
654
-
670
+
655
671
  Docs:
656
672
  https://docs.eigeningenuity.co/developing-with-eigen/python-library/historian-multi/metadata/createtag
657
673
  """
@@ -706,7 +722,7 @@ class HistorianMulti(object):
706
722
  RemoteServerException: If the historian cannot be found or the API returns an error.
707
723
  RuntimeError: If no response is received from the API.
708
724
  HTTPError: If the API request fails.
709
-
725
+
710
726
  Docs:
711
727
  https://docs.eigeningenuity.co/developing-with-eigen/python-library/historian-multi/metadata/updatetag
712
728
  """
@@ -763,7 +779,7 @@ class HistorianMulti(object):
763
779
  RemoteServerException: If the historian cannot be found or the API returns an error.
764
780
  RuntimeError: If no response is received from the API.
765
781
  HTTPError: If the API request fails.
766
-
782
+
767
783
  Docs:
768
784
  https://docs.eigeningenuity.co/developing-with-eigen/python-library/historian-multi/writing-data/createandpopulatetag
769
785
  """
@@ -823,7 +839,7 @@ class HistorianMulti(object):
823
839
  RemoteServerException: If the historian cannot be found or the API returns an error.
824
840
  RuntimeError: If no response is received from the API.
825
841
  HTTPError: If the API request fails.
826
-
842
+
827
843
  Docs:
828
844
  https://docs.eigeningenuity.co/developing-with-eigen/python-library/historian-multi/writing-data/writepoints
829
845
  """
@@ -861,7 +877,7 @@ class HistorianMulti(object):
861
877
  RemoteServerException: If the historian cannot be found or the API returns an error.
862
878
  RuntimeError: If no response is received from the API.
863
879
  HTTPError: If the API request fails.
864
-
880
+
865
881
  Docs:
866
882
  https://docs.eigeningenuity.co/developing-with-eigen/python-library/historian-multi/writing-data/writepointsbatch
867
883
  """
@@ -916,7 +932,7 @@ def createPoint(
916
932
 
917
933
  Raises:
918
934
  EigenException: If status is not "OK" or "BAD".
919
-
935
+
920
936
  Docs:
921
937
  https://docs.eigeningenuity.co/developing-with-eigen/python-library/historian-multi/writing-data/createpoint
922
938
  """
@@ -937,7 +953,7 @@ def get_historian_multi(
937
953
 
938
954
  Returns:
939
955
  HistorianMulti: An object that can be used to query historian data.
940
-
956
+
941
957
  Docs:
942
958
  https://docs.eigeningenuity.co/developing-with-eigen/python-library/historian-multi/get_historian_multi
943
959
  """
@@ -133,34 +133,24 @@ class CSVContentsManager:
133
133
 
134
134
  def get_property_values_dict(self, row_number, column_numbers, allow_blank_property_list, default_key='', prefix='', blank_override='', allow_split=True):
135
135
  this_row = self.data_list[row_number]
136
- if allow_split:
137
- split_values = [this_row[column].split('::', 2) for column in column_numbers]
138
- else:
139
- split_values = [[this_row[column]] for column in column_numbers]
140
- split_keys = [(value[0] + ':').split(':') for value in split_values]
141
- this_list = {prefix + (self.mapped_keys[column] or default_key): Neo4jProperty(prefix + (self.mapped_keys[column] or default_key), this_row[column], self.formats[column], blank_override=blank_override) if len(split_values[count]) == 1 else {prefix + (split_keys[count][0] or default_key): Neo4jProperty(prefix + (split_keys[count][0] or default_key), split_values[count][1], split_keys[count][1] or self.formats[column], blank_override=blank_override)} for count, column in enumerate(column_numbers) if this_row[column] or self.mapped_keys[column] in allow_blank_property_list or allow_blank_property_list == []}
136
+ split_values, labels, split_keys = self.get_property_value_data(this_row, column_numbers, allow_split)
137
+ this_list = {prefix + (self.mapped_keys[column] or default_key): Neo4jProperty(prefix + (self.mapped_keys[column] or default_key), this_row[column], self.formats[column], blank_override=blank_override, labels=labels[count]) if len(split_values[count]) == 1 else {prefix + (split_keys[count][0] or default_key): Neo4jProperty(prefix + (split_keys[count][0] or default_key), split_values[count][1], split_keys[count][1] or self.formats[column], blank_override=blank_override, labels=labels[0])} for count, column in enumerate(column_numbers) if this_row[column] or self.mapped_keys[column] in allow_blank_property_list or allow_blank_property_list == []}
142
138
  return this_list
143
139
 
144
- def parse_property_value_with_labels(self, raw_value, default_key, override_key, format_value):
145
- match_labels = ''
146
- value_parts = raw_value.split('$$', 1)
147
- value = value_parts[0]
148
- if len(value_parts) > 1:
149
- match_labels = value_parts[1]
150
-
151
- if '::' in value:
152
- key_value_parts = value.split('::', 1)
153
- key = key_value_parts[0] or default_key
154
- value = key_value_parts[1]
155
- else:
156
- key = override_key or default_key
157
-
158
- return Neo4jProperty(key, value, format_value, match_labels=match_labels)
159
-
160
140
  def get_property_values_list(self, row_number, column_numbers, default_key='', override_key='', allow_split=True, override_format=None):
161
141
  this_row = self.data_list[row_number]
142
+ split_values, labels, split_keys = self.get_property_value_data(this_row, column_numbers, allow_split)
143
+ these_keys = [override_key or self.mapped_keys[column] if self.types[column] == '' else self.mapped_keys[column] or default_key for column in column_numbers]
144
+ this_list = [Neo4jProperty(these_keys[count], split_values[count][0], override_format or self.formats[column], labels=labels[count]) if len(split_values[count]) == 1 else Neo4jProperty(split_values[count][0] or default_key, split_values[count][1], override_format or split_keys[count][1] or self.formats[column], labels=labels[count]) for count, column in enumerate(column_numbers) if this_row[column]]
145
+ return this_list
146
+
147
+ def get_property_value_data(self, this_row, column_numbers, allow_split=True):
162
148
  if allow_split:
163
- this_list = [self.parse_property_value_with_labels(this_row[column], self.mapped_keys[column] or default_key, override_key or self.mapped_keys[column] if self.types[column] == '' else self.mapped_keys[column] or default_key, override_format or self.formats[column]) for column in column_numbers if this_row[column]]
149
+ split_vals = [this_row[column].split('::') for column in column_numbers]
164
150
  else:
165
- this_list = [Neo4jProperty(override_key or self.mapped_keys[column] if self.types[column] == '' else self.mapped_keys[column] or default_key, this_row[column], override_format or self.formats[column]) for column in column_numbers if this_row[column]]
166
- return this_list
151
+ split_vals = [[this_row[column]] for column in column_numbers]
152
+ split_values = [[split_val[0].split(':')[0]] if len(split_val) == 1 else [split_val[0], split_val[1].split(':')[0]] for split_val in split_vals]
153
+ labels = [[(split_val[-1]+':').split(':', 1)[1][0:-1]] for split_val in split_vals]
154
+ split_keys = [(value[0] + ':').split(':') for value in split_values]
155
+
156
+ return split_values, labels, split_keys
@@ -1,4 +1,7 @@
1
1
  import csv
2
+ from io import StringIO
3
+ from charset_normalizer import from_bytes
4
+ import unicodedata
2
5
 
3
6
  import messages
4
7
  from csvcontentsmanager import CSVContentsManager
@@ -39,8 +42,7 @@ class FileAnalyser():
39
42
  file_name = amu.find_file(self.def_path, filename)
40
43
  if file_name is None:
41
44
  return 'fnf', contents, []
42
-
43
-
45
+
44
46
  if self.force_encoding:
45
47
  try:
46
48
  self.logger(f"Trying to read file with forced encoding {self.force_encoding}")
@@ -49,26 +51,40 @@ class FileAnalyser():
49
51
  contents = CSVContentsManager(csv_data, self.header_mappings, self.alias_mappings, self.default_data_type)
50
52
  except Exception as exc:
51
53
  self.logger(f"Error reading file with forced encoding {self.force_encoding}: {exc}")
52
- try:
53
- self.logger('Trying to read file with utf-8 encoding')
54
- with open(file_name, encoding='utf-8') as csv_file:
55
- csv_data = csv.reader(csv_file, delimiter=self.separator)
56
- contents = CSVContentsManager(csv_data, self.header_mappings, self.alias_mappings, self.default_data_type)
57
- except:
58
- try:
59
- self.logger('utf-8 encoding failed, trying to auto-detect encoding')
60
- with open(file_name) as csv_file:
61
- csv_data = csv.reader(csv_file, delimiter=self.separator)
62
- contents = CSVContentsManager(csv_data, self.header_mappings, self.alias_mappings, self.default_data_type)
63
- except:
54
+ match file_format:
55
+ case 'csv':
64
56
  try:
65
- self.logger('auto-detect encoding failed, trying iso-8859-1')
66
-
67
- with open(file_name, encoding='iso-8859-1') as csv_file:
68
- csv_data = csv.reader(csv_file, delimiter=self.separator)
69
- contents = CSVContentsManager(csv_data, self.header_mappings, self.alias_mappings, self.default_data_type)
70
- except:
71
- return 'incorrect file format', contents, []
57
+ with open(file_name, "rb") as f:
58
+ raw = f.read()
59
+
60
+ # detect encoding
61
+ result = from_bytes(raw)
62
+ best = result.best()
63
+
64
+ if best is None:
65
+ return 'incorrect file format', None, []
66
+
67
+ text = str(best)
68
+
69
+ # normalize unicode (fix Mac/Windows accent differences)
70
+ text = unicodedata.normalize("NFC", text)
71
+
72
+ csv_data = csv.reader(
73
+ StringIO(text),
74
+ delimiter=self.separator
75
+ )
76
+
77
+ contents = CSVContentsManager(
78
+ csv_data,
79
+ self.header_mappings,
80
+ self.alias_mappings,
81
+ self.default_data_type
82
+ )
83
+
84
+ except Exception:
85
+ return 'incorrect file format', None, []
86
+ case _:
87
+ pass
72
88
  elif self.detect_encoding:
73
89
  try:
74
90
  self.logger('Detecting file encoding...')
@@ -92,25 +108,35 @@ class FileAnalyser():
92
108
  match file_format:
93
109
  case 'csv':
94
110
  try:
95
- self.logger('Trying to read file with utf-8 encoding')
96
- with open(file_name, encoding='utf-8') as csv_file:
97
- csv_data = csv.reader(csv_file, delimiter=self.separator)
98
- contents = CSVContentsManager(csv_data, self.header_mappings, self.alias_mappings, self.default_data_type)
99
- except:
100
- try:
101
- self.logger('utf-8 encoding failed, trying to auto-detect encoding')
102
- with open(file_name) as csv_file:
103
- csv_data = csv.reader(csv_file, delimiter=self.separator)
104
- contents = CSVContentsManager(csv_data, self.header_mappings, self.alias_mappings, self.default_data_type)
105
- except:
106
- try:
107
- self.logger('auto-detect encoding failed, trying iso-8859-1')
108
-
109
- with open(file_name, encoding='iso-8859-1') as csv_file:
110
- csv_data = csv.reader(csv_file, delimiter=self.separator)
111
- contents = CSVContentsManager(csv_data, self.header_mappings, self.alias_mappings, self.default_data_type)
112
- except:
113
- return 'incorrect file format', contents, []
111
+ with open(file_name, "rb") as f:
112
+ raw = f.read()
113
+
114
+ # detect encoding
115
+ result = from_bytes(raw)
116
+ best = result.best()
117
+
118
+ if best is None:
119
+ return 'incorrect file format', None, []
120
+
121
+ text = str(best)
122
+
123
+ # normalize unicode (fix Mac/Windows accent differences)
124
+ text = unicodedata.normalize("NFC", text)
125
+
126
+ csv_data = csv.reader(
127
+ StringIO(text),
128
+ delimiter=self.separator
129
+ )
130
+
131
+ contents = CSVContentsManager(
132
+ csv_data,
133
+ self.header_mappings,
134
+ self.alias_mappings,
135
+ self.default_data_type
136
+ )
137
+
138
+ except Exception:
139
+ return 'incorrect file format', None, []
114
140
  case _:
115
141
  pass
116
142
 
@@ -121,6 +121,12 @@ def strip_quotes(quote_list):
121
121
  return stripped_list
122
122
 
123
123
 
124
+ def merge_node_labels(merge_labels, node_labels):
125
+ wanted, _, remove = sort_labels(merge_labels, node_labels)
126
+ merged_labels = [i for i in merge_labels + wanted if not i in remove]
127
+ return merged_labels
128
+
129
+
124
130
  def merge_labels(self, required_labels, unrequired_labels, remove_labels):
125
131
  merged_labels = [i for i in self.required_labels + required_labels if (not ('!' + i in unrequired_labels) and not (i in remove_labels) and not (i.startswith('!')))]
126
132
  return merged_labels
@@ -129,7 +135,7 @@ def merge_labels(self, required_labels, unrequired_labels, remove_labels):
129
135
  def combine_required_labels(config_labels, override_labels):
130
136
  valid_config_labels = validate_labels_to_list(config_labels)
131
137
  valid_override_labels = validate_label_string_to_list(override_labels)
132
- required_labels = [i for i in valid_config_labels if (not(i.startswith('!') and ('!'+i not in valid_config_labels)) and ('!'+i not in valid_override_labels))] + [i for i in valid_override_labels if (not(i.startswith('!')) and ('!'+i not in valid_override_labels))]
138
+ required_labels = [i for i in valid_config_labels if (not(i.startswith('!')) and ('!'+i not in valid_config_labels) and ('!'+i not in valid_override_labels))] + [i for i in valid_override_labels if (not(i.startswith('!')) and ('!'+i not in valid_override_labels))]
133
139
  unwanted_labels = [i for i in valid_config_labels if (i.startswith('!') and (i[1:] not in valid_override_labels) and ('!' + i not in valid_override_labels))] + [i for i in valid_override_labels if i.startswith('!') and not i.startswith('!!')]
134
140
 
135
141
  combined_list = list(set(required_labels + unwanted_labels))
@@ -50,16 +50,6 @@ class NodeFileProcessor:
50
50
  last_row = min(num_rows, self.last_row)
51
51
  return last_row
52
52
 
53
- def get_inline_merge_labels(self, label_string):
54
- # For node MERGE, only colon-separated labels are directly supported.
55
- # OR expressions (label1|label2) are ignored here because MERGE cannot express label OR.
56
- if not label_string:
57
- return []
58
- if '|' in label_string:
59
- messages.warning_message('Unsupported inline node label expression: ', f'{label_string} (ignoring OR labels for MERGE)')
60
- return []
61
- return lm.validate_label_string_to_list(label_string)
62
-
63
53
  def process_node_file(self):
64
54
 
65
55
  # For each line in the file, build a cypher query to MERGE a node
@@ -91,13 +81,13 @@ class NodeFileProcessor:
91
81
 
92
82
  for primary_property in self.contents.get_property_values_list(this_row, node_columns, self.primary_property, allow_split=True, override_format='str'):
93
83
  time_now = amu.get_formatted_time_now()
94
- inline_merge_labels = self.get_inline_merge_labels(primary_property.match_labels)
95
- merge_labels, new_labels, remove_labels = lm.sort_node_labels(self.required_labels, validated_csv_labels + inline_merge_labels)
84
+ merge_labels, new_labels, remove_labels = lm.sort_node_labels(self.required_labels, validated_csv_labels)
85
+ node_labels = lm.merge_node_labels(merge_labels, primary_property.labels)
96
86
 
97
87
  # Build a simple MERGE query using queries
98
88
  query_text = (QueryBuilder()
99
89
  .merge()
100
- .node(labels=merge_labels, ref_name=property_ref, properties=primary_property)
90
+ .node(labels=node_labels, ref_name=property_ref, properties=primary_property)
101
91
  )
102
92
 
103
93
  # Add in System properties if required
@@ -170,8 +160,8 @@ class NodeFileProcessor:
170
160
  row_properties = self.contents.get_property_values_dict(this_row, property_columns, self.blank_property_list, blank_override=self.blank_property_override, allow_split=False)
171
161
 
172
162
  for primary_property in self.contents.get_property_values_list(this_row, node_columns, self.primary_property, allow_split=True, override_format='str'):
173
- inline_merge_labels = self.get_inline_merge_labels(primary_property.match_labels)
174
- merge_labels, new_labels, remove_labels = lm.sort_node_labels(self.required_labels, validated_csv_labels + inline_merge_labels)
163
+ merge_labels, new_labels, remove_labels = lm.sort_node_labels(self.required_labels, validated_csv_labels)
164
+ node_labels = lm.merge_node_labels(merge_labels, primary_property.labels)
175
165
  properties = pm.combine_properties(self.required_properties, row_properties)
176
166
  # Remove any properties we don't want
177
167
  for unwanted in self.unrequired_properties:
@@ -193,7 +183,7 @@ class NodeFileProcessor:
193
183
  # So now we know all about this particular update. Let's put it in the query dictionary
194
184
  # We'll group these by unique combinations of labels and primary key type
195
185
  # Have to use a list since a dictionary key can't be a dictionary
196
- dictionary_key = [new_labels, merge_labels, remove_labels, [primary_property.key], calculated_properties.keys()]
186
+ dictionary_key = [new_labels, node_labels, remove_labels, [primary_property.key], calculated_properties.keys()]
197
187
  try:
198
188
  dictionary_index = batch_keys.index(dictionary_key)
199
189
  query_dictionary[dictionary_index] += query_data_list
@@ -58,45 +58,6 @@ class RelationshipFileProcessor:
58
58
  last_row = min(num_rows, self.last_row)
59
59
  return last_row
60
60
 
61
- def get_inline_match_labels(self, node_ref, label_string):
62
- # Supports:
63
- # label1 -> node_ref:label1
64
- # label1:label2 -> node_ref:label1 AND node_ref:label2
65
- # label1|label2 -> node_ref:label1 OR node_ref:label2
66
- # label1:label2|label3 -> (node_ref:label1 AND node_ref:label2) OR node_ref:label3
67
- if not label_string:
68
- return [], ''
69
-
70
- # Grouped expression support:
71
- # prefix:(a|b) -> required label 'prefix' + WHERE (node_ref:a OR node_ref:b)
72
- # prefix1:prefix2:(a|b) -> required labels 'prefix1' and 'prefix2' + grouped OR
73
- if label_string.endswith(')') and ':(' in label_string:
74
- prefix, grouped = label_string.rsplit(':(', 1)
75
- grouped = grouped[:-1]
76
- if grouped and '|' in grouped:
77
- required_labels = lm.validate_label_string_to_list(prefix)
78
- option_literals = []
79
- for option in grouped.split('|'):
80
- these_labels = lm.validate_label_string_to_list(option)
81
- if these_labels:
82
- option_literals.append('(' + ' AND '.join([f'{node_ref}:{label}' for label in these_labels]) + ')')
83
- if option_literals:
84
- return required_labels, '(' + ' OR '.join(option_literals) + ')'
85
-
86
- if '|' not in label_string:
87
- return lm.validate_label_string_to_list(label_string), ''
88
-
89
- option_literals = []
90
- for option in label_string.split('|'):
91
- these_labels = lm.validate_label_string_to_list(option)
92
- if these_labels:
93
- option_literals.append('(' + ' AND '.join([f'{node_ref}:{label}' for label in these_labels]) + ')')
94
-
95
- if not option_literals:
96
- return [], ''
97
-
98
- return [], '(' + ' OR '.join(option_literals) + ')'
99
-
100
61
  def process_relationship_file(self):
101
62
 
102
63
  # For each line in the file, build a cypher query to MERGE a relationship
@@ -136,12 +97,12 @@ class RelationshipFileProcessor:
136
97
  # If there are multiple From or To nodes, create a relationship query for each combination
137
98
  for from_node in self.contents.get_property_values_list(this_row, from_columns, self.primary_property, self.from_property, override_format='str'):
138
99
  validated_csv_from_labels = lm.validate_labels(self.contents.get_column_values_list(this_row, from_label_columns))
139
- inline_from_labels, inline_from_where = self.get_inline_match_labels(from_ref, from_node.match_labels)
140
- from_labels = lm.sort_relationship_labels(self.required_labels + self.from_required_labels, validated_csv_from_labels + inline_from_labels)
100
+ from_labels = lm.sort_relationship_labels(self.required_labels + self.from_required_labels, validated_csv_from_labels)
101
+ from_node_labels = lm.merge_node_labels(from_labels, from_node.labels)
141
102
  for to_node in self.contents.get_property_values_list(this_row, to_columns, self.primary_property, self.to_property, override_format='str'):
142
103
  validated_csv_to_labels = lm.validate_labels(self.contents.get_column_values_list(this_row, to_label_columns))
143
- inline_to_labels, inline_to_where = self.get_inline_match_labels(to_ref, to_node.match_labels)
144
- to_labels = lm.sort_relationship_labels(self.required_labels + self.to_required_labels, validated_csv_to_labels + inline_to_labels)
104
+ to_labels = lm.sort_relationship_labels(self.required_labels + self.to_required_labels, validated_csv_to_labels)
105
+ to_node_labels = lm.merge_node_labels(to_labels, to_node.labels)
145
106
 
146
107
  # Build a MERGE query for the relationship(s)
147
108
  for relationship in relationships:
@@ -151,16 +112,9 @@ class RelationshipFileProcessor:
151
112
  time_now = amu.get_formatted_time_now()
152
113
  query_text = (QueryBuilder()
153
114
  .match()
154
- .node(labels=from_labels, ref_name=from_ref, properties=from_node)
115
+ .node(labels=from_node_labels, ref_name=from_ref, properties=from_node)
155
116
  .match()
156
- .node(labels=to_labels, ref_name=to_ref, properties=to_node)
157
- )
158
-
159
- where_literals = [i for i in [inline_from_where, inline_to_where] if i]
160
- if where_literals:
161
- query_text = query_text.where_literal(' AND '.join(where_literals))
162
-
163
- query_text = (query_text
117
+ .node(labels=to_node_labels, ref_name=to_ref, properties=to_node)
164
118
  .merge()
165
119
  .node(ref_name=from_ref)
166
120
  .related_to(label=relation, ref_name=relation_ref)
@@ -182,7 +136,7 @@ class RelationshipFileProcessor:
182
136
  query_list = self.query_manager.parameterise(query_text, self.section)
183
137
 
184
138
  for a_query in query_list:
185
- query = Neo4jQuery('node', a_query, time_now)
139
+ query = Neo4jQuery('relationship', a_query, time_now)
186
140
  if self.validate_only and not self.summarise:
187
141
  print(a_query)
188
142
  queries.append(query)
@@ -243,12 +197,12 @@ class RelationshipFileProcessor:
243
197
  # If there are multiple From or To nodes, create a relationship query for each combination
244
198
  for from_node in self.contents.get_property_values_list(this_row, from_columns, self.primary_property, self.from_property, override_format='str'):
245
199
  validated_csv_from_labels = lm.validate_labels(self.contents.get_column_values_list(this_row, from_label_columns))
246
- inline_from_labels, inline_from_where = self.get_inline_match_labels(from_ref, from_node.match_labels)
247
- from_labels = lm.sort_relationship_labels(self.required_labels + self.from_required_labels, validated_csv_from_labels + inline_from_labels)
200
+ from_labels = lm.sort_relationship_labels(self.required_labels + self.from_required_labels, validated_csv_from_labels)
201
+ from_node_labels = lm.merge_node_labels(from_labels, from_node.labels)
248
202
  for to_node in self.contents.get_property_values_list(this_row, to_columns, self.primary_property, self.to_property, override_format='str'):
249
203
  validated_csv_to_labels = lm.validate_labels(self.contents.get_column_values_list(this_row, to_label_columns))
250
- inline_to_labels, inline_to_where = self.get_inline_match_labels(to_ref, to_node.match_labels)
251
- to_labels = lm.sort_relationship_labels(self.required_labels + self.to_required_labels, validated_csv_to_labels + inline_to_labels)
204
+ to_labels = lm.sort_relationship_labels(self.required_labels + self.to_required_labels, validated_csv_to_labels)
205
+ to_node_labels = lm.merge_node_labels(to_labels, to_node.labels)
252
206
 
253
207
  # Build a MERGE query for the relationship(s)
254
208
  for relationship in relationships:
@@ -264,7 +218,7 @@ class RelationshipFileProcessor:
264
218
 
265
219
  query_data_list = []
266
220
  for count in range(max(len(param_from_nodes), len(param_to_nodes), len(param_explicit_props), len(param_calc_props))):
267
- new_labels_list = [[from_labels, to_labels, relation, from_node.key, to_node.key, inline_from_where, inline_to_where, param_calc_props[min(count, len(param_calc_props) - 1)]]]
221
+ new_labels_list = [[from_node_labels, to_node_labels, relation, from_node.key, to_node.key, param_calc_props[min(count, len(param_calc_props) - 1)]]]
268
222
  query_data_list += [[param_from_nodes[min(count, len(param_from_nodes) - 1)].value.replace('\\\\n', '\n'), param_to_nodes[min(count, len(param_to_nodes) - 1)].value.replace('\\\\n', '\n'), param_explicit_props[min(count, len(param_explicit_props) - 1)], param_calc_props[min(count, len(param_calc_props) - 1)], time_now]]
269
223
 
270
224
  # So now we know all about this particular update. Let's put it in the query dictionary
@@ -295,8 +249,6 @@ class RelationshipFileProcessor:
295
249
  relationship = batch_keys[from_to_labels][2]
296
250
  from_node = batch_keys[from_to_labels][3]
297
251
  to_node = batch_keys[from_to_labels][4]
298
- from_where = batch_keys[from_to_labels][5]
299
- to_where = batch_keys[from_to_labels][6]
300
252
  batch_num = 1
301
253
  while batch_num <= num_batches:
302
254
  if batch_num == num_batches:
@@ -337,13 +289,6 @@ class RelationshipFileProcessor:
337
289
  .node(labels=from_labels, ref_name=from_ref, properties_literal=from_keys)
338
290
  .match()
339
291
  .node(labels=to_labels, ref_name=to_ref, properties_literal=to_keys)
340
- )
341
-
342
- where_literals = [i for i in [from_where, to_where] if i]
343
- if where_literals:
344
- query_text = query_text.where_literal(' AND '.join(where_literals))
345
-
346
- query_text = (query_text
347
292
  .merge()
348
293
  .node(ref_name=from_ref)
349
294
  .related_to(label=relationship, ref_name=relation_ref)
@@ -2,15 +2,20 @@ import datetime
2
2
  import messages
3
3
  import ast
4
4
  import processors.propertymanager as pm
5
+ import processors.labelmanager as lm
5
6
  from querymanager import QueryManager
6
7
 
7
8
  class Neo4jProperty():
8
9
 
9
- def __init__(self, key, value = None, format = None, type = None, blank_override = False, match_labels=''):
10
+ def __init__(self, key, value=None, format=None, type=None, blank_override=False, labels=[]):
10
11
 
11
12
  self.key = pm.validate_property(key)
12
13
  # Sanitise the value
13
14
  self.value = value.replace('\\', '\\\\').replace('\r', '\\r').replace('"', '\\"')
15
+ if labels == ['']:
16
+ self.labels = []
17
+ else:
18
+ self.labels = lm.validate_labels(labels)
14
19
 
15
20
  if self.value == "":
16
21
  if blank_override:
@@ -20,8 +25,6 @@ class Neo4jProperty():
20
25
  self.format = format
21
26
  # type is the kind of thing this is, such as ID, START_ID etc. See assetmodelutilities.py for the full list
22
27
  self.type = type
23
- # Optional inline label selector used when matching nodes from csv values such as key::value::labelA|labelB
24
- self.match_labels = match_labels
25
28
 
26
29
  # We'll format the value the first time someone wants it, so say it's not formatted yet
27
30
  self.formatted_values = {}
@@ -56,7 +59,7 @@ class Neo4jProperty():
56
59
 
57
60
  def get_value(self, ref):
58
61
  # Check to see if we have a formatted value, and if not do it now
59
- if not ref in self.formatted_values.keys():
62
+ if ref not in self.formatted_values.keys():
60
63
  self.formatted_values[ref] = format_value(self, ref)
61
64
 
62
65
  return self.formatted_values[ref]
@@ -338,6 +341,7 @@ def format(properties, property_ref='', query_manager = None, section='DEFAULT')
338
341
  return QueryManager.parameterise(query_manager, pair_data, section)
339
342
 
340
343
 
344
+
341
345
  def to_str(properties, comparison_operator: str = ':', boolean_operator: str = ',', property_ref='', key_ref='') -> str:
342
346
  pairs = [f'{key_ref}{key.split(":")[0]}{comparison_operator}{Neo4jProperty(key, str(value)).get_value(property_ref)}' for key, value in properties.items()]
343
347
  res = boolean_operator.join(pairs)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-eigen-ingenuity
3
- Version: 0.5.30b4
3
+ Version: 0.5.31
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,7 +5,7 @@ eigeningenuity/commonmenu.py,sha256=iewhtyN83fVNVXMrhhu4sd2FSLtqPrg8bSlidhvl-rc,
5
5
  eigeningenuity/elastic.py,sha256=HwHyRHLw71v6wDl1VDercCRn6m0Lrh-4RzHSQxqTTJw,7960
6
6
  eigeningenuity/events.py,sha256=zo4dO23PeNBw5bt9O_F56qHIEQw5YgRrFi3yA5hYA44,13929
7
7
  eigeningenuity/historian.py,sha256=urJzCUF3OwOlXY-FZvl0tVzi3KICfptYigmf3gIklOU,43518
8
- eigeningenuity/historianmulti.py,sha256=Q65J1XGiCfEkzTXvwnp7l9YwGNFs8sqBkdlQOcF6N4M,35934
8
+ eigeningenuity/historianmulti.py,sha256=X5TJDS7HP-w4nGt6OueJAF8gO_xAutE840oVU0rUogA,36204
9
9
  eigeningenuity/logformatter.py,sha256=Xy-fLbYp58XXerRKsswzquyke9ujbNYNEHivRLlet9w,6291
10
10
  eigeningenuity/settings.py,sha256=rnx4tzDN3yMQUfga-jdDoJCYhcCxa2lWSGfEAPiWdD0,3406
11
11
  eigeningenuity/sql.py,sha256=I3NwAeOT61Cnsr5e6QxDYCrwsVJ-0h3j0VxUA6uiyGc,6165
@@ -41,12 +41,12 @@ modelbuilder/src/assetmodelbuilder.py,sha256=92Yu9CvmObPYDdqCpn8eBCaZ_KGBhm307Ys
41
41
  modelbuilder/src/assetmodelcsvwriter.py,sha256=GKNi_fw7AlY-UG2XhwFIS34Ff3XiVRss-o5MUzyJSV0,1071
42
42
  modelbuilder/src/assetmodelutilities.py,sha256=1j-S2CKaxcde-Pj6AfgYMGOKu13kwA-sIJSIyLqMW94,6700
43
43
  modelbuilder/src/configmanager.py,sha256=Orwg_75Zk8Go_RdmFnEoKKRLJp6_2XZAtPRQZuD5Zmc,31937
44
- modelbuilder/src/csvcontentsmanager.py,sha256=25JbbbmgnebAkjr_RvItBBZXK8Cq66a4Lcea9bWqcdk,8258
44
+ modelbuilder/src/csvcontentsmanager.py,sha256=601JuaT5rxlTlj58uK50c6vSUk4NKh4pGOrVq9ECX8o,8247
45
45
  modelbuilder/src/csvwriter.py,sha256=2Xc6kdV6cYwCjrVF6WaZfS6tVp8-oc0ksIHSOx6iqj8,14132
46
- modelbuilder/src/fileanalyser.py,sha256=G9-xJK_4ccj-1TJDag7x9hCpdPpQdaJO0MWUdFuCjkU,8047
46
+ modelbuilder/src/fileanalyser.py,sha256=hNwEZLlIRRLroJCxiWXwJTQHIsHbZDWbBK4BCFIMcLw,7633
47
47
  modelbuilder/src/filemanager.py,sha256=nfRQlW-AIp8ICu1CO0MO55OyWMWDQJrW4Z8yRRhBs-k,26454
48
48
  modelbuilder/src/messages.py,sha256=6JnW-ke6nHGUA4hTEBvo_kVlNJTXoV4LWw8mNwMpBCQ,1325
49
- modelbuilder/src/property.py,sha256=W67yx-vourlFDTsAcSgJOOlb4Q0exZFWf3gbNP2blJI,11615
49
+ modelbuilder/src/property.py,sha256=lwYUuN17q1g9MHE2K2yM03ArfEPWmzRP9yxfS1tYbo8,11605
50
50
  modelbuilder/src/querymanager.py,sha256=Wr0LcY7iCwmLyeSx8LcdbQT2xt1viltp6XFvP3Bg5v8,3270
51
51
  modelbuilder/src/versionmanager.py,sha256=B8mrYY5Der0sWi1GQjduyVGZ6BuAb6rTNVAZzQlP4k4,19148
52
52
  modelbuilder/src/connectors/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -56,10 +56,10 @@ modelbuilder/src/connectors/genericconnector.py,sha256=bMfnbrOWq97BC9oM7RIA58bNd
56
56
  modelbuilder/src/connectors/httpsconnector.py,sha256=DOZyxRW3JQcaiaYtnx0_Jq2dBEhgSUIubnx5jj7OY_g,6078
57
57
  modelbuilder/src/processors/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
58
58
  modelbuilder/src/processors/cypherfileprocessor.py,sha256=EmaLsBhC6gWQwvhyY7Ks2HEbGEzDoGAZfu2nBkh2hOs,2941
59
- modelbuilder/src/processors/labelmanager.py,sha256=b2xkIqMd2hptplm5Sp10zoc7LGOKTVZH2jDKN7brvYU,6619
60
- modelbuilder/src/processors/nodefileprocessor.py,sha256=8D93Yy9HsOGMtbOnsodjgqGLGkoI0AC31PdxamnDjqA,15338
59
+ modelbuilder/src/processors/labelmanager.py,sha256=W57GcDeCANwgWlp7uBWq0PusKDMixFEv79eBhV7LKfU,6833
60
+ modelbuilder/src/processors/nodefileprocessor.py,sha256=DLzJzsl4APjX8CsKyZY7GRNtr0rJcteFi0TsdM4hAXI,14747
61
61
  modelbuilder/src/processors/propertymanager.py,sha256=zLr8S0HPZMXeUp1RUzVXWyNa64MxLufXrOqh5uL1mwU,6978
62
- modelbuilder/src/processors/relationshipfileprocessor.py,sha256=OvY5Lp0RcH9MhCCErCaAKZECwMeFH5tiFF8Y9XrdakQ,22342
62
+ modelbuilder/src/processors/relationshipfileprocessor.py,sha256=e0YewiXMZRRFs-wl-vl7VDPI06xEoltHXHHk1SOSRuk,19515
63
63
  modelbuilder/src/processors/relationshipmanager.py,sha256=lDtE_5AdKzL3boq7VD8Gmpai8Uscq79vRxkzYQL8A9A,1105
64
64
  modelbuilder/src/queries/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
65
65
  modelbuilder/src/queries/cypherbuilder.py,sha256=VpUGuPo-Ba3skjCVBFjmxm4ORQBGgF5cDiQYnK67hLA,10418
@@ -88,8 +88,8 @@ regressiontests/eigeningenuity/historian-multi/test_getRawDatapoints.py,sha256=f
88
88
  regressiontests/eigeningenuity/historian-multi/test_listDataTags.py,sha256=TcceNSjCKoiK5SJcgTH2JXfKLYxIHdQdwZWlkpGnEVM,2006
89
89
  regressiontests/eigeningenuity/historian-multi/test_tagManagement.py,sha256=ylInBt453d1RaSih1eTTxGPZmb60UK4vMwI3UW-U1JY,4830
90
90
  regressiontests/eigeningenuity/historian-multi/test_writePoints.py,sha256=51tfUSLUqLKcCKJ1EyhjfzoC_4OP6n1oL3zgTSkXu4s,2696
91
- python_eigen_ingenuity-0.5.30b4.dist-info/METADATA,sha256=N50odrp3h5iJE7p6uIPKboyYQ7xd7pY8VaG7BqjLjME,8124
92
- python_eigen_ingenuity-0.5.30b4.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
93
- python_eigen_ingenuity-0.5.30b4.dist-info/entry_points.txt,sha256=G3LjFQX5xKaN4mqtqCL8uaC-gRbP5T5x9r0gBTJTXXA,70
94
- python_eigen_ingenuity-0.5.30b4.dist-info/top_level.txt,sha256=oDWOSmlNPKNBlIEKP8_JaV01O60jTcUIt2tDkq3OD18,56
95
- python_eigen_ingenuity-0.5.30b4.dist-info/RECORD,,
91
+ python_eigen_ingenuity-0.5.31.dist-info/METADATA,sha256=KcA1Hz-qUxkAzYcOx9rsMJzJ5GTnT0_YCed9OKwYUj0,8122
92
+ python_eigen_ingenuity-0.5.31.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
93
+ python_eigen_ingenuity-0.5.31.dist-info/entry_points.txt,sha256=G3LjFQX5xKaN4mqtqCL8uaC-gRbP5T5x9r0gBTJTXXA,70
94
+ python_eigen_ingenuity-0.5.31.dist-info/top_level.txt,sha256=oDWOSmlNPKNBlIEKP8_JaV01O60jTcUIt2tDkq3OD18,56
95
+ python_eigen_ingenuity-0.5.31.dist-info/RECORD,,