-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsequence_generation.py
2147 lines (1784 loc) · 96.8 KB
/
sequence_generation.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 operator
import functools
import numpy as np
import copy
import sys
import random
import z3
import subprocess
import time
from enum import IntEnum, Enum
#pylint: disable = E0602
#enums used to make indexing into structures more readable/maintainable
class SET(Enum):
Explicit = 0
Implicit = 1
class Possibility(IntEnum):
State = 0
Requirements = 1
Constraints = 2
Dependency = 3
class WireState(IntEnum):
State = 0
Index = 1
class ProposedState(IntEnum):
State = 0
Index = 1
Dependency = 2
RawReq = 3
#numpy complains if "==" is used directly
def numpy_compare(np_value, tuple_value):
return all(map(lambda x: operator.eq(*x), zip(np_value, tuple_value)))
#exception used when handling states, generally thrown if the resulting state is empty
class State_Space_Error(Exception):
def __init__(self, msg):
self.msg = msg
class Set_Error(Exception):
def __init__(self, msg):
self.msg = msg
class z3_Error(Exception):
def __init__(self, msg):
self.msg = msg
class Wire_Error(Exception):
def __init__(self, msg):
self.msg = msg
def topological_sort(out_going_edges_dict):
'''topologically sorts the graph described by a dictionary of outgoing edges, returns a list of lists,
whereby nodes in the same sublist have the same "rank", i.e. can be permuted arbitrarily'''
out_going_edges = copy.deepcopy(out_going_edges_dict)
in_going_edges = {}
node_list = []
add_to_outgoing = set()
for node, neighbours in out_going_edges.items():
for n in neighbours:
size = len(neighbours)
if not n in in_going_edges:
in_going_edges.update({n: {node}})
else:
in_going_edges.update({n: in_going_edges[n] | {node}})
if not n in out_going_edges:
add_to_outgoing.add(n)
out_going_edges[node] = len(neighbours)
if not node in in_going_edges:
in_going_edges.update({node: set()})
for node in add_to_outgoing:
out_going_edges[node] = 0
value = True
while len(out_going_edges) != 0 and value:
remove_set = set()
for node, size in out_going_edges.items():
if size == 0:
remove_set.add(node)
if remove_set == set() and len(out_going_edges) != 0:
value = False
remove_list = list(remove_set)
#random.shuffle(remove_list)
node_list.append(remove_list)
for node in remove_list:
#node_list.append(node)
del out_going_edges[node]
for n in in_going_edges[node]:
if n in out_going_edges:
out_going_edges.update({n: out_going_edges[n] - 1})
if not value:
return None
else:
return node_list
def select_state(state):
'''selects a single state from a state space of possible states'''
if is_possibility(state):
#currently just returns first option...
return select_state(state[0])
if isinstance(state, list):
return list(map(select_state, state))
if isinstance(state, tuple):
new_state = (state[0] + state[1]) // 2
return (new_state, new_state)
if isinstance(state, set):
if state == {0, 1}:
return {0} #try to set enable signals to 0 if possible
else:
element = state.pop()
state = state.add(element)
return {element}
else:
raise State_Space_Error("unknown state format")
#no "splinter" should contain s2
#used to generate z3 constraints
def state_difference(s1, s2):
if isinstance(s1, list) and isinstance(s2, list):
return_value = []
for i in range(len(s2)):
possibility = state_difference(s1[i], s2[i])
for state in possibility:
return_value.append(s1[0:i] + [state] + s1[i+1:])
return return_value
if isinstance(s1, set) and isinstance(s2, set):
s = set.difference(s1, s2)
if s != set():
return [set.difference(s1, s2)]
else:
return []
if isinstance(s1, tuple) and isinstance(s2, tuple):
if s1[1] > s2[1] and s1[0] >= s2[0]:
return [(s2[1] + 1, s1[1])]
elif s1[0] < s2[0] and s2[1] >= s1[1]:
return [(s1[0], s2[0] - 1)]
elif s1[0] < s2[0] and s2[1] < s1[1]:
return [(s1[0], s2[0] - 1), (s2[1] + 1, s1[1])]
else:
return []
#unites two state dictionaries in place (i.e. d1 will contain united dictionary)
#throws exception if states described by d1 and d2 disagree
def unite_dict(d1, d2):
'''unites two state dictionaries (state requirements) in place (d1 will contain the united dictionary),
throws exception if states described by d1 and d2 disagree'''
for key in d2:
if key in d1:
try:
d1[key] = intersect(d1[key], d2[key])
except State_Space_Error:
raise State_Space_Error("requested change of %s to %s does not conform to most general state %s" %(key, d1[key], d2[key]))
else:
d1.update({key: d2[key]})
#creates a new dictionary and returns it
def unite_dict_return(d1, d2):
'''unites two state dictionaries (state requirements) and returns the result in a new dictionary. Throws an exception of d1 and d2 disagree'''
d3 = copy.deepcopy(d1)
for key in d2:
if key in d3:
try:
d3[key] = intersect(d3[key], d2[key])
except State_Space_Error:
raise State_Space_Error("the dictionaries do not agree on %s; values %s and %s" %(key, d2[key], d3[key]))
else:
d3[key] = d2[key]
return d3
#used by advanced backtracking
def state_union_dict(d1, d2):
'''unites two state dictionaries (state requirements) in place, but does not throw an exception if their states disagree and instead sets the corresponding conductor state to "None".'''
for key in d2:
if key in d1:
try:
d1[key] = intersect(d1[key], d2[key]) #can only be sure that intersection won't work
except State_Space_Error:
d1[key] = None #will fail "try checks" and will hence be tried
#raise State_Space_Error("requested change of %s to %s does not conform to most general state %s" %(key, d1[key], d2[key]))
else:
d1.update({key: d2[key]})
#computes the union of two states
#not used anymore...
def state_union(space1, space2):
if type(space1) == list and type(space2)==list and len(space1) == len(space2):
return list(map(lambda x: intersect(x[0], x[1]), zip(space1, space2)))
if(type(space1) == tuple and type(space2) == tuple):
a = min(space1[0], space2[0])
b = max(space1[1], space2[1])
if(a > b):
raise State_Space_Error(
"resulting space state is empty, invalid wire")
return((a, b))
elif (type(space1) == set and type(space2) == set):
c = set.union(space1, space2)
if c == set():
raise State_Space_Error(
"resulting space state is empty, invalid wire")
return c
else:
#print(str(space1) + " and " + str(space2))
raise State_Space_Error("incompatible state spaces: " + str(space1) + " and " + str(space2))
def is_possibility(space):
'''decides if a given state space is a list of cartesian state products or just a single such product.
Would hence return True for [[(0, 2)], [(4, 5)]] or [[(2, 3)]] but False for [(2, 3)]'''
return isinstance(space, list) and len(space) > 0 and isinstance(space[0], list)
def intersect(space1, space2):
'''Returns the intersection of two state spaces'''
if not is_possibility(space1) and not is_possibility(space2):
return intersect_option(space1, space2)
if is_possibility(space1) and is_possibility(space2):
combined_state = []
for s1 in space1:
new_state = None
i = 0
while new_state is None and i < len(space2):
try:
new_state = intersect_option(space2[i], s1)
except State_Space_Error:
i = i + 1
if not new_state is None:
combined_state.append(new_state)
if len(combined_state) == 0:
raise State_Space_Error("resulting state is empty")
else:
return combined_state
#elif:
#return State_Space_Error("%s and %s have an unexpected format" %(str(space1), str(space2)))
elif is_possibility(space1):
return intersect_states(space1, [space2])
else:
return intersect_states(space2, [space1])
def is_range(state):
'''determines if a partial state description corresponds to a range of the form (min, max)'''
return isinstance(state, tuple) and len(state) == 2 and isinstance(state[0], int) and isinstance(state[1], int)
def intersect_option(space1, space2):
'''intersects two state spaces for which is_possibility returns false, i.e. they correspond to a single cartesian state product'''
if is_range(space1) and is_range(space2):
a = max(space1[0], space2[0])
b = min(space1[1], space2[1])
if(a > b):
raise State_Space_Error(
"resulting space state is empty, invalid wire")
return (a, b)
elif isinstance(space1, list) and isinstance(space2, list) and len(space1) == len(space2):
return list(map(lambda x: intersect_option(x[0], x[1]), zip(space1, space2)))
elif (type(space1) == set and type(space2) == set):
c = set.intersection(space1, space2)
if c == set():
raise State_Space_Error(
"resulting space state is empty, invalid wire")
return c
else:
#print(str(space1) + " and " + str(space2))
raise State_Space_Error("incompatible state spaces: " + str(space1) + " and " + str(space2))
def empty_intersection(name, state_dict1, state_dict2):
if name[:4] == "set_":
name = name[4:]
try:
intersect(state_dict1[name], state_dict2[name])
except State_Space_Error:
return True
except KeyError:
return True
return False
def create_state_possibility(state, most_general_state):
'''tries to unite the state attribute of an output state possibility with the intersection of amr states given by the conductor's inputs (most_general_state).
Returns an infeasible state if that is not possible (cannot simply discard the possibilitiy because of other, feasible state updates the possibility might define)'''
try:
return intersect(state, most_general_state)
except State_Space_Error:
new_state = []
for elem in most_general_state:
if isinstance(elem, tuple):
new_state.append((0, -1))
elif isinstance(elem, set):
new_state.append(set())
else:
raise State_Space_Error("%s is an unknown state dimension expression" % str(elem))
return new_state
#used in synthesize_state_updates (updates state of stateful nodes)
#generates all steps (i.e. offsets of entries of reachable) that should be marked reachable (if propagate conditions met)
def generate_all_valid_steps(size):
'''generates all bit strings of length size.
Used in synthesize_state_updates to correctly fill in the dp table'''
if size == 1:
return [[0], [1]]
else:
valid_steps = generate_all_valid_steps(size-1)
return list(map(lambda x: x + [0], valid_steps)) + list(map(lambda x: x + [1], valid_steps))
#extracts states from states that are possible
def possible(current_state, states):
'''returns the State Possibilities defined by states for which the state attribute agrees with "current_state"'''
possible_states = []
for state, condition, constraints, dependency in states:
try:
s = intersect(state, current_state)
possible_states.append((s, condition, constraints, dependency))
except State_Space_Error:
pass
return possible_states
class Input(object):
'''class used to provide Input pin descriptions for consumers and producers'''
def __init__(self, state_space, wire_type, monitor = None):
'''generate an input pin description:
state_space: corresponds to amr
wire_type: describes the conductor's type, must agree with the Output wire type
monitor: function of the form (node, conductor_name) -> ((value, current_states) -> (usable, <string of code that returns once conductor adopts value>))
node corresponds to the component object the input belongs to, and conductor name to the name of the conductor connected to input.
Will be passed to monitor when the conductor is instantiated (Wire.__init__)
usable must evaluate to True or False and indicates if the monitor can be used, according to current states'''
self.name = None
self.state_space = state_space
self.wire_type = wire_type
self.monitor = monitor
# constraints define conditions on inputs/internal device state that must be observed to ensure the "validity" of this output
class Output(object):
'''class used to provide output pin descriptions'''
def __init__(self, state_space, constraints, wire_type, method = None):
'''generates an output pin description:
state_space: summarises the state spaces described by the individual state possibilities by the output (as a convex approximation)
constraints: is a list of Constraint objects, each of which defines a State Possibility.
wire_type: the type of conductor defined by the output
method: specifies the set method of the output, used to explicitly update its state. Do not specify if no explicit set possible. Should be of the form:
(node, pinname) -> (value -> <string of code that updates conductor to value>)
Whereby node and pinname correspond to the component object the output belongs to, and pinname to the output pin's name.'''
self.name = None
self.state_space = state_space
self.wire_type = wire_type
self.constraints = constraints
if method is None:
self.set = Output.no_set
else:
self.set = method
@staticmethod
def no_set(device, pinname):
return lambda _: Wire.raise_exception("output of wire is not settable, or no set method was specified")
@staticmethod
def raise_exception(string):
raise AttributeError(string)
class Constraint(object):
'''class used to define a State Possibility'''
def __init__(self, state_possibility, state_requirements, dependency, complex_constraints = [], dependency_update = None, state_update = None):
'''defines a State Possibility:
state_possibility (type state): corresponds to the state attribute
state requirements (type state dict)
dependency (type partial function): should correspond to a partial function call (without node attribute) to Conductor.implicit or Conductor.explicit, defines an Event Graph with implicit or explicit Initiate Event.
complex_constraints: is a list of of constraints of the following format: (lambda X1, X2, .., Xn: <expression>, [(X1, index1), ..., (Xn, indexn)]), whereby Xi are pinnames of other pins the component defines
and indexi defines the state dimension that is being constrained.
dependency_update: specifies how the dependency attribute should be updated, is of the form (next: node -> (() -> index), [dependency0, ..., dependencyn]),
whereby node is the component object associated with the Output the Constraint object belongs to, and the index i returned by next specifies that the dependency attribute should be updated with dependencyi.
state_update: specifies how the state (state_possibility) attribute should be updated, is of the form (node -> (() -> state)), whereby node is the object associated with the Output the constraint belongs to'''
self.state_possibility = state_possibility
self.state_requirements = state_requirements
self.dependency = dependency
self.complex_constraints = complex_constraints
self.dependency_update = dependency_update
self.state_update = state_update
#flatten the information expressed by a Constraint to a form defined by Possibilty enum
def create_possibility(self, output_device, most_general_state, name, updates, constraints):
'''flattens the information expressed by a Constraint to a form defined by Possibility enum (and appends to "constraints"), adds state and dependency updates to the "update" list. Called internally in Conductor initialisation (Wire.__init__)'''
if not self.state_update is None:
function = self.state_update(output_device)
#determine current value of state_possibility
self.state_possibility = function()
#adds a new entry to update, which includes:
#index of updatable possibility
#the update function
#the z3 variable name
updates.append([len(constraints), Possibility.State, function, "update_%s_%d"%(name, len(constraints))])
else:
self.state_possibility = create_state_possibility(self.state_possibility, most_general_state)
if not self.dependency_update is None:
#must retain dependency list defined by dependency_update since they still need to be initialized (by passing "node" to them)!
(function, dependencies) = self.dependency_update
function = function(output_device)
updates.append([len(constraints), Possibility.Dependency, function, dependencies])
self.dependency = None
constraints.append([self.state_possibility, self.state_requirements, self.complex_constraints, self.dependency])
def create_bus_constraints(self, output_device, input_set, name, constraints):
constraints.append([self.state_possibility, self.state_requirements(output_device, input_set), self.complex_constraints, self.dependency(output_device, name, input_set)])
@staticmethod
def is_default(node):
return lambda node=node: 1 if node.is_default else 0
@staticmethod
def is_configured(node):
return lambda node=node: 1 if node.configured else 0
@staticmethod
def default_state(node):
return lambda node=node: node.current
@staticmethod
def explicit(output, before_set, before_complete, node, after_set = set(), after_complete = set()):
'''method used to define Event Graphs with an explicit Initiate Event'''
output_name = getattr(node, output).name
set_list = [before_set, before_complete, after_set, after_complete]
set_event = lambda name: "set_" + name
for i in range(4):
set_list[i] = set(map(lambda name: getattr(node, name).name, set_list[i]))
if i >= 2:
set_list[i] = set(map(set_event, set_list[i]))
return (SET.Explicit, set_list, lambda _ : {output_name: set()})
@staticmethod
def implicit(output, implicit_event, node, before_complete = {}, before_set = {}, after_complete = {}, after_set = {}):
'''method used to define Event Graphs with an implicit Initiate event'''
output_name = getattr(node, output).name
if isinstance(implicit_event, str):
implicit_event = getattr(node, implicit_event)
set_list = Constraint.explicit(output, before_set, before_complete, node, after_set, after_complete)[1]
new_implicit_event = {}
for name, state in implicit_event.items():
new_implicit_event[getattr(node, name).name] = state
return (SET.Implicit, set_list, lambda states, new_implicit_event = new_implicit_event: {output_name : set(filter(lambda x: not empty_intersection(x, new_implicit_event, states), new_implicit_event.keys()))})
@staticmethod
def indep(output, node):
output_name = getattr(node, output).name
return {output_name: {"set_" + output_name}}
@staticmethod
def off_because(output, reason, node):
output_name = getattr(node, output).name
reason_name = getattr(node, reason).name
return {output_name: {reason_name}}
@staticmethod
def settable(output, supplies, enable, node):
output_name = getattr(node, output).name
supplies_set = {getattr(node, supply).name for supply in supplies}
if enable is None:
return {"set_" + output_name: supplies_set, output_name : {"set_" + output_name} | supplies_set}
else:
enable_name = getattr(node, enable).name
#return {"set_" + output_name: supplies_set, "set_" + enable_name: {"set_" + output_name} , output_name : {enable_name}}
return {"set_" + output_name: supplies_set, "set_" + enable_name: {"set_" + output_name} | supplies_set , output_name : {enable_name, "set_" + output_name} | supplies_set}
@staticmethod
def enable(enable, supplies, node):
enable_name = getattr(node, enable).name
supplies_set = {getattr(node, supply).name for supply in supplies}
return {"set_" + enable_name: supplies_set, enable_name: {"set_" + enable_name} | supplies_set}
#return {"set_" + enable_name: supplies_set, enable_name: {"set_" + enable_name}}
@staticmethod
def on(output, supplies, enable, node):
output_name = getattr(node, output).name
supplies_set = {getattr(node, supply).name for supply in supplies}
if enable is None:
return {output_name: supplies_set}
else:
enable_name = getattr(node, enable).name
return {output_name: supplies_set | {enable_name}}
@staticmethod
def isl_on(output, setters, enable, supplies, node):
enable_name = getattr(node, enable).name
setter_set = {getattr(node, setter).name for setter in setters}
output_name = getattr(node, output).name
supplies_set = {getattr(node, supply).name for supply in supplies}
return {
output_name: supplies_set | {enable_name} | setter_set,
"set_" + enable_name : setter_set
}
# replaces statically defined input and output in devices it connects with a wire object => original input/output definition
# in class becomes inaccessible => make sure that all relevant information about input and outputs are copied to wire object
class Wire(object):
'''class used to internally construct Conductors given Component and Platform descriptions.'''
def __init__(self, name, output_device, output_name, input_set):
'''constructs a Conductor:
name (String): specifies the conductor's name,
output device (Node instance): refers to the producer instance (Node object) which defines the output pin the conductor is connected to
output_name (String): specifies the name of the output pin the conductor is connected to
input_set (Set of (Node instance, String)): specifies the set of inputs the conductor is connected to, as tuples of (Node instance, String), whereby the former references the component instance that defines the input,
and the latter indicates the name of the input pin.'''
_output = getattr(output_device, output_name)
if not isinstance(_output, Output):
print("\ngiven output of wire " +
name + " has already been assigned!\n")
raise AttributeError(self)
self.pin_name = output_name
self.type = _output.wire_type
self.constraints = []
self.input_set = input_set
self.output_device = output_device
self.name = name
self.most_general_state = _output.state_space
self.monitors = []
monitors = set()
#check types, unify output/input constraints, modify input attributes to point to wire
for input_node, input_name in input_set:
_input = getattr(input_node, input_name)
if input_node is output_device:
print("Warning: output of device " +
input_node.name + " connected to own input")
if not (isinstance(_input, Input)):
print("\ngiven input or output of wire " +
name + " has already been assigned!\n")
raise AttributeError(self)
if not (_input.wire_type == _output.wire_type):
if _input.wire_type == "monitor":
monitors.add((input_node, input_name))
else:
print("\ninput and output given to wire " +
name + " require different wire types!\n")
raise AttributeError(self)
if not _input.monitor is None:
self.monitors.append(_input.monitor(input_node, name))
self.most_general_state = intersect(self.most_general_state, _input.state_space)
if not (input_node, input_name) in monitors:
setattr(input_node, input_name, self)
#remove purely monitoring - based connections
input_set.difference_update(monitors)
self.updates = []
for constraint in _output.constraints:
if self.type == "bus":
constraint.create_bus_constraints(output_device, input_set, name, self.constraints)
else:
constraint.create_possibility(output_device, self.most_general_state, name, self.updates, self.constraints)
#instantiate wire set method
self.set = _output.set(output_device, output_name)
#let output attribute point to wire
setattr(output_device, output_name, self)
def update(self, topology):
'''updates the conductor's State Possibilities according to the dependency and state update they define.
the parameter topology is the entire Topology (Platform) object and is required to adequately update the z3 variables.'''
for index, update_type, function, arg in self.updates:
if update_type == Possibility.Dependency:
self.constraints[index][Possibility.Dependency] = arg[function()]
elif update_type == Possibility.State:
value = function()
self.constraints[index][Possibility.State] = value
topology.updatable_vars[arg] = topology.format_state(value)
else:
raise Wire_Error("update %i (%s) has an unexpected format" %(i, self.updates[i]))
#collection of different set methods used by components:
@staticmethod
def vid_set(node, pinname):
if pinname == "B_FDV_1V8":
offset = 8
if pinname == "B_CDV_1V8":
offset = 0
# XXX: The new API models this as a device with voltage controls so we need to reverse some stuff
# here.
def offset_to_control(offset):
if offset == 0:
return "CDV_1V8"
elif offset == 8:
return "FDV_1V8"
else:
return "INVALID_CONTROL"
def binary_to_voltage(binary):
voltage = 1.6125 - (binary * 0.00625)
if voltage < 0.5:
voltage = 0
elif voltage > 1.6:
voltage = 0
return voltage
def fun(value, offset=offset):
commands = node.configure()
commands.append("power.set_device_control('isl6334d_ddr_v', '%s', %.3f)" % (
offset_to_control(offset),
binary_to_voltage(int("".join(str(*x) for x in value), 2))
))
return "\n".join(commands)
return fun
@staticmethod
def cpu_clk_ok(node, pinname):
pins = ["B_CLOCK_BLOL", "B_CLOCK_CLOL"]
wait_for_string = "\n".join(map(lambda pin: "wait_for('%s', lambda: gpio.get_value('%s'), True, 10)" % (pin, pin), pins))
set_string = lambda s: "gpio.set_value('C_PLL_DCOK', %s)" % s
return lambda value: wait_for_string + "\n" + set_string(True) if value == [{1}] else set_string(False)
@staticmethod
def fpga_clk_ok(node, pinname):
return lambda value, pinname = pinname: "" if value == [{0}] else "wait_for('%s', lambda: gpio.get_value('%s'), True, 1)" % (pinname, pinname)
@staticmethod
def gpio_set(node, pinname):
def fun(value, pinname=pinname):
bool_value = bool(list(value[0])[0])
# XXX: PSUP_ON is special as we need to initialize the fan controller that we don't model yet
# and also enable/disable alerts
if pinname == "B_PSUP_ON":
if bool_value:
commands = [
"fault.mask_scram()",
"power.disable_bus_alerts('pwr_fan')",
"gpio.set_value('%s', %s)" % (pinname, bool_value),
"init_fan_control()",
"fault.unmask_scram()",
"power.enable_bus_alerts('pwr_fan')"
]
else:
commands = [
"fault.mask_scram()",
"power.disable_bus_alerts('pwr_fan')",
"gpio.set_value('%s', %s)" % (pinname, bool_value)
# XXX: We would also need to deinit devices but this is enough for now
]
else:
commands = [
"gpio.set_value('%s', %s)" % (pinname, bool_value)
]
return "\n".join(commands)
return fun
@staticmethod
def pin_set(node, pinname):
def fun(value, device=node.device, pinname=pinname):
commands = node.configure()
commands.append("power.set_device_control('%s', '%s', %s)" % (
str(device),
pinname,
'True' if value == [{1}] else 'False'
))
return "\n".join(commands)
return fun
@staticmethod
def voltage_set(node, pinname):
def fun(value, device=node.device):
commands = node.configure()
commands.append("power.device_write('%s', 'VOUT_COMMAND', %s)" % (
str(device), str(value[0][0] / 1000)
))
return "\n".join(commands)
return fun
@staticmethod
def ir_set(node, pinname):
loop = node.loop1
if len(pinname.split('_')) > 1:
loop = node.loop2
def fun(value, node=node, loop=loop):
commands = node.configure()
commands.append("power.device_write('%s', 'VOUT_COMMAND', %s)" % (
loop,
str(value[0][0] / 1000)
))
return "\n".join(commands)
return fun
@staticmethod
def no_set(node, pinname):
return lambda _: Wire.raise_exception("output of wire is not settable, or no set method was specified")
@staticmethod
def raise_exception(string):
raise Set_Error(string)
@staticmethod
def clock_config(node, pinname):
def fun(_):
return "\n".join(node.configure())
return fun
class Node(object):
'''base class used to describe a component, every component description must inherit from Node'''
def __init__(self, name, bus_addr, node_class):
self.name = name
self.bus_addr = bus_addr
self.subclass = node_class
def update(self, states):
'''generic update method, can be overwritten by subclasses'''
pass
def get_labels(self):
'''retrieves the labelling of the node used to graphically represent it'''
input_string = None
output_string = None
attributes = set(self.subclass.__dict__) | set(self.__dict__)
for attr in attributes:
#only draw connected ports
if attr in self.__dict__:
obj = self.__dict__[attr]
if isinstance(obj, Wire):
if obj.output_device.name == self.name:
if output_string is None:
output_string = "<%s> %s" %(attr, attr)
else:
output_string += " | <%s> %s" %(attr, attr)
else:
if input_string is None:
input_string = "<%s> %s" %(attr, attr)
else:
input_string += " | <%s> %s" %(attr, attr)
strings = [input_string, output_string]
additions = [("{", "{{", "} | "), ("}", " | {", "}}")]
for i in range(len(strings)):
empty, left, right = additions[i]
if strings[i] is None:
strings[i] = empty
else:
strings[i] = left + strings[i] + right
return strings[0] + self.name + strings[1]
class PowerState(object):
'''class used to represent a consumer's power state'''
def __init__(self, most_general_state, state_change_sequence):
'''constructs a power state representation of a consumer:
most_general_state (state dict): describes the general consumer demands associated with the power state
state_change_sequence (dictionary PowerState -> transition sequence): a dictionary entry P: trans specifies that transition sequence trans must be performed to change from power state P to the power state described by this PowerState instance.
Trans is assumed to be in an incremental form.'''
self.most_general_state = most_general_state
self.state_change_sequence = state_change_sequence
#defines initialisation methods and transition getters
class Stateful_Node(Node):
'''Class used to describe consumers, inherits from the general component class Node'''
def __init__(self, name, bus_addr, default_state, subclass):
self.subclass = subclass
self.default_state = default_state
self.states = None
super(Stateful_Node, self).__init__(name, bus_addr, subclass)
def get_transition(self, current_state, new_state):
'''returns the sequence of consumer demands that implements the transition for current_state to new_state'''
return self.states[new_state].state_change_sequence[current_state]
def get_most_general_states(self, current_state):
'''return the consumer demands associated with the power state "current_state"'''
return self.states[current_state].most_general_state
def print_transitions(self):
'''debugging print function that prints all transitions the consumer defines'''
for name, state in self.states.items():
print(name)
for init_state, sequence in state.state_change_sequence.items():
print(init_state)
print(sequence)
def extend_states(self):
'''constructs absolute consumer demands of transitions from incremental transition descriptions'''
for end_state in self.states:
for init_state, sequence in self.states[end_state].state_change_sequence.items():
last = self.get_most_general_states(init_state)
for i in range(len(sequence)):
last = copy.deepcopy(last)
last.update(sequence[i][0])
sequence[i] = (last, sequence[i][1])
last.update(self.get_most_general_states(end_state))
sequence.append((last, "")) #makes transition's end state consistent with final node state
def init_states(self):
'''renames local pin names of PowerState descriptions to feature conductor names and constructs absolute transitions'''
fun, args = self.subclass.states
args = map(lambda x: getattr(self, x).name, args)
self.states = fun(*args)
self.extend_states()
#object that collects all the flags and objects passed to the state_search
class State_Search_Flags(object):
'''object specifying the set of State_Search_Flags that can be passed to various methods to change their behaviour'''
def __init__(
self,
all_solutions = True,
extend = True,
ignore_nodes = set(),
record_unchanged = False,
print_solutions = False,
no_output = False,
advanced_backtracking = True,
use_z3 = False,
print_changed_req = True,
visualize = False,
return_graph = False,
prefer_concurrent_interleaving = True
):
self.aggressive = not all_solutions
self.advanced_backtracking = advanced_backtracking
self.all_solutions = all_solutions
self.extend = extend
self.ignore_nodes = ignore_nodes
self.record_unchanged = record_unchanged
self.print_solutions = print_solutions
self.no_output = no_output
self.use_z3 = use_z3
self.print_changed_req = print_changed_req
self.visualize = visualize and global_visualise
self.return_graph = return_graph
self.prefer_concurrent_interleaving = prefer_concurrent_interleaving
#used in shared_wire_states array because numpy does not support arrays of dictionaries... :|
class Dictionary_object(object):
'''ugly helper class since numpy does not support arrays of dictionaries'''
def __init__(self, wire_list):
self.w = {}
for wire in wire_list:
self.w[wire] = None
class Topology(object):
'''class used to construct platform instances'''
def __init__(self, nodes, wires, rank_length = 1, speed = 0.5, sorted_wires = None):
'''constructs a reduced platfrom instance from component and connection descriptions:
nodes: a list of component descriptions of the following from (component_name, bus_address, component_class, <list of additional attributes>)
whereby the component_class specifies the class of which the described component is an instance (said class must inherit from Node for a producer / Stateful_Node for a consumer)
wires: a list of connection descriptions of the following format: (conductor name, name of output component, name of output pin, Set of: (name of input component, name of input pin))'''
self.commands = ""
self.nodes = {}
self.wires = {}
self.stateful_nodes = set()
self.most_general_state = {}
self.current_wire_state_range = {}
self.current_wire_state = {}
self.current_node_state = {}
self.speed = speed
#attributes storing z3 expression of problem
self.problem = z3.Solver()
self.vars = {}
#stores variables corresponding to updatable state_possibilities
self.updatable_vars = {}
#used to construct dependency graph of wires
out_going_wires = {}
incoming_wires = {}
graph = {}
#define nodes
for name, bus_addr, class_obj, args in nodes:
out_going_wires[name] = set()
incoming_wires[name] = set()
#instantiate node object
new_node = class_obj(name, bus_addr, *args)
self.nodes.update({name: new_node})
if isinstance(new_node, Stateful_Node):
self.stateful_nodes.add(name)
graph_w = {}
#define wires (requires nodes to be defined already)
for name, output_device, output_name, input_set in wires:
graph[name] = set()
out_going_wires[output_device].add(name)
input_nodes_set = set()
for (input_node, input_name) in input_set:
incoming_wires[input_node].add(name)
input_nodes_set.add((self.nodes[input_node], input_name))
w = Wire(name, self.nodes[output_device], output_name, input_nodes_set)
input_set = set(map(lambda x : (x[0].name, x[1]), input_nodes_set))
graph_w[name] = [output_device, output_name, input_set, w.type]
self.wires.update({name: w})
self.most_general_state.update({name: self.wires[name].most_general_state})
self.generate_vars(w)