-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.py
executable file
·3299 lines (2977 loc) · 147 KB
/
models.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
from persistent.mapping import PersistentMapping
PM = PersistentMapping
from persistent.list import PersistentList
PL = PersistentList
from collections import OrderedDict as OD
import models as models
import re, logging, uuid, copy, json
import transaction
import ipdb
import math
#dynamic data sets
from datetime import datetime
import requests
def isalambda(v):
LAMBDA = lambda:0
return isinstance(v, type(LAMBDA)) and v.__name__ == LAMBDA.__name__
def getAddressOrDefault(dict, fieldAddress):
if fieldAddress in dict:
return dict[fieldAddress]
elif "__default" in dict:
return dict['__default']
else:
return None
import re
def camelCase(toConvert):
# try:
# ipdb.set_trace()
toReturn = ""
step1 = re.sub("[^\w]", "", toConvert.title())
#step1 = toConvert.title().replace(" ", "")
if len(step1) > 0:
toReturn = step1[0].lower()
if len(step1) > 1:
toReturn += step1[1:]#
return toReturn
# except:
# ipdb.set_trace()
def traverse(obj, *params):
# ipdb.set_trace()
paramIndex = 0
while paramIndex < len(params):
defaultValue = params[paramIndex]
name = params[paramIndex+1]
paramIndex += 2
if name not in obj:
obj[name] = defaultValue
if paramIndex == len(params) and params[paramIndex -1] == True:
return obj
else:
obj = obj[name]
return obj
def traverseNames(obj, defaultClass, names):
for name in names:
if name not in obj:
obj[name] = defaultClass()
obj = obj[name]
return obj
#Base Class for all collections includes UUID and getList and getDict functions
# which create a dict or list if none such exists already
class Node(PersistentMapping):
def __init__(self, **kwargs):
super(Node, self).__init__()
#self['context'] = PersistentMapping()
self['uuid'] = uuid.uuid4().hex
self.update(kwargs)
def getList(self, name):
if not name in self:
self[name] = PersistentList()
return self[name]
def getDict(self, name):
if not name in self:
self[name] = PersistentMapping()
return self[name]
def getNode(self, name):
if not name in self:
self[name] = Node()
return self[name]
def getByDefault(self, defaultValue, name):
if not name in self:
self[name] = defaultValue
return self['name']
def getValue(self, name, defaultValue):
if name not in self:
self[name] = defaultValue
return self[name]
def __str__(self):
#print type(self)
if "name" in self:
return self['name']
else:
return str(self.__dict__)
def __repr__(self):
return self.__str__()
#just a container for ModelClass objects
# PersistentMapping is from the Object Persistence mechanism. Makes a python
# dictionary which is directly persistable inside Data.fs
class ModelClasses(PersistentMapping):
pass
#no idea
class ModelFields(Node):
pass
#placeToRecordExternalDatasetUpdateTimings
class DynamicDataSets(Node):
pass
class Users(Node):
pass
class User(Node):
pass
class VoteCount(Node):
pass
class Title(Node):
def getIdentifier():
if "identifier" not in self:
step1 = self.title.title().replace(" ", "")
identifier = step1[0].lower() + step1[1:]
self['identifier'] = identifier
return self['identifier']
class Vote(Node):
def __init__(self, **kwargs):
super(Vote, self).__init__(kwargs)
def addTo(election, data):
election['votes'].append(self);
class Party(Title):
def __init__(self, **kwargs):
super(Title, self).__init__(kwargs)
def addTo(election, data):
election['parties'].append(self);
class Constituency(Title):
pass
class Region(Title):
pass
class ScottishParliamentaryElection(Node):
def __init__(self, **kwargs):
super(ScottishParliamentaryElection, self).__init__()
self.update(kwargs)
def getSwingTarget(self, swingString):
target = self
for swingStep in swingString.split("."):
target = self.getNode(swingStep)
return target
def getSwing(self, swingAddress):
target = self.getSwingTarget(constituencyAddress)
return target['value']
def addSwing(self, swingAddress, percent):
target = self.getSwingTarget(swingAddress)
target.value = percent
def runConstituencyVote(self):
# ipdb.set_trace()
self['seats'] = {"constituency":{}}
parties = self['parties']['constituency']
swings = self['swings']['constituency']
national = self['2016']
for (regionName, region) in national.items():
for (constituencyName, constituency) in region.items():
# for fromParty in parties:
# for toParty in parties:
# targetList = ["national", region, constituency]
# swing = 0
# for target in targetList:
# try:
# swing += target[fromParty][toParty]['constituency']
# except:
# pass
# if not swing == 0:
# traverse(swings, {},fromParty, [], toParty).append(swing)
for fromParty in parties:
try:
baseVote = constituency[fromParty]['constituency']['baseVote']
constituency[fromParty]['constituency']['calculatedVotes'] = 0
except:
pass
for fromParty in parties:
try:
baseVote = constituency[fromParty]['constituency']['baseVote']
# traverse(constituency[fromParty]['constituency'], 0, "calculatedVotes")
constituency[fromParty]['constituency']['calculatedVotes'] += baseVote
for toParty in parties:
targetList = [constituencyName, regionName, "national"]
for target in targetList:
swingAddress = target+"."+fromParty+"."+toParty
try:
swing = swings[swingAddress]
swingVotes = int(baseVote * (min(swing, 100) / 100.0))
constituency[fromParty] ['constituency'] ['calculatedVotes'] -= swingVotes
traverse(constituency, {}, toParty, {}, 'constituency', 0, 'calculatedVotes')
constituency[toParty]['constituency']['calculatedVotes'] += swingVotes
except:
continue
except:
pass
winningVotes = -1
for party in parties:
if constituency[party]['constituency']['calculatedVotes'] > winningVotes:
winningVotes = constituency[party]['constituency']['calculatedVotes']
winningParty = party
constituency['winningParty'] = winningParty
traverse(self['seats']['constituency'], {}, winningParty, [], 'constituencies').append(constituencyName)
traverse(self['seats'], {}, 'constituency', {}, winningParty, {}, 'regions', 0, regionName)
self['seats']['constituency'][winningParty]['regions'][regionName] += 1
def runListVote(self):
# ipdb.set_trace()
self['seats']['list'] = {}
parties = self['parties']['list']
swings = self['swings']['list']
national = self['2016']
for (regionName, region) in national.items():
for (constituencyName, constituency) in region.items():
# for fromParty in parties:
# for toParty in parties:
# targetList = ["national", region, constituency]
# swing = 0
# for target in targetList:
# try:
# swing += target[fromParty][toParty]['constituency']
# except:
# pass
# if not swing == 0:
# traverse(swings, {},fromParty, [], toParty).append(swing)
for fromParty in parties:
try:
baseVote = constituency[fromParty]['constituency']['calculatedVotes']
constituency[fromParty]['list']['calculatedVotes'] = 0
except:
pass
for fromParty in parties:
try:
baseVote = constituency[fromParty]['constituency']['calculatedVotes']
# traverse(constituency[fromParty]['list'], 0, "calculatedVotes")
constituency[fromParty]['list']['calculatedVotes'] += baseVote
for toParty in parties:
targetList = [constituencyName, regionName, "national"]
for target in targetList:
swingAddress = target+"."+fromParty+"."+toParty
try:
swing = swings[swingAddress]
swingVotes = int(baseVote * (min(swing, 100) / 100.0))
constituency[fromParty] ['list'] ['calculatedVotes'] -= swingVotes
traverse(constituency, {}, toParty, {}, 'list', 0, 'calculatedVotes')
constituency[toParty]['list']['calculatedVotes'] += swingVotes
print toParty, swingVotes, constituency[toParty]['list']['calculatedVotes']
except:
continue
except:
pass
#implement dehondt voting thing
#transaction.commit()
#add up votes from constituencies
for (constituencyName, constituency) in region.items():
for party in parties:
try:
votesFromConstituency = constituency[party]['list']['calculatedVotes']
traverse(self['seats']['list'], {}, party, {}, regionName, 0, "calculatedVotes")
self['seats']['list'][party][regionName]["calculatedVotes"] += votesFromConstituency
except:
pass
for party in parties:
try:
traverse(self['seats']['list'], {}, party, {}, regionName, 0, 'calculatedSeats')
# self['seats']['list'][regionName][party]['calculatedSeats'] = self['seats']['constituency'][party]['regions'][regionName]
except:
pass
print "Region: ", regionName
for dehondtRound in range(7):
winningVotes = -1
for party in parties:
try:
constituencySeats = self['seats']['constituency'][party]['regions'][regionName]
except:
constituencySeats = 0
try:
listSeats = self['seats']['list'][party][regionName]['calculatedSeats']
except:
listSeats = 0
try:
dehondtDevisor = constituencySeats + listSeats + 1
effectiveVotes = int(self['seats']['list'][party][regionName]['calculatedVotes'] / dehondtDevisor)
print party, dehondtDevisor, effectiveVotes
if effectiveVotes > winningVotes:
winningParty = party
winningVotes = effectiveVotes
except Exception, e:
#print e
pass
print winningParty+ ": wins"
self['seats']['list'][winningParty][regionName]['calculatedSeats'] += 1
# if constituency[party]['list']['calculatedVotes'] > winningVotes:
# winningVotes = constituency[party]['constituency']['calculatedVotes']
# winningParty = party
# constituency[party]['constituency']['winningParty'] = winningParty
# traverse(self['seats']['constituency'], [], winningParty).append(constituencyName)
# ipdb.set_trace()
def calculateConstituencyVotes(self):
pass
class SwingVote(Node):
def __init__(self, **kwargs):
super(SwingVote, self).__init__(kwargs)
class DynamicDataSet(Node):
def __init__(self, **kwargs):
super(DynamicDataSet, self).__init__()
self['fieldDefinitions'] = PersistentMapping()
self['processorDefinitions'] = PersistentMapping()
self['subModelDefinitions'] = PersistentMapping()
self['svgDisplayDefDefinitions'] = PersistentMapping()
def nextTimeForUpdate(self):
for (key, item) in self.items():
#stuff about datetime
#cant be bothered
pass
def getRawData(self):
dataContainer = self
if not "getRawData" in dataContainer:
return False
toReturn = None
exec(dataContainer['getRawData'])
dataContainer['rawData'] = toReturn
def getFieldDefinitions(self):
dataContainer = self
toReturn = {}
exec(dataContainer["buildFieldDefinitions"])
dataContainer['fieldDefinitions'] = toReturn
def getSelectInputFieldColumnValues(self):
dataContainer = self
fieldColumnValues = dataContainer['selectInputFieldValues'] = Node()
for dataPoint in dataContainer['rawData']:
for columnName in dataContainer['selectInputFieldNames']:
columnValues = fieldColumnValues.getList(columnName)
columnValue = dataPoint[columnValue]
if columnValue not in columnValues:
columnValues.append(columnValue)
def buildSelectInputFields(self):
dataContainer = self
newFieldDefinitions = {}
for fieldName in self['selectInputFieldNames']:
fieldValues = list(self['selectInputFieldValues'][fieldName])
selectFieldValuesDict = {}
for fieldValue in fieldValues:
selectFieldValuesDict[fieldValue] = fieldValue
defaultValue = ""
if "__all__" in fieldValues:
defaultValue = "__all__"
newFieldDefinitions[fieldName] = \
ClassField( {"name": fieldName,
"fieldType": "select",
"defaultValue": defaultValue,
"rangeBottom": 1,
"rangeTop": 1000000,
"rangeType": "log",
"selectableValues": selectFieldValuesDict,
"unit": "arbitraryText",
"unitPrefix": "",
"unitSuffix": "",
"inputField": True,
"outputField": True,
"defaultInputField": False,
"defaultOutputField": False,
"svgComponent": None
})
self['fieldDefinitions'].update(newFieldDefinitions)
def getProcessorDefinitions(self):
dataContainer = self
toReturn = {}
exec(dataContainer["buildProcessorDefinitions"])
dataContainer['processorDefinitions'] = toReturn
def getSubModelDefinitions(self):
dataContainer = self
toReturn = {}
exec(dataContainer["buildSubModelDefinitions"])
dataContainer['subModelDefinitions'] = toReturn
def getSVGDisplayDefDefinitions(self):
dataContainer = self
toReturn = {}
exec(dataContainer['buildSVGDisplayDefDefinitions'])
dataContainer['svgDisplayDefDefinitions'] = toReturn
def updateStatic(self):
dataContainer = self
toReturn = "blankStaticLogEntry"
if not "updateStatic" in dataContainer:
self.getFieldDefinitions()
self.getProcessorDefinitions()
self.getSubModelDefinitions()
self.getSVGDisplayDefDefinitions()
toReturn = "DefaultStaticUpdate: CurrentDateTime/lazy"
else:
toReturn = None
exec(dataContainer['updateStatic'])
if "updateStaticLog" not in dataContainer:
dataContainer['updateStaticLog'] = PersistentList()
dataContainer['updateStaticLog'].append(toReturn)
def updateData(self):
dataContainer = self
toReturn = "blankDataLogEntry"
exec(dataContainer['updateData'])
if "updateDataLog" not in dataContainer:
dataContainer['updateDataLog'] = PersistentList()
dataContainer['updateDataLog'].append(toReturn)
#Stores data by UUID. This class is used to store data by ModelClass or by ModelInstance. The Node base class has a uuid created in its init method.
class ValueByInstance(Node):
def __init__(self):
super(ValueByInstance, self).__init__()
def hasData(self, key, instance):
if not key in self:
return False
if not instance['uuid'] in self[key]:
return False
return True
def getValue(self, instance, key):
return self.getDict(key)[instance['uuid']]
def setValue(self, instance, key, value):
self.getDict(key)[instance['uuid']] = value
def hasInstance(self, instance, key):
return instance['uuid'] in self.getDict(key)
def addToList(self, instance, key, value):
uuid = instance['uuid']
keyDict = self.getDict(key)
if uuid not in keyDict:
keyDict[uuid] = PersistentList()
keyDict[uuid].append(value)
return keyDict[uuid]
def clearList(self, instance, key):
uuid = instance['uuid']
keyDict = self.getDict(key)
if uuid not in keyDict:
keyDict[uuid] = PersistentList()
keyDict[uuid].clear()
return keyDict[uuid]
#BranchPath is the base class for InputSetter and OutputSetter
class BranchPath(Node):
def __init__(self, modelClass, fieldAddress, pathName):
super(BranchPath, self).__init__()
self['modelClass'] = modelClass
self['fieldAddress'] = fieldAddress
currentClass = modelClass
path = self.getList("path")
#travel along the fieldAddress, collecting the Branch objects
# you pass along the way, and record them all in self['path']
# which is a list.
for fieldName in fieldAddress:
currentBranch = currentClass['fields'][fieldName]
path.append(currentBranch)
if "subModelClass" in currentBranch:
currentClass = currentBranch['subModelClass']
def setValue(self, instance, value):
self['path'][-1]['instanceData'].setValue(instance, "fieldValue", value)
def getValue(self, instance):
return self['path'][-1]['instanceData'].getValue(instance, "fieldValue")
def __str__(self):
toReturn = "\n\nBranchPath:"
for branch in self['path']:
toReturn += "\n %s" % branch
return toReturn
def __repr__(self):
return self.__str__()
#inputSetter is used to set the currentValue of a field
# when a user changes its value
class InputSetter(BranchPath):
def __init__(self, modelClass, fieldAddress):
super(InputSetter, self).__init__(modelClass, fieldAddress, "inputSetter")
#used to read the final value from when a ProcessPath is process() ed
class OutputSetter(BranchPath):
def __init__(self, modelClass, fieldAddress):
super(OutputSetter, self).__init__(modelClass, fieldAddress, "outputSetter")
#Constructed from one InputSetter and one OutputSetter. An annonymous
# Branch is made to join the InputSetter and OutputSetter at the
# ModelClass where they meat up together.
# .process(instance) performs all calculations to make the
# currentOutput the correct value given the currentInput
class ProcessPath(Node):
def __init__(self, modelClass, inputFieldAddress, outputFieldAddress):
super(ProcessPath, self).__init__()
print "ProcessPath(init):\n inputField: %s\n outputField: %s" % (inputFieldAddress, outputFieldAddress)
inputSetter = self['inputSetter'] = \
modelClass.getInputSetter(inputFieldAddress)
outputSetter = self['outputSetter'] = \
modelClass.getOutputSetter(outputFieldAddress)
#inputPath and outputPath contain a list of Branch objects
inputPath = inputSetter['path']
outputPath = outputSetter['path']
outputPathMaxIndex = len(outputPath) -1
#this loops finds the common root of inputSetter and outputSetter
for i in range(len(inputPath)):
#ipdb.set_trace()
if inputPath[i]['uuid'] == outputPath[i]['uuid']:
continue
if i == outputPathMaxIndex:
break
#rootBranch contains the common root of inputSetter and outputStter
rootBranch = inputPath[i]
#linkBranch is an anonymous Branch which connects the inputSetter to the outputSetter
linkBranch = Branch(rootBranch['modelClass'], rootBranch['fieldName'], rootBranch['field'])
linkBranch['outputFieldName'] = outputPath[i]['fieldName']
self['inputSetter'] = inputSetter
self['outputSetter'] = outputSetter
self['rootI'] = i
self['linkBranch'] = linkBranch
#Travel from the end of the inputSetter to the beginiing of the inputSetter (the commonRoot) and then from the start of the outputSetter
# to the end of the outpuSetter, updating all the relevant values
# in all the fields along the way. In the end, outputSetter.getValue(instance) will contain the correct value.
def process(self, instance):
##ipdb.set_trace()
instance['currentlyProcessing'] = []
processPath = self
print "Processing Path:\n input: %s\n output: %s" % (self['inputSetter'], self['outputSetter'])
#rootI is the [index] of the common root Branch
rootI = processPath['rootI']
inputPath = processPath['inputSetter']['path'][rootI:-1]
inputField = processPath['inputSetter']['path'][-1]
#iterate from end of inputSetter (backwards) to commonRoot. Updating fieldValues along the way
for branch in reversed(inputPath):
#assume that the ModelClass we are currently Processing has
# all the modelInstance values set already. Call "process"
# to calculate the value of the currentOutputField given that
# the currentInputField and its value have already been set.
remoteFieldValue = branch['subModelClass']['fields'][branch['remoteFieldName']]['processor'].process(instance, inputField['field']['name'])
#look up the Branch connecting this ModelClass to its parent.
# the top of this Branch is the currentInputField for the parent
# ModelClass. Set the value of that field value of currentOutputFIeld
# for this (the child) ModelClass
branch.setFieldValue(instance, remoteFieldValue)
inputField = branch
#currentlyProcessing is used to find circular dependencies during
# processing
del instance['currentlyProcessing'][:]
##ipdb.set_trace()
# iterate from commonRoot to end of outputSetter (forwards). Updating fieldValues along the way
for branch in processPath['outputSetter']['path'][rootI:]:
#process this ModelClass, assuming that all values have been set
fieldValue = branch['processor'].process(instance, inputField['field']['name'])
#set the value of currentInputField for the child ModelClass
# using the calculated currentOutputField from this, the parent,
# ModelClass
branch.setFieldValue(instance, fieldValue)
#traverse along the path, down the ModelClass tree
if 'subModelClass' in branch:
branch['subModelClass']['fields'][branch['remoteFieldName']].setFieldValue(instance, branch.getFieldValue(instance))
inputField = branch['subModelClass']['fields'][branch['remoteFieldName']]
del instance['currentlyProcessing'][:]
return fieldValue
#contains all the data for an instance of a ModelClass.
# each time a user creates a new instance of ModelClass
# on the web interface. One of these objects is created to contain the
# relevant data.
# Much of the time, the ModelInstance does not directly contain
# data, but its UUID is used as the lookup key for data stored
# directly in ModelClass objects
class ModelInstance(Node):
def __init__(self, modelInstances, modelClass):
super(ModelInstance, self).__init__()
#modelInstances is a global store of all ModelInstance objects
# the UUID of a modelInstance is sent to the browser for identification
modelInstances[self['uuid']] = self
self['modelClass'] = modelClass
#contains a list of the fields whos values are part of the calculation
# for this ModelClass for this step in the iteration along the ProcessPath
self['currentlyProcessing'] = PersistentList()
print "Setting Defaults for ModelClass: %s" % self['modelClass']['name']
#set the currentInputField to either the last field updated by the user, or
# the default, if the user has not yet interacted with this instanceData
inputField = self["lastAlteredInput"] = modelClass['defaultInputField']
#set the currentOutputField to ...
outputField = self["lastAlteredOutput"] = modelClass['defaultOutputField']
#set the currentVisualisation to ...
visualisationField = self["lastAlteredVisualisation"] = modelClass['defaultVisualisationField']
#record the inputFieldAltered sequence for embed URL and other things... cant remember whwat
modelFieldAlteredSequence = self['modelFieldAlteredSequence'] = PersistentList()
#store BottomModel data and memoise bottomModel instances
self['bottomModel'] = None
self['isBottomModel'] = False
self['bottomModelHistory'] = PersistentMapping()
#setup the process path for this modelInstance
self.getInputSetter(inputField)
self.getOutputSetter(outputField)
# and process :)
self.process()
#utility method to get InputSetter from the parent ModelClass.
# make this the official InputSetter for this modelInstance
def getInputSetter(self, inputFieldAddress):
self['inputFieldAddress'] = inputFieldAddress
toReturn = self['inputSetter'] = self['modelClass'].getInputSetter(inputFieldAddress)
return toReturn
#utility method to get OutputSetter from the parent ModelClass
# make this the official OutputSetter for this modelInstane
def getOutputSetter(self, outputFieldAddress):
self['outputFieldAddress'] = outputFieldAddress
toReturn = self['outputSetter'] = self['modelClass'].getOutputSetter(outputFieldAddress)
return toReturn
#utility method to get ProcessPath from the parent ModelClass
# make this the official OutputSetter for this modelInstane
def getProcessPath(self):
toReturn = self['processPath'] = self['modelClass'].getProcessPath(self['inputFieldAddress'], self['outputFieldAddress'])
return toReturn
#utility method to get ProcessPath for this Instance. Used by the svgOutputCalculter, e.g.
# DO NOT STORE THIS PROCESS PATH AS THE OFFICIAL PROCESS PATH FOR THIS INSTANCE
def getProcessPathTemp(self, inputFieldAddress, outputFieldAddress):
toReturn = self['modelClass'].getProcessPath(inputFieldAddress, outputFieldAddress)
return toReturn
#process this instance.
def process(self):
##ipdb.set_trace()
processPath = self.getProcessPath()
return processPath.process(self)
#get the JSON definition for this instance.
# Sent to the browser to constuct sliders and stuff
def getJSInterface(self, boundInputField=None):
boundInputFullAddress = json.dumps(boundInputField)
(fieldDefinitions, fieldBranches) = self['modelClass'].getFieldDefinitions()
##ipdb.set_trace()
#if not 'jsInterface' in self:
jsInterface = self['jsInterface'] = \
{ "id": self['uuid'],
"modelClass": self['modelClass']['name'],
"fields": dict(fieldDefinitions),
}
#more bottomModel stuff
if boundInputField is not None:
jsInterface['fields'][boundInputFullAddress]['inputField'] = False
fieldValues = jsInterface['fieldValues'] = {}
for (fieldName, fieldBranch) in fieldBranches.items():
fieldValues[fieldName] = fieldBranch.getFieldValue(self)
if "inputFieldHUD" in self['modelClass']:
jsInterface['inputFieldHUDJSON'] = self['modelClass']['inputFieldHUD']
print ("MODELINSTANCE", self.keys())
return jsInterface
def getCanonicalURLJSON(self):
#modelClass, fieldValues, lastAlteredInput, lastAlteredOutput, lastAlteredVisualisation
(fieldDefinitions, fieldBranches) = self['modelClass'].getFieldDefinitions()
##ipdb.set_trace()
#if not 'jsInterface' in self:
urlData = \
{ "id": self['uuid'],
"fields": dict(fieldDefinitions).keys()
}
#more bottomModel stuff
#if self['boundInputField'] is not None:
# urlData['fields'][boundInputFullAddress]['inputField'] = False
fieldValues = urlData['fieldValues'] = {}
for (fieldName, fieldBranch) in fieldBranches.items():
fieldValues[fieldName] = fieldBranch.getFieldValue(self)
return urlData
def setFieldValues(self, fieldValues):
# ipdb.set_trace()
(fieldDefinitions, fieldBranches) = self['modelClass'].getFieldDefinitions()
for (fieldName, fieldBranch) in fieldBranches.items():
fieldBranch.setFieldValue(self, fieldValues[fieldName])
#Big complicated object that administrates loads of stuff
# FieldNames by RootClass
#
class Branch(Node):
dependentFieldRegex = re.compile("\!\!(?P<fieldName>.*?)\!\!")
def __init__(self, modelClass, fieldName, field):
super(Branch, self).__init__()
#my parent ModelClass
self['modelClass'] = modelClass
#the name of this FieldBranch in the parent ModelClass
self['fieldName'] = fieldName
#the fieldDefinition (more or less the same as the JSON object sent to
# the browser to define the Field
self['field'] = field
#Data stored by RootModelClass (e.g. the path to this FieldBranch from the RootModelClass, e.g. ["inputWatts", "mass"] for CPS: Coal: mass)
self['classData'] = ValueByInstance()
#data stored by ModelInstance (e.g the currentValue of this field)
self['instanceData'] = ValueByInstance()
def initialise(self, root, fieldAddress):
#store Field name by RootClass
self['classData'].setValue(root, "fieldAddress", fieldAddress)
#create a DisplayName and store by RootClass
self['classData'].setValue(root, "displayFieldAddress", "%s: %s %s %s" % (self['modelClass']['name'], self['field']['unitPrefix'], self['fieldName'], self['field']['unitSuffix']))
#create a flat dictionary for ALL branches attached to a ModelClass and
# all its SubModelClasses
root['fieldBranches'][fieldAddress] = self
#if a Branch has a SubModel hanging off the end of it, then we
# initialise the SubModel's fields recursively, making them
# available in the flat field list in the RootModelClass
if "subModelClassDef" in self:
subModelDef = self['subModelClassDef']
subModelClass = self['subModelClass'] = self['modelClass']['modelClassContainer'][subModelDef['className']]
self['remoteFieldName'] = subModelDef['remoteFieldName']
subModelClass.initialise(root, fieldAddress)
#extract some specific data from the actual Fields, that affects
# the parent RootModelClass of that Field (e.g. defaultInputField)
if self['modelClass'] == root:
if self['field']['defaultInputField'] == True:
root['defaultInputField'] = fieldAddress
if self['field']['defaultOutputField'] == True:
root['defaultOutputField'] = fieldAddress
if self['field']['defaultVisualisationField'] == True:
root['defaultVisualisationField'] = fieldAddress
return self
def getFieldValue(self, instance):
if not self['instanceData'].hasInstance(instance,"fieldValue"):
toReturn = self['field']['defaultValue']
self['instanceData'].setValue(instance, "fieldValue", toReturn)
else:
toReturn = self['instanceData'].getValue(instance, "fieldValue")
return toReturn
def setFieldValue(self, instance, value):
self['instanceData'].setValue(instance, "fieldValue", value)
def process(self, instance, inputField):
print "BranchProcess:\n instance: %s\n inputField: %s" % (instance, inputField)
def __str__(self):
subModelClass = {"name": "noSubModel"}
if "subModelClass" in self:
subModelClass = self['subModelClass']
remoteFieldName = "__noRemoteFieldName"
if "remoteFieldName" in self:
remoteFieldName = self['remoteFieldName']
outputField = "__noOutputField"
if "outputFieldName" in self:
outputField = self['outputFieldName']
return "Branch: %s, Field: %s, SubModel: %s\n outputField: %s" \
% ( self['modelClass']['name'],
self['field']['name'],
subModelClass['name'],
outputField
)
class ModelClassAlreadyDefinedException(Exception):
def __init__(self, message):
self.message = message
class ModelClass(Node):
def __init__(self, root, modelClassName, fields, processors, subModels, svgDisplayDefs, **kwargs):
super(ModelClass, self).__init__()
modelClasses = root['modelClasses']
fieldUnitIndex = root['fieldUnitIndex']
if modelClassName in modelClasses:
raise ModelClassAlreadyDefinedException("There is already a ModelClass called %s" % modelClassName)
modelClasses[modelClassName] = self
self["modelClassContainer"] = modelClasses
self['fieldUnitIndex'] = fieldUnitIndex
self["name"] = modelClassName
self["hasInstance"] = False
self['fieldBranches'] = PersistentMapping()
self["inputSetters"] = PersistentMapping()
self["outputSetters"] = PersistentMapping()
self["processPaths"] = PersistentMapping()
self['fieldsByUnit'] = Node()
self["classInstanceData"] = ValueByInstance()
fieldDict = self.getDict("fields")
for (fieldName, field) in fields.items():
field["modelClass"] = self['name']
branch = Branch(self, fieldName, field)
fieldDict[fieldName] = branch
fieldUnitIndex.getList(field['unit']).append(branch)
self['fieldsByUnit'].getList(field['unit']).append(branch)
processorDict = self.getDict('fieldProcessors')
for (fieldName, processorDict) in processors.items():
field = fieldDict[fieldName]
field['processor'] = FieldProcessor(field, processorDict)
for (fieldName, subModelDef) in subModels.items():
fieldDict[fieldName]['subModelClassDef'] = subModelDef
self['svgDisplayDefs'] = SVGDisplayDefs(self, svgDisplayDefs)
self.update(kwargs)
def initialise(self, root=None, address=tuple()):
if root==None:
root = self
if not "initialised" in root:
for (fieldName, fieldBranch) in self['fields'].items():
fieldBranch.initialise(root, address + (fieldName,))
if root==self:
self.getFieldDefinitions()
root['initialised'] = True
def getInputSetter(self, inputFieldAddress):
if not inputFieldAddress in self['inputSetters']:
self['inputSetters'][inputFieldAddress] = InputSetter(self, inputFieldAddress)
return self['inputSetters'][inputFieldAddress]
def getOutputSetter(self, outputFieldAddress):
if not outputFieldAddress in self['outputSetters']:
self['outputSetters'][outputFieldAddress] = OutputSetter(self, outputFieldAddress)
return self['outputSetters'][outputFieldAddress]
def getProcessPath(self, inputFieldAddress, outputFieldAddress):
#ipdb.set_trace()
if inputFieldAddress not in self['processPaths']:
inputFieldMem = self['processPaths'][inputFieldAddress] = PersistentMapping()
inputFieldMem = self['processPaths'][inputFieldAddress]
if outputFieldAddress not in inputFieldMem:
inputFieldMem[outputFieldAddress] = ProcessPath(self, inputFieldAddress, outputFieldAddress)
return self['processPaths'][inputFieldAddress][outputFieldAddress]
def getFieldDefinitions(self, root=None):
if root == None:
root = self
if root == self and "fieldDefinitionsRanAsRoot" in self:
fieldDefinitions = self['fieldDefinitions']
fieldBranches = self['fieldBranches']
else:
fieldDefinitions = PersistentMapping()
fieldBranches = PersistentMapping()
for (fieldName, field) in self['fields'].items():
fieldDefinition = field['field']
fieldAddress = field['classData'].getValue(root, "fieldAddress")
fullAddress = json.dumps(fieldAddress)
##ipdb.set_trace()
if "data" not in fieldDefinition.__dict__:
ipdb.set_trace()
fieldDefinitions[fullAddress] = fieldDefinition.__dict__['data']
fieldDefinitions[fullAddress]['displayFieldAddress'] = \
field['classData'].getValue(root, "displayFieldAddress")
fieldDefinitions[fullAddress]['fullAddress'] = fullAddress
fieldBranches[fullAddress] = field
if 'subModelClass' in field:
(subFieldDefinitions, subFieldBranches) = field['subModelClass'].getFieldDefinitions(root=root)
fieldDefinitions.update(subFieldDefinitions)
fieldBranches.update(subFieldBranches)
if self == root:
self['fieldDefinitions'] = PersistentMapping(fieldDefinitions)
self['fieldBranches'] = PersistentMapping(fieldBranches)
self['fieldDefinitionsRanAsRoot'] = True
transaction.commit()
return (fieldDefinitions, fieldBranches)
def getModelInstance(self, modelInstances):
instance = ModelInstance(modelInstances, self)
#jsInterface = instance.getJSInterface()
return instance
def __str__(self):
return "Class: %s\n fields: %s\n inputSetters: %s\n outputSetters: %s\n processPaths: %s\n svgDisplayDefs: %s\n\n" \
% (self['name'], self['fields'], self['inputSetters'], self['outputSetters'], self['processPaths'], self['svgDisplayDefs'])
class ClassField(Node):
"""def __init__( self,
name, fieldType,
defaultValue, rangeBottom, rangeTop, rangeType,
selectableValues,
unit=None, unitPrefix="", unitSuffix="",
inputField=False, outputField=False,
defaultInputField=False, defaultOutputField=False,
svgComponent=None
):
"""
def __init__( self, data):
super(ClassField, self).__init__()
self['visualisationField'] = False
self['defaultVisualisationField'] = False
self.update(data)
"""
self['name'] = name
self['fieldType'] = fieldType
self['defaultValue'] = defaultValue
self['rangeBottom'] = rangeBottom
self['rangeTop'] = rangeTop
self['rangeType'] = rangeType
self['unit'] = unit
self['unitPrefix'] = unitPrefix
self['unitSuffix'] = unitSuffix
self['selectableValues'] = selectableValues
self['inputField'] = inputField
self['outputField'] = outputField
self['defaultInputField'] = defaultInputField
self['defaultOutputField'] = defaultOutputField
"""