-
Notifications
You must be signed in to change notification settings - Fork 8
/
model.py
2594 lines (2249 loc) · 107 KB
/
model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import copy
import importlib
import threading
import time
import logging
import pytz
#for tables
import numpy
import numpy as np
import datetime
import dateutil.parser
import sys
import os
import uuid
import modeltemplates
"""
next Todo
-
- execute: problem im thread mit der Ausführung
- code documentation
- google document
-
"""
sys.path.append("./plugins") #for the importlib loader, doesn't understand relative paths
myGlobalDir = os.path.dirname(os.path.realpath(__file__)) # holds the directory of this script
def date2secs(value):
""" converts a date with timezone into float seconds since epoch
Args:
value: the date given as either a string or a datetime object
Returns:
the seconds since epoch or the original value of not convertibel
"""
if type(value) == type(datetime.datetime(1970, 1, 1, 0, 0)):
timeDelta = value - datetime.datetime(1970, 1, 1, 0, 0,tzinfo=pytz.UTC)
return timeDelta.total_seconds()
elif type(value) is str:
#try a string parser
try:
date = dateutil.parser.parse(value)
timeDelta = date - datetime.datetime(1970, 1, 1, 0, 0,tzinfo=pytz.UTC)
return timeDelta.total_seconds()
except:
return value
else:
return value
def date2msecs(value):
"""
converst a timestamp in to ms since epoch
"""
return date2secs(value)*1000
def secs2date(epoch):
""" converts float seconds since epoch into datetime object with UTC timezone """
return datetime.datetime(1970, 1, 1, 0, 0,tzinfo=pytz.UTC) + datetime.timedelta(seconds=epoch)
def secs2dateString(epoch):
""" converts seconds since epoch into a datetime iso string format 2009-06-30T18:30:00.123456+02:00 """
try:
stri = secs2date(epoch).isoformat()
return stri
except:
return None
class Table():
#accept columnNames as list of strings for the names of the columns
def __init__(self,columnNames=[]):
self.__init_logger(logging.DEBUG)
if type(columnNames)==type(dict()):
columnNames = list(columnNames.keys())
#self.columnNames = columnNames
self.data = None # data is a list (each element is a row of the data)
self.meta ={} # to store some meta information
self.meta["columnNames"] = columnNames
pass
def __init_logger(self,level):
self.logger = logging.getLogger("Table()")
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
handler.setFormatter(formatter)
self.logger.addHandler(handler)
self.logger.setLevel(level)
def get_meta_information(self):
return self.meta
def get_column_names_dict(self):
namesDict = {}
for name in self.meta["columnNames"]:
namesDict[name]=""
return namesDict
def get_number_of_rows(self):
return len(self.data)
def update_meta(self,updateDict={}):
return copy.deepcopy(self.meta.update(updateDict))
# exist already, replace, else enlarge table
def write_column(self,columnName,values):
pass
def __get_current_rows(self):
pass
#accept dict or list in right order
def add_row(self,row):
vector = []
if type(row)==type(dict()):
#make correct order first
for name in self.meta["columnNames"]:
vector.append(row[name])
elif type(row) == list (list()):
pass # this is what we expect
else:
print("wrong input type to table")
return False
entry = numpy.asarray(vector, dtype="float64")
if self.data == None:
self.data = [entry] # first entry
else:
self.data.append(entry)
return True
#returns a value table, including postprocessing
def get_value_table(self,variables,startTime=None,endTime=None,noBins=None,agg="sample",includeTimeStamps=None):
if 0:#startTime==None and endTime==None and noBins==None:
try:
table = numpy.stack(self.data,axis=0)
return table.T
except:
return None
else:
self.logger.info("query with processing")
#check the start and end times
timeIndex = self.__get_column_index(self.get_meta_information()["timeId"])
startTimeOfTable = self.data[0][timeIndex]
endTimeOfTable = self.data[-1][timeIndex]
if startTime == None:
queryStart = startTimeOfTable
else:
queryStart = date2secs(startTime)
if endTime == None:
queryEnd = endTimeOfTable
else:
queryEnd = date2secs(endTime)
#check sanity of interval
if queryStart < startTimeOfTable :
self.logger.warn("start time query before table start")
return None
if queryEnd > endTimeOfTable:
self.logger.warn("end time of query after table end")
return None
print("hier2")
#now iterate over the variables and aggregate them
if agg == "sample":
#here, we pick some data out
startRow = self.__get_row_index_from_time(queryStart)
endRow = self.__get_row_index_from_time(queryEnd)
totalRows = endRow-startRow+1
if noBins == None:
rowStep = 1
noBins = totalRows
else:
rowStep = float(totalRows) / float(noBins)
currentRow = startRow
result = []
variablesIndices = [] # holding the list of variables as indices in our table
for var in variables:
variablesIndices.append(self.__get_column_index(var))
if includeTimeStamps:
variablesIndices.append(self.__get_column_index(self.get_meta_information()["timeId"]))
for i in range(noBins):
currentRowIndex = int(startRow + float(i)*rowStep)
pickRow = self.data[currentRowIndex]
#now select only the wanted indices
reducedRow = [pickRow[i] for i in variablesIndices]
#now select only the wanted variables
result.append(reducedRow)
table = numpy.stack(result,axis=0)
return table.T
else:
#other aggrataion not supported
return None
#return the column index of a given nodeId
def __get_column_index(self,nodeId):
if nodeId not in self.meta["columnNames"]:
return None
return self.meta["columnNames"].index(nodeId)
def __get_row_index_from_time(self,searchTime):
timeIndex = self.__get_time_index()
index = 0
for row in self.data:
if row[timeIndex]>searchTime:
if index>0:
index -= 1
return index
if row[timeIndex]==searchTime:
return index
index += 1
return None
def __get_time_index(self):
return self.__get_column_index(self.get_meta_information()["timeId"])
def save(self,fileName):
numpytable = self.get_value_table()
numpy.save(fileName, numpytable)
keyfile = open(fileName+ ".meta.json", "w")
keyfile.write(json.dumps(self.get_meta_information(), indent=4))
keyfile.close()
def load(self,fileName):
try:
f = open(fileName+ ".meta.json", "r")
self.meta = json.loads(f.read())
f.close()
self.data = numpy.load(fileName + ".npy")
return True
except:
print("table: problem loading",fileName,sys.exc_info()[1])
return False
class TimeSeriesTables():
def __init__(self):
self.tables=[]
self.__init_logger(logging.DEBUG)
pass
def __init_logger(self,level):
self.logger = logging.getLogger("TimeSeriesTables")
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
handler.setFormatter(formatter)
self.logger.addHandler(handler)
self.logger.setLevel(level)
# row is a dict with all variables, try to find a matching table, if not, create a new one
def __get_table(self,row,timeId=None):
workTable = None
for table in self.tables:
if table.get_column_names_dict().keys()==row.keys():
#this is the right table
workTable = table
break
if not workTable:
#haven't found it, make new table
workTable = Table(row)
if timeId:
workTable.update_meta({"timeId":timeId})
self.tables.append(workTable)
return workTable
# find to which table the variable belongs
# the desc param can be a browsepath or be a list of
# the table can only be found if all of the variables are in the same table
def __find_table(self,desc):
if type(desc)==type(str()):
for table in self.tables:
if desc in table.get_column_names_dict():
return table
return None
elif type(desc) == type(list()):
lastTable = None
for key in desc:
if not lastTable:
lastTable = self.__find_table(key)
else:
nowTable = self.__find_table(key)
if nowTable != lastTable:
return None
return lastTable
#get the number of rows of the table to which this id belongs
def get_number_of_rows(self,desc):
workTable = self.__find_table(desc)
if workTable:
return workTable.get_number_of_rows()
else:
return None
#the row is dict containing "name":value and one "time":"2018-01-05T...."
# here, we will also convert all types
def add_row(self,row):
#first check if the row contains the time
timeId= None
for key in row:
value = row[key]
if type(value) == type(datetime.datetime(1,1,1,1,1)):
date2secs(value)
#timeDelta = value-datetime.datetime (1970,1 , 1, 0, 0)
row[key]=date2secs(value)
timeId = key
#now find the right table
workTable = self.__get_table(row,timeId=timeId)
return workTable.add_row(row)
#params: variables is an ordered list
def get_value_table(self,variables,startTime=None,endTime=None,noBins=100,agg="sample",includeTimeStamps = None):
workTable = self.__find_table(variables)
if not workTable: return None
return workTable.get_value_table(variables, startTime=startTime, endTime=endTime, noBins=noBins, agg=agg, includeTimeStamps=includeTimeStamps)
'''
if not startTime and not endTime:
#get full table
return workTable.get_value_table(variables,startTime=startTime, endTime=endTime, noBins=noBins, agg=agg)
else:
return workTable.get_value_table(variables, startTime=startTime, endTime=endTime, noBins=noBins, agg=agg)
'''
def save(self,fileName):
index = 0
for table in self.tables:
table.save(fileName+".table_"+str(index))
index +=1
def load(self,fileName):
index = 0
running = True
#delete all existing tables
self.tables=[]
while running:
#load the keys and the data
try:
newTable = Table()
if not newTable.load(fileName+".table_"+str(index)):
break
self.tables.append(newTable)
index+=1
except:
print("not found, index",index)
#used as an OOP wrapper for the flat and procedural style of the model class
class Node():
""" used as an OOP wrapper for the flat and procedural style of the model class
it is a convenient way to access nodes and their hierarchy and internals
"""
def __init__(self,myModel,myId):
""" a node can be created by calling the
mynode = model.get_node("root.mynode") or
mynode = Node(mymodel,"123")
Returns:
a node object for further access to values, hierarchy etc.
"""
self.model = myModel # this is not a copy!!
self.id = myId
def get_value(self):
""" Returns:
the "value" property of the node
None if node has no "value"
"""
return self.model.get_value(self.id)
def set_value(self,value):
return self.model.set_value(self.id,value)
def get_parent(self):
""" Returns:
a Node()-instance of the parent of the current node,
None if no parent available
"""
nodeInfo = self.model.get_node_info(self.id)
if nodeInfo:
return self.model.get_node(nodeInfo["parent"])
else:
return None
def get_child(self,childName):
""" Returns:
a Node() instance of the child holding the childName
None if the current node does not have a child with the name childName
"""
nodeInfo = self.model.get_node_info(self.id)
if nodeInfo:
for childId in nodeInfo['children']:
childInfo = self.model.get_node_info(childId)
if childInfo["name"] == childName:
return self.model.get_node(childId)
return None
def get_children(self):
""" Returns:
a list of Node()-objects which are the children of the current node
"""
nodeInfo = self.model.get_node_info(self.id)
children=[]
for childId in nodeInfo['children']:
children.append(self.model.get_node(childId))
return children
def get_properties(self):
""" Returns:
a dictionary holding the properties of the node like {"value":123,"name":"myVariable","children":...}
"""
nodeInfo = self.model.get_node_info(self.id)
return copy.deepcopy(nodeInfo)
def get_property(self,property):
"""
Args:
property: the property name asked for
Returns:
the value of the property behind the property given
None if the property does not exist
"""
nodeDict =self.get_properties()
if property in nodeDict:
return self.get_properties()[property]
else:
return None
def get_model(self):
""" this function should only be used for testing, we should never be in the need to access the model inside
Returns:
the underlying model of type Model() class
"""
return self.model
def get_leaves(self):
""" this function returns a list of Nodes containing the leaves where this referencer points to
this functions works only for nodes of type "referencer", as we are following the forward references
leaves are defined as following:
1) all nodes that are listed under the forward references and which are not of type referencer or folder
2) if nodes pointed to are referencer, the targets are again analyzed
3) if a node pointed to is a folder, all children of the folder are taken which are not referencer or folder themselves
folders and referencers inside the folder are not taken into account
doing so, hierarchies of referencers are unlimited, hierarchies of folders are only of depth 1
Returns:
all nodes which are considered leaves as a list of Node() objects
"""
leaves = self.model.get_leaves(self.id) # a list of node dicts
leaveNodes = []
for leave in leaves:
leaveNodes.append(Node(self.model,leave["id"]))
return leaveNodes
def get_id(self):
""" Returns: the nodeid (which is generated by the system) """
return self.id
def get_browse_path(self):
""" Returns: the browsepath along the style "root.myfolder.myvariable..." """
return self.model.get_browse_path(self.id)
def get_name(self):
""" Returns: the name of the node without the path """
return self.model.get_node_info(self.id)["name"]
def get_table_time_node(self):
""" if the current node belongs to a table, then we can get the time node
a node
Returns:
(obj Node()) the node of type
"""
timeNode = self.model.find_table_time_node(self.id)
if timeNode:
return Node(self.model,timeNode)
else:
return None
def get_time_indices(self,startTime,endTime):
""" works only for "column" nodes, it looks to find the timeField node of the table to which the node belongs
then tries to find start and end time inside the timeField column and returns the index (rownumber) which are
INSIDE the given startTime, endTime
Args:
startTime: the startTime to look up ,supported formats: epoch seconds, datetime object, iso string
endTime: the startTime to look up ,supported formats: epoch seconds, datetime object, iso string
Returns:
(numpy array) indexnumbers containing the rows of the table that fall inside the given [startTime, endTime] intervall
None for not finding table, timeField, start-endTimes whatsoever
"""
try:
startTime = date2secs(startTime)
endTime = date2secs(endTime)
times = numpy.asarray(self.get_value())
indices = numpy.where((times >= startTime) & (times <= endTime))[0]
return indices
except:
return None
class Model():
nodeTemplate = {"id": None, "name": None, "type": "folder", "parent": None, "children": [], "backRefs": [],"forwardRefs":[],"value":None}
def __init__(self):
"""
initialize an empty Model object, it will contain the root Node as folder with Id "0"
during the initialization, also the plug-ins (all files in the ./plugin) are loaded:
all templates and functions are imported
a model holds all modelling information and data to work on
"""
self.model = {"1":{"name":"root","type":"folder","children":[],"parent":"0","id":"1","backRefs":[],"forwardRefs":[]}}
self.__init_logger(logging.DEBUG)
self.globalIdCounter=1 # increased on every creation of a node, it holds the last inserted node id
self.timeSeriesTables = TimeSeriesTables()
self.functions={} # a dictionary holding all functions from ./plugins
self.templates={} # holding all templates from ./plugins
self.lock = threading.RLock()
self.import_plugins()
self.differentialHandles ={} # containing handle:model_copy entries to support differential queries
self.currentModelName = "emptyModel" # the current name of the model
def __init_logger(self, level):
"""setup the logger object"""
self.logger = logging.getLogger("Table()")
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
handler.setFormatter(formatter)
self.logger.addHandler(handler)
self.logger.setLevel(level)
def __get_id(self, id):
"""
Args:
id (string): give a browsepath ("root.myfolder.myvariable") or a nodeId ("10")
Returns:
(string): the node id as string
None if not found
"""
if id in self.model:
return id
#maybe a browsepath?
try:
names = id.split('.')
if names[0]=="root":
names = names[1:]
except:
return None
#now we start at root
actualSearchId = "1"
for name in names:
nextSearchId = None
for childId in self.model[actualSearchId]["children"]:
if self.model[childId]["name"] == name:
#this is a match
nextSearchId = childId
break
if not nextSearchId:
return None
#we found it, go deeper now
actualSearchId = nextSearchId
return actualSearchId
def get_node(self,desc):
""" instantiate a Node() object on the node given as desc
Args:
desc (string): give a browsepath ("root.myfolder.myvariable") or a nodeId ("10")
Returns:
(Node()): a node object of the given node
None if not found
"""
with self.lock:
id = self.__get_id(desc)
if id:
return Node(self,id)
def get_node_info(self,desc):
"""
Args:
desc (string): give a browsepath ("root.myfolder.myvariable") or a nodeId ("10")
Returns:
(dict): a dictionary holding all properties of the node includin references and children
"""
with self.lock:
id = self.__get_id(desc)
if not id: return None
return copy.deepcopy(self.model[id])
def get_node_with_children(self,desc):
""" retrieve node information including children of the first level
Args:
desc (string): give a browsepath ("root.myfolder.myvariable") or a nodeId ("10")
Returns:
(Node()): a node object of the given node
None if not found
"""
with self.lock:
id = self.__get_id(desc)
if not id: return None
response = copy.deepcopy(self.model[id])
if response["children"]!=[]:
children =[]
for childId in response["children"]:
children.append(copy.deepcopy(self.model[childId]))
response["children"]=children
return response
def get_models(self):
"""
get the available model files from the disk under /models
: Returns: a list of strings
"""
try:
mydir = myGlobalDir
os.chdir(mydir) # to enable import easily
files = os.listdir(mydir + '/models')
# take only the ones with '.json, but cut the '.model.json' extension
models = [f.split('.model')[0] for f in files if f.endswith(".json")]
return models
except Exception as ex:
self.logger.error("Model.get_models() failed "+str(ex))
return []
def get_info(self):
"""
get some information about the model
Returns: (dict) key value pairs on information of the model,
"""
return {"name":self.currentModelName}
def import_plugins(self):
""" find all plugins (= all .py files in the ./plugin folder
take from there the templates from the files and the functions
this function is execution on startup of the model
"""
#mydir =os.path.dirname(os.path.realpath(__file__))
mydir = myGlobalDir
os.chdir(mydir)#to enable import easily
sys.path.append(mydir+'/plugins') # for the importlib to find the stuff
plugins = os.listdir(mydir+'/plugins')
for fileName in plugins:
if fileName.startswith('__'):
continue # avoid __pycache__ things
moduleName = fileName[:-3]
module = importlib.import_module(moduleName)
#now analyze all objects in the module
for objName in dir(module):
if objName.startswith('__'):
continue # these are python generated info objects, we don't want them
element = getattr(module,objName)
if type(element ) is dict:
#this is a template information
self.templates[moduleName+"."+objName]=copy.deepcopy(element)
elif callable(element):
#this is a function, get more info
newFunction = {"module":module,"function":element}
self.functions[moduleName+"."+objName]=newFunction
def get_id(self,ids):
""" convert a descriptor or a list into only ids (which can be used as entry to the model dictionary
Args:
ids (string, list(string)): a single or list of strings containing either and id ("101") or browsepath ("root.myfolder.myvar")
Returns:
a list(id) or id as string
"""
with self.lock:
if type(ids) == type(list()):
newList = []
for id in ids:
newList.append(self.__get_id(id))
return newList
elif type(ids) == type(dict()):
newDict = {}
for oldId in ids:
id = self.__get_id(oldId)
newDict[id]=ids[oldId] #also copy the value
return newDict
else:
#assume its scalar
return self.__get_id(ids)
def get_browse_path(self,desc):
"""
Args:
desc(string): a node id or browsepatch
Returns:
(string) a browsepath
"""
with self.lock:
id = self.get_id(desc)
if not id in self.model:
return None
path = self.model[id]["name"]
while 1:
id = self.model[id]["parent"]
if id =="0":
break
else:
path = self.model[id]["name"]+"."+path
return path
def create_node(self,parent="root",type="folder",value=None,name="newNode",properties={}):
"""
create a node inside the model by giving several infos
Args:
parent: a descriptor (browsepath or id) of the parent
type: the type of the node
value: (optional) give a value for the node
name(string): a name of the node, must be unique under the parent
properties (dict): a dictionary containing further key-values to be placed into the node as properties
Returns:
(string) nodeid,
None for problem durinf creation
"""
#check if parent exists
with self.lock:
parentId = self.get_id(parent)
if not parentId:
return None
#check if same name existst already
newpath = self.get_browse_path(parent)+"."+name
if self.get_id(newpath):
#we found it, it exists alreay, so we can't create it
return None
#we can create this node
self.globalIdCounter+=1
newId = str(self.globalIdCounter)
newNode = copy.deepcopy(self.nodeTemplate)
newNode.update({"id":newId,"name":name,"type":type,"parent":parentId})
if properties !={}:
newNode.update(properties)
if value != None:
newNode["value"]=value
self.model[parentId]["children"].append(newId)
self.model[newId]=newNode
return newNode["id"]
def create_node_from_path(self,path,properties={"type":"variable"}):
"""
create a node from a path given, all intermediate nodes of th path given that do not yet exist are also created as folder type
Args:
path(string): the path to the node to be creates
properties(dict): the properties of the node
example:
create_node_from_path("root.myfolder.something.thisvar")
this will create myfolder as folder, something as folder, thisvar as variable and will also
set all hierarchies correctly
Returns:
(string) the nodeid created or
None if problem during creation
"""
currentNode = "root" #root
with self.lock:
for node in path.split('.')[1:-1]:
if not self.__get_id(currentNode+'.'+node):
#this one does not exist, so make it
self.create_node(currentNode,name=node)
currentNode += '.'+node
return self.create_node(parent=currentNode,name=path.split('.')[-1],properties=properties)
def create_nodes_from_template(self,parent="root",template=[]):
"""
deprecated!! this is the old style of templates as lists, now it's a dict
Create a node from a template; a template is a list of node-dicts,
Args:
parent(string): descriptor of the parent node under which the nodes of the template should be created
template: a list of node dicts of the nodes to be creates, children are allowed as dict
Returns:
(boolenan) True for created, False for error
Example:
create_nodes_from_template(parent="root.myfolder",[{"name":"myvariable1","type":"variable"},
{"name":"myfolder","type":"folder","children":[
{"name":"mysubvar","type":"variable"}]])
"""
with self.lock:
parentId = self.get_id(parent)
if not parentId:
return False
newNodeIds = [] #these must be corrected later
for node in template:
#we take all info from the nodes and insert it into the tree
nodeName = node["name"]
newNodeId = self.create_node(parentId,name=nodeName,properties=node)
newNodeIds.append(newNodeId)
#do we have "children per template syntax"?, then remove that property from the nodes and make more nodes
if "children" in self.model[newNodeId]:
savedChildren = copy.deepcopy(self.model[newNodeId]["children"])
self.model[newNodeId]["children"]=[] # empty out
for child in savedChildren:
newChildId = self.create_node(newNodeId,name=child["name"],properties=child)
newNodeIds.append(newChildId)
#now correct missing stuff
for nodeId in newNodeIds:
if self.model[nodeId]["type"]== "referencer":
# convert the path of references into an id: get the parent path, add the tail, convert to id
forwardReferences =self.model[nodeId]["forwardRefs"] #make a copy, we'll delete this
self.model[nodeId]["forwardRefs"]=[]
parentPath = self.get_browse_path(self.model[nodeId]["parent"])
for forwardRef in forwardReferences:
forwardPath = parentPath+forwardRef
self.add_forward_refs(nodeId,[forwardPath])
return True
def __create_nodes_from_path_with_children(self,parentPath,nodes):
"""
recursive helper function for create_template_from_path
e build all nodes under the parentPath on this level and then the children
we return a list of all created node ids
"""
createdNodes = []
for node in nodes:
newModelNode = {}
for k, v in node.items():
if k not in ["children", "parent", "id", "browsePath"]: # avoid stupid things
newModelNode[k] = v
newId = self.create_node_from_path(parentPath+'.'+newModelNode["name"],newModelNode)
if newId:
createdNodes.append(newId)
if "children" in node:
createdNodes.extend(self.__create_nodes_from_path_with_children(parentPath+'.'+newModelNode["name"],node["children"]))
return createdNodes
def create_template_from_path(self,path,template):
"""
Create a template from a path given, the template contains one or more nodes
the path must not yet exist!
Args:
path(string): the path under which the template will be placed. the template always contains
a root node, this will be renamed according to the path
Returns:
(boolenan) True for created, False for error
"""
with self.lock:
#first create the template root node
#we rename the template according to the path requested
template["name"]=path.split('.')[-1]
parentPath = '.'.join(path.split('.')[:-1])
newNodeIds = self.__create_nodes_from_path_with_children(parentPath,[template])
print(newNodeIds)
#now adjust the references
for newNodeId in newNodeIds:
if "references" in self.model[newNodeId]:
#we must create forward references
for ref in self.model[newNodeId]["references"]:
# the given path is of the form templatename.levelone.leveltwo inside the template
# we replace the "templatename" with the path name the template was given
targetPath = parentPath+'.'+template['name']+'.'+'.'.join(ref.split('.')[1:])
self.add_forward_refs(newNodeId,[targetPath])
del self.model[newNodeId]["references"] # we remove the reference information from the template
def get_templates(self):
"""
give all templates loaded
Returns: a dict with entries containing the full templates
"""
with self.lock:
return copy.deepcopy(self.templates)
def add_forward_refs(self,referencerDesc,targets):
"""
adding forward references from a referencer to other nodes, the forward references are appended at the list
of forward references of the referencer node
references to oneself are not allowed
Args:
referenderDesc (string): descriptor of the referencer node from which we want to add forward references
targets (list(descriptors)): listof node descriptors to which we want to add forward refs
Returns:
True/False for success
"""
with self.lock:
fromId = self.get_id(referencerDesc)
if not fromId:
self.logger.error("can't set forward ref on ",referencerDesc)
return False
if not self.model[fromId]["type"]=="referencer":
self.logger.error("can't set forward ref on ", referencerDesc, "is not type referencer, is type",self.model[fromId]["type"])
return False
for target in targets:
toId = self.get_id(target)
if not toId:
continue
if toId == fromId:
continue
self.model[toId]["backRefs"].append(fromId)
self.model[fromId]["forwardRefs"].append(toId)
return True
def get_model(self):
"""
Returns: the full deepcopy of the internal model object (list of dictionaries of the nodes)
"""
with self.lock:
#also add the browsepath to all nodes
for nodeid in self.model:
self.model[nodeid]["browsePath"]=self.get_browse_path(nodeid)
return copy.deepcopy(self.model)
def get_model_for_web(self):
"""
Returns: the full deepcopy of the internal model object (list of dictionaries of the nodes)
but leaving out the column values (this can be a lot of data)
and the file values (files are binary or strings with big size, typically serialized ML-models)
"""
model = {}
with self.lock:
for nodeId, nodeDict in self.model.items():
if nodeDict["type"] in ["column","file"]:
# with columns we filter out the values
node = {}
for nk, nv in nodeDict.items():
if nk == "value":
try:
node[nk] = "len " + str(len(nv))
except:
node[nk] = "None"
else:
node[nk] = copy.deepcopy(nv) # values can be list, dict and deeper objects
model[nodeId] = node
else:
#this node is not a colum, can still hold huge data
model[nodeId] = copy.deepcopy(nodeDict) # values can be list, dict and deeper objects nodeDict
model[nodeId]["browsePath"] = self.get_browse_path(nodeId) #also add the browsepath
return model
def remove_forward_refs(self,sourceDesc,targetDescriptors = []):
"""
remove forward references from a referencer, this also removes the backreference from the target
Args:
sourceDesc: the descriptor of the referencer node
targets: a list of descriptors, if missing we delete all
Returns:
True/False for success
"""
with self.lock:
fromId = self.get_id(sourceDesc)
if not fromId:
return False
if not self.model[fromId]["type"] == "referencer":
return False # only for referencers
if targetDescriptors == []:
targets = self.model[fromId]["forwardRefs"].copy()
else:
targets = self.get_id(targetDescriptors)
for toId in targets:
if not toId:
continue # we skip Nones coming from the get_id
self.model[fromId]["forwardRefs"].remove(toId)
self.model[toId]["backRefs"].remove(fromId)