-
Notifications
You must be signed in to change notification settings - Fork 1
/
lib.py
1555 lines (1312 loc) · 55.3 KB
/
lib.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, functools, math, time
import xml.etree.ElementTree as ET
from model import *
from sim import Property, Simulator
from procon import ProducerRegistry, ConsumerRegistry
class SchemaRegistry(type):
ALL = {}
def __new__(mcs, name, bases, dict):
tp = type.__new__(mcs, name, bases, dict)
if name != 'SimSchema':
inst = tp()
if inst.name in mcs.ALL:
print('WARNING: Multiple registrations for name', inst.name)
print(' old registrant:', mcs.ALL[inst.name])
print(' new registrant:', inst)
mcs.ALL[inst.name] = inst
return tp
class SimSchema(Schema, metaclass=SchemaRegistry):
def __init__(self, cat, name, ins, outs, props=None):
Schema.__init__(self, name, ins, outs)
self.cat = cat
self.props = props or []
self.propmap = {prop.name: prop for prop in self.props}
def reset(self, node):
pass
def step(self, node):
raise NotImplementedError('SimSchema.step()')
################################################################################
class Add(SimSchema):
'''Computes the sum of all of its inputs.'''
def __init__(self):
SimSchema.__init__(self, 'Arithmetic', 'ADD', [
Connector('I', float, False),
], [
Connector('Q', float),
])
def step(self, node):
node.setOut('Q', sum(node.getIns('I')))
class Subtract(SimSchema):
'''Computes Q = A - B'''
def __init__(self):
SimSchema.__init__(self, 'Arithmetic', 'SUB', [
Connector('A', float),
Connector('B', float),
], [
Connector('Q', float),
])
def step(self, node):
node.setOut('Q', node.getIn('A') - node.getIn('B'))
class Multiply(SimSchema):
'''Computes the product of all of its inputs with floating point precision.'''
def __init__(self):
SimSchema.__init__(self, 'Arithmetic', 'MUL', [
Connector('I', float, False),
], [
Connector('Q', float),
])
def step(self, node):
node.setOut('Q', functools.reduce(operator.mul, node.getIns('I'), 1.0))
class Divide(SimSchema):
'''Computes Q = A / B with floating-point precision.'''
def __init__(self):
SimSchema.__init__(self, 'Arithmetic', 'DIV', [
Connector('A', float),
Connector('B', float),
], [
Connector('Q', float),
])
def step(self, node):
node.setOut('Q', node.getIn('A') / node.getIn('B'))
class DivideModulus(SimSchema):
'''Computes Q (quotient) and M (modulus) such that Q*B + M = A and M is in [0, B) or (B, 0], depending on the sign of B.'''
def __init__(self):
SimSchema.__init__(self, 'Arithmetic', 'DIMO', [
Connector('A', float),
Connector('B', float),
], [
Connector('Q', float),
Connector('M', float),
])
def step(self, node):
quot, mod = divmod(node.getIn('A'), node.getIn('B'))
node.setOut('Q', quot)
node.setOut('M', mod)
class Exponentiate(SimSchema):
'''Computes Q = A ** B (A raised to the B).'''
def __init__(self):
SimSchema.__init__(self, 'Arithmetic', 'EXP', [
Connector('A', float),
Connector('B', float),
], [
Connector('Q', float),
])
def step(self, node):
node.setOut('Q', node.getIn('A') ** node.getIn('B'))
class Negate(SimSchema):
'''Computes Q = -I.'''
def __init__(self):
SimSchema.__init__(self, 'Arithmetic', 'NEG', [
Connector('I', float),
], [
Connector('Q', float),
])
def step(self, node):
node.setOut('Q', -node.getIn('I'))
class Reciprocal(SimSchema):
'''Computes Q = 1 / I = I ** (-1).'''
def __init__(self):
SimSchema.__init__(self, 'Arithmetic', 'RCP', [
Connector('I', float),
], [
Connector('Q', float),
])
def step(self, node):
node.setOut('Q', 1.0 / node.getIn('I'))
class Signum(SimSchema):
'''Computes Q = signum(I), where signum is a function that returns a value in the set {-1, 0, 1} whose sign is the same as the input, or zero if the input is zero.'''
def __init__(self):
SimSchema.__init__(self, 'Arithmetic', 'SGN', [
Connector('I', float),
], [
Connector('Q', int),
])
def step(self, node):
val = node.getIn('I')
if val == 0.0:
node.setOut('Q', 0.0)
else:
node.setOut('Q', math.copysign(1.0, val))
class Ceiling(SimSchema):
'''Computes Q = ceil(I), where ceil is a function returning the least integer greater than I.'''
def __init__(self):
SimSchema.__init__(self, 'Arithmetic', 'CEIL', [
Connector('I', float),
], [
Connector('Q', int),
])
def step(self, node):
node.setOut('Q', math.ceil(node.getIn('I')))
class Floor(SimSchema):
'''Computes Q = floor(I), where floor is a function returning the greatest integer less than I.'''
def __init__(self):
SimSchema.__init__(self, 'Arithmetic', 'FLOR', [
Connector('I', float),
], [
Connector('Q', int),
])
def step(self, node):
node.setOut('Q', math.floor(node.getIn('I')))
################################################################################
class Zero(SimSchema):
'''Emits a constant 0.0.'''
def __init__(self):
SimSchema.__init__(self, 'Constants', 'ZERO', [], [Connector('0', float)])
def step(self, node):
node.setOut('0', 0.0)
class One(SimSchema):
'''Emits a constant 1.0.'''
def __init__(self):
SimSchema.__init__(self, 'Constants', 'ONE', [], [Connector('1', float)])
def step(self, node):
node.setOut('1', 1.0)
class Two(SimSchema):
'''Emits a constant 2.0.'''
def __init__(self):
SimSchema.__init__(self, 'Constants', 'TWO', [], [Connector('2', float)])
def step(self, node):
node.setOut('2', 2.0)
class E(SimSchema):
'''Emits Euler's constant.'''
def __init__(self):
SimSchema.__init__(self, 'Constants', 'E', [], [Connector('e', float)])
def step(self, node):
node.setOut('e', math.e)
class Pi(SimSchema):
'''Emits pi, the ratio of a circle's circumference to its diameter.'''
def __init__(self):
SimSchema.__init__(self, 'Constants', 'PI', [], [Connector('p', float)])
def step(self, node):
node.setOut('p', math.pi)
class Tau(SimSchema):
'''Emits tau, the ratio of a circle's circumference to its radius.'''
def __init__(self):
SimSchema.__init__(self, 'Constants', 'TAU', [], [Connector('t', float)])
def step(self, node):
node.setOut('t', 2*math.pi)
class Infinity(SimSchema):
'''Emits the floating point representation of positive infinity.'''
def __init__(self):
SimSchema.__init__(self, 'Constants', '+INF', [], [Connector('Q', float)])
def step(self, node):
node.setOut('Q', float('inf'))
class NegativeInfinity(SimSchema):
'''Emits the floating point representation of negative infinity.'''
def __init__(self):
SimSchema.__init__(self, 'Constants', '-INF', [], [Connector('Q', float)])
def step(self, node):
node.setOut('Q', float('-inf'))
class FloatConst(SimSchema):
'''Emits the floating point constant set as its `value' property.'''
def __init__(self):
SimSchema.__init__(self, 'Constants', 'FCON', [], [Connector('Q', float)], [Property('value', float, 0.0)])
def step(self, node):
node.setOut('Q', node.getProp('value'))
class IntConst(SimSchema):
'''Emits the integer constant set as its `value' property.'''
def __init__(self):
SimSchema.__init__(self, 'Constants', 'ICON', [], [Connector('Q', int)], [Property('value', int, 0)])
def step(self, node):
node.setOut('Q', node.getProp('value'))
class StringConst(SimSchema):
'''Emits the string constant set as its `value' property.'''
def __init__(self):
SimSchema.__init__(self, 'Constants', 'SCON', [], [Connector('Q', str)], [Property('value', str, '')])
def step(self, node):
node.setOut('Q', node.getProp('value'))
################################################################################
class Equal(SimSchema):
'''Computes the boolean truth of A == B.'''
def __init__(self):
SimSchema.__init__(self, 'Comparison', 'EQ', [
Connector('A'),
Connector('B'),
], [
Connector('Q', bool),
])
def step(self, node):
node.setOut('Q', node.getIn('A') == node.getIn('B'))
class Less(SimSchema):
'''Computes the boolean truth of A < B. The logical negation of this value is the truth of A >= B'''
def __init__(self):
SimSchema.__init__(self, 'Comparison', 'LS', [
Connector('A'),
Connector('B'),
], [
Connector('Q', bool),
])
def step(self, node):
node.setOut('Q', node.getIn('A') < node.getIn('B'))
class Greater(SimSchema):
'''Computes the boolean truth of A > B. The logical negation of this value is the truth of A <= B'''
def __init__(self):
SimSchema.__init__(self, 'Comparison', 'GT', [
Connector('A'),
Connector('B'),
], [
Connector('Q', bool),
])
def step(self, node):
node.setOut('Q', node.getIn('A') > node.getIn('B'))
################################################################################
class And(SimSchema):
'''Computes the logical conjunction of all of its inputs. For no inputs, emits True.'''
def __init__(self):
SimSchema.__init__(self, 'Logic', 'AND', [
Connector('I', bool, False),
], [
Connector('Q', bool),
])
def step(self, node):
node.setOut('Q', all(node.getIns('I')))
class Or(SimSchema):
'''Computes the logical disjunction of all of its inputs. For no inputs, emits False.'''
def __init__(self):
SimSchema.__init__(self, 'Logic', 'OR', [
Connector('I', bool, False),
], [
Connector('Q', bool),
])
def step(self, node):
node.setOut('Q', any(node.getIns('I')))
class Not(SimSchema):
'''Computes the logical negation of its input.'''
def __init__(self):
SimSchema.__init__(self, 'Logic', 'NOT', [
Connector('I', bool),
], [
Connector('Q', bool),
])
def step(self, node):
node.setOut('Q', not node.getIn('I'))
class EdgeDetect(SimSchema):
'''Emits True for exactly one tick when I goes from falsehood to truth (or truth to falsehood when `falling' is nonzero).'''
def __init__(self):
SimSchema.__init__(self, 'Logic', 'EDGE', [
Connector('I', bool),
], [
Connector('Q', bool)
], [
Property('falling', int, 0),
Property('init', int, 0),
])
def reset(self, node):
node.last = bool(node.getProp('init'))
def step(self, node):
val = node.getIn('I')
if node.getProp('falling'):
node.setOut('Q', node.last and not val)
else:
node.setOut('Q', val and not node.last)
node.last = val
class LevelToggle(SimSchema):
'''Toggles Q between True and False while I is a boolean truth. (Use EdgeDetect for an edge toggle.)'''
def __init__(self):
SimSchema.__init__(self, 'Logic', 'LTGL', [
Connector('I', bool),
], [
Connector('Q', bool),
], [
Property('init', int, 0)
])
def reset(self, node):
node.value = bool(node.getProp('init'))
def step(self, node):
if node.getIn('I'):
node.value = not node.value
node.setOut('Q', node.value)
################################################################################
class ToInteger(SimSchema):
'''Casts input I to an integer.'''
def __init__(self):
SimSchema.__init__(self, 'Conversion', '2INT', [
Connector('I'),
], [
Connector('Q', int),
])
def step(self, node):
node.setOut('Q', int(node.getIn('I')))
class ToString(SimSchema):
'''Casts input I to a string.'''
def __init__(self):
SimSchema.__init__(self, 'Conversion', '2STR', [
Connector('I'),
], [
Connector('Q', str),
])
def step(self, node):
node.setOut('Q', str(node.getIn('I')))
class ToCharacter(SimSchema):
'''Casts I to a string consisting of a sole character or codepoint of I's value.'''
def __init__(self):
SimSchema.__init__(self, 'Conversion', '2CHR', [
Connector('I', int),
], [
Connector('Q', str),
])
def step(self, node):
node.setOut('Q', chr(node.getIn('I')))
################################################################################
class FileWrite(SimSchema):
'''Writes to the beginning of, or append to, `file' the string value of I on each tick, depending on the value of `append', and closes the file if `close' is a boolean truth.'''
def __init__(self):
SimSchema.__init__(self, 'Files', 'FIWR', [
Connector('I'),
], [], [
Property('file', str, ''),
Property('append', int, 0),
Property('close', int, 0),
])
def reset(self, node):
node.fp = open(node.getProp('file'), 'a' if node.getProp('append') else 'w')
def step(self, node):
if node.getProp('close'):
self.reset(node)
if not node.getProp('append'):
try:
node.fp.seek(0, 0)
except OSError:
node.fp = open(node.getProp('file'), 'w')
node.fp.write(str(node.getIn('I')))
if node.getProp('close'):
node.fp.close()
class FileRead(SimSchema):
'''Reads strings from a file, delimited by `delim', or in lines if `delim' is empty. Emits the first such block at the beginning of a simulation, and advances to the next block whenever C is a truth. If B is a truth, seeks to byte I of the file and emits the next record; if R is a truth, seeks to record I of the file and emits it.'''
def __init__(self):
SimSchema.__init__(self, 'Files', 'FIRD', [
Connector('C', bool),
Connector('I', int),
Connector('B', bool),
Connector('R', bool),
], [
Connector('Q', str),
], [
Property('file', str, ''),
Property('delim', str, ''),
])
def reset(self, node):
node.fp = open(node.getProp('file'), 'r')
node.buf = self.nextbuf(node)
def nextbuf(self, node):
delim = node.getProp('delim')
if not delim:
return node.fp.readline()
buf = ''
while True:
pos = node.tell()
data = node.fp.read(1024)
orig = len(buf)
buf += data
try:
idx = data.index(delim)
except ValueError:
pass
else:
break
buf = buf[:orig + idx]
node.fp.seek(pos + idx + len(delim))
return buf
def step(self, node):
if node.getIn('B'):
node.fp.seek(node.getIn('I'))
node.buf = self.nextbuf(node)
if node.getIn('R'):
node.fp.seek(0)
for i in range(node.getIn('I')):
self.nextbuf(node)
node.buf = self.nextbuf(node)
if node.getIn('C'):
node.buf = self.nextbuf(node)
node.setOut('Q', node.buf)
################################################################################
class Buffer(SimSchema):
'''Emits its input, delayed by one simulation tick. This may be used in the default stepper (ParallelStepper) to synchronize inputs, and is otherwise useless. DelayBuffer provides more flexibility.'''
def __init__(self):
SimSchema.__init__(self, 'Generic', 'BUF', [
Connector('I'),
], [
Connector('Q'),
])
def step(self, node):
node.setOut('Q', node.getIn('I'))
class DelayBuffer(SimSchema):
'''Emits its input, delayed by `delay' simulation ticks. This may be used in the default stepper (ParallelStepper) to synchronize inputs.'''
def __init__(self):
SimSchema.__init__(self, 'Generic', 'DLAY', [
Connector('I'),
], [
Connector('Q'),
], [
Property('delay', int, 1, min=1)
])
def reset(self, node):
if node.getProp('delay') > 1:
node.delay_buffer = [None] * (node.getProp('delay') - 1)
node.delay_index = 0
def step(self, node):
if node.getProp('delay') <= 1:
node.setOut('Q', node.getIn('I'))
return
node.delay_buffer[node.delay_index] = node.getIn('I')
node.delay_index += 1
if node.delay_index >= len(node.delay_buffer):
node.delay_index = 0
node.setOut('Q', node.delay_buffer[node.delay_index])
node.delay_index += 1
if node.delay_index >= len(node.delay_buffer):
node.delay_index = 0
class Printer(SimSchema):
'''Prints all of its input values to stdout.'''
def __init__(self):
SimSchema.__init__(self, 'Generic', 'PRINT', [
Connector('I', None, False),
], [])
def step(self, node):
print(*node.getIns('I'))
class PrintIf(SimSchema):
'''Prints all of the input values of I (in no particular order) to stdout if C is a boolean truth.'''
def __init__(self):
SimSchema.__init__(self, 'Generic', 'PRIF', [
Connector('I', None, False),
Connector('C', bool),
], [])
def step(self, node):
if node.getIn('C'):
print(*node.getIns('I'))
class IsNull(SimSchema):
'''Emits truth if I is a null value, and false otherwise.'''
def __init__(self):
SimSchema.__init__(self, 'Generic', 'NUL?', [
Connector('I'),
], [
Connector('Q', bool),
])
def step(self, node):
node.setOut('Q', node.getIn('I') is None)
class SetBus(SimSchema):
'''Sets the simulator bus named `bus' to the input value.'''
def __init__(self):
SimSchema.__init__(self, 'Generic', 'SBUS', [Connector('I')], [], [Property('bus', str, '')])
def step(self, node):
node.graph.setBus(node.getProp('bus'), node.getIn('I'))
class GetBus(SimSchema):
'''Gets the value of the simulator bus named `bus'.'''
def __init__(self):
SimSchema.__init__(self, 'Generic', 'GBUS', [], [Connector('Q')], [Property('bus', str, '')])
def step(self, node):
node.setOut('Q', node.graph.getBus(node.getProp('bus')))
class Python(SimSchema):
'''Evaluates `expr' as Python code, and emits the result to Q. `invars' is a comma-separated list of additional inputs to this node whose values will be available as variables of the same name in the expression. `invars' should not contain whitespace or other characters illegal in identifiers.'''
def __init__(self):
SimSchema.__init__(self, 'Generic', 'PY', [], [Connector('Q')], [
Property('expr', str, ''),
Property('invars', str, ''),
])
def getIns(self, node):
return [Connector(name) for name in node.getProp('invars', '').split(',')]
def getInMap(self, node):
return {con.name: con for con in self.getIns(node)}
def step(self, node):
ins = {name: node.getIn(name) for name in node.getProp('invars', '').split(',')}
node.setOut('Q', eval(node.getProp('expr'), globals(), ins))
class Default(SimSchema):
'''Emits its input I, so long as it is not the null value (None); otherwise, emits D.'''
def __init__(self):
SimSchema.__init__(self, 'Generic', 'DFLT', [
Connector('I'),
Connector('D'),
], [
Connector('Q'),
])
def step(self, node):
inval = node.getIn('I')
if inval is None:
node.setOut('Q', node.getIn('D'))
else:
node.setOut('Q', inval)
class Null(SimSchema):
'''Emits the null value (None). Note that this is equivalent to leaving an input disconnected.'''
def __init__(self):
SimSchema.__init__(self, 'Generic', 'NULL', [], [Connector('Q')])
def step(self, node):
pass
class Select(SimSchema):
'''If C is a boolean truth, emit T. Otherwise, emit F.'''
def __init__(self):
SimSchema.__init__(self, 'Generic', 'SLCT', [
Connector('T'),
Connector('F'),
Connector('C', bool),
], [
Connector('Q'),
])
def step(self, node):
cond = node.getIn('C')
if cond:
node.setOut('Q', node.getIn('T'))
else:
node.setOut('Q', node.getIn('F'))
class End(SimSchema):
'''When C is a boolean truth, ends the simulation.'''
def __init__(self):
SimSchema.__init__(self, 'Generic', 'END', [Connector('C', bool)], [])
def step(self, node):
if node.getIn('C'):
node.graph.running = False
################################################################################
class Sine(SimSchema):
'''Computes the sine in radians of I.'''
def __init__(self):
SimSchema.__init__(self, 'Trigonometry', 'SIN', [
Connector('I', float),
], [
Connector('Q', float),
])
def step(self, node):
node.setOut('Q', math.sin(node.getIn('I')))
class Cosine(SimSchema):
'''Computes the cosine in radians of I.'''
def __init__(self):
SimSchema.__init__(self, 'Trigonometry', 'COS', [
Connector('I', float),
], [
Connector('Q', float),
])
def step(self, node):
node.setOut('Q', math.cos(node.getIn('I')))
class Tangent(SimSchema):
'''Computes the tangent in radians of I.'''
def __init__(self):
SimSchema.__init__(self, 'Trigonometry', 'TAN', [
Connector('I', float),
], [
Connector('Q', float),
])
def step(self, node):
node.setOut('Q', math.tan(node.getIn('I')))
################################################################################
class Ticks(SimSchema):
'''Returns the number of ticks this simulation has run for, starting at 0 on the first run or at the beginning of an aggregate subsimulation.'''
def __init__(self):
SimSchema.__init__(self, 'Time', 'TICK', [], [Connector('Q', int)])
def step(self, node):
node.setOut('Q', node.graph.tick)
class Init(SimSchema):
'''Emits True on the first tick of a simulation (including the first tick of an aggregate subsimulation), and False otherwise.'''
def __init__(self):
SimSchema.__init__(self, 'Time', 'INIT', [], [Connector('Q', bool)])
def step(self, node):
node.setOut('Q', node.graph.tick == 0)
class Time(SimSchema):
'''Returns real time in seconds since the epoch.'''
def __init__(self):
SimSchema.__init__(self, 'Time', 'TIME', [], [Connector('Q', float)])
def step(self, node):
node.setOut('Q', time.time())
class PerformanceCounter(SimSchema):
'''Returns a high-precision counter in seconds with an arbitrary epoch. The resolution is fine enough that "parallel" invocations of independent nodes will have (subtle) different values.'''
def __init__(self):
SimSchema.__init__(self, 'Time', 'PCNT', [], [Connector('Q', float)])
def step(self, node):
node.setOut('Q', time.perf_counter())
class ProcessClock(SimSchema):
'''Returns a counter in seconds whose epoch is the start of the process. The resolution is in units used by the operating system's process scheduler. Note that simulation may not necessarily start at 0 seconds, due to setup or simulation in another process.'''
def __init__(self):
SimSchema.__init__(self, 'Time', 'PCLK', [], [Connector('Q', float)])
def step(self, node):
node.setOut('Q', time.clock())
class Start(SimSchema):
'''Returns the real time (as with Time) that this simulation was last reset (i.e., when its tick count was zeroed).'''
def __init__(self):
SimSchema.__init__(self, 'Time', 'START', [], [Connector('Q', float)])
def step(self, node):
node.setOut('Q', node.graph.starttime)
class Integral(SimSchema):
'''Maintains an internal value (initially `init') and changes the value every tick by d, which is in units per second. If R is a boolean truth, this internal value is unconditionally set to V. Emits the internal value.'''
def __init__(self):
SimSchema.__init__(self, 'Time', 'INTG', [
Connector('d', float),
Connector('V', float),
Connector('R', bool),
], [
Connector('Q', float),
], [
Property('init', float, 0.0),
])
def reset(self, node):
node.value = node.getProp('init')
node.lasttime = time.perf_counter()
def step(self, node):
if node.getIn('R'):
node.value = node.getIn('V')
else:
node.value += node.getIn('d') * (time.perf_counter() - node.lasttime)
node.setOut('Q', node.value)
node.lasttime = time.perf_counter()
class Accumulator(SimSchema):
'''Maintains an internal value (initially `init') and changes the value every tick by d. If R is a boolean truth, this internal value is unconditionally set to V. Emits the internal value.'''
def __init__(self):
SimSchema.__init__(self, 'Time', 'ACCM', [
Connector('d', float),
Connector('V', float),
Connector('R', bool),
], [
Connector('Q', float),
], [
Property('init', float, 0.0),
])
def reset(self, node):
node.value = node.getProp('init')
def step(self, node):
if node.getIn('R'):
node.value = node.getIn('V')
else:
node.value += node.getIn('d')
node.setOut('Q', node.value)
class Derivative(SimSchema):
'''Takes the delta (as with Delta) between I and its previous value (initially `init'), and divides it by the change in time, giving a result in units per second.'''
def __init__(self):
SimSchema.__init__(self, 'Time', 'DERV', [
Connector('I', float),
], [
Connector('Q', float),
], [
Property('init', float, 0.0),
])
def reset(self, node):
node.value = node.getProp('init')
node.lasttime = time.perf_counter()
def step(self, node):
value = node.getIn('I')
node.setOut('Q', (value - node.value) / (time.perf_counter() - node.lasttime))
node.value = value
node.lasttime = time.perf_counter()
class Delta(SimSchema):
'''Takes the difference between I and its value on the previous tick (initially `init').'''
def __init__(self):
SimSchema.__init__(self, 'Time', 'DELT', [
Connector('I', float),
], [
Connector('Q', float),
], [
Property('init', float, 0.0)
])
def reset(self, node):
node.value = node.getProp('init')
def step(self, node):
value = node.getIn('I')
delta = value - node.value
node.value = value
node.setOut('Q', delta)
class RunningMaximum(SimSchema):
'''Maintains the running maximum of its input values over time. Initially, or if R is a boolean truth, it resets immediately to the value of its input.'''
def __init__(self):
SimSchema.__init__(self, 'Time', 'RMAX', [
Connector('I', float),
Connector('R', bool),
], [
Connector('Q', float),
])
def reset(self, node):
node.value = None
def step(self, node):
if node.getIn('R') or node.value is None:
node.value = node.getIn('I')
else:
node.value = max(node.value, node.getIn('I'))
node.setOut('Q', node.value)
class RunningMinimum(SimSchema):
'''Maintains the running minimum of its input values over time. Initially, or if R is a boolean truth, it resets immediately to the value of its input.'''
def __init__(self):
SimSchema.__init__(self, 'Time', 'RMIN', [
Connector('I', float),
Connector('R', bool),
], [
Connector('Q', float),
])
def reset(self, node):
node.value = None
def step(self, node):
if node.getIn('R') or node.value is None:
node.value = node.getIn('I')
else:
node.value = min(node.value, node.getIn('I'))
node.setOut('Q', node.value)
class RunningAverage(SimSchema):
'''Maintains the running average of its input values over time. Initially, or if R is a boolean truth, it resets immediately to the value of its input.'''
def __init__(self):
SimSchema.__init__(self, 'Time', 'RAVG', [
Connector('I', float),
Connector('R', bool),
], [
Connector('Q', float),
])
def reset(self, node):
node.value = None
node.counter = 0
def step(self, node):
if node.getIn('R') or node.value is None:
node.value = node.getIn('I')
node.counter = 1
else:
node.counter += 1
node.value = ((node.counter - 1) * node.value + node.getIn('I')) / node.counter
node.setOut('Q', node.value)
class LevelLatch(SimSchema):
'''When C is a boolean truth, outputs I; otherwise, emits the last value of I for which C was true.'''
def __init__(self):
SimSchema.__init__(self, 'Time', 'LLCH', [
Connector('I'),
Connector('C', bool),
], [
Connector('Q'),
])
def reset(self, node):
node.value = None
def step(self, node):
if node.getIn('C'):
node.value = node.getIn('I')
node.setOut('Q', node.value)
class SRLatch(SimSchema):
'''When S but not R, sets an internal value to True; when R but not S, sets an internal value to false; emits the internal value.'''
def __init__(self):
SimSchema.__init__(self, 'Time', 'SRLCH', [
Connector('S', bool),
Connector('R', bool),
], [
Connector('Q', bool),
], [
Property('init', int, 0),
])
def reset(self, node):
node.value = bool(node.getProp('init'))
def step(self, node):
r, s = node.getIn('R'), node.getIn('S')
if s and not r:
node.value = True
if r and not s:
node.value = False
node.setOut('Q', node.value)
class RandomAccessMemory(SimSchema):
'''Maintains `cells' internal values, all initially null, and emits them as a list. When W is a truth, writes V to the Ith index of the internal memory.'''
def __init__(self):
SimSchema.__init__(self, 'Time', 'RAM', [
Connector('W', bool),
Connector('V'),
Connector('I', int),
], [
Connector('Q', list),
], [
Property('cells', int, 16),
])
def reset(self, node):
node.mem = [None] * node.getProp('cells')
def step(self, node):
if node.getIn('W'):
node.mem[node.getIn('I')] = node.getIn('V')
node.setOut('Q', node.mem)
class AssociativeMemory(SimSchema):
'''Maintains an internal mapping, and emits it; when W is a truth, associates K to V.'''
def __init__(self):
SimSchema.__init__(self, 'Time', 'ASM', [
Connector('W', bool),
Connector('K'),
Connector('V'),
], [
Connector('Q', dict),
])
def reset(self, node):
node.mem = {}
def step(self, node):
if node.getIn('W'):
node.mem[node.getIn('K')] = node.getIn('V')
node.setOut('Q', node.mem)
################################################################################
class ListGetIndex(SimSchema):
'''Emits the element at index I of list L. If I is out of range, emits D instead. Non-numeric values of I (including null) will emit the first element of the list.'''
def __init__(self):
SimSchema.__init__(self, 'Sequences', 'LGIX', [
Connector('L', list),
Connector('I', int),
Connector('D'),