Repository navigation
Expand file tree
/
Copy pathsimulation.py
More file actions
1672 lines (1322 loc) · 62.6 KB
/
Copy pathsimulation.py
File metadata and controls
1672 lines (1322 loc) · 62.6 KB
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
"""
A general-purpose Simulation class for discrete events.
The Simulation object is the central object of a simulation. It
handles the simulation clock time and maintains communication between
the components of the simulation.
A simulation is structured as a directed graph of event-processing
nodes called EventProcessors (EPs). EventProcessors generate
data-carrying Events, which are routed through the graph to other
EventProcessors via delayed connections. Most objects in the
simulation will be a subclass of EventProcessor, customized to provide
some specific behavior.
There are different subclasses of Event, each doing different types of
computation, and each can contain any arbitrary Python data. A
simulation begins by giving each EventProcessor an opportunity to send
any initial events. It then proceeds by processing and delivering
events to EventProcessors in time order. After all events for the
current time are processed, the simulation gives each EventProcessor a
chance to do any final computation, after which simulation time skips
to the time of the earliest event remaining in the queue.
PORTS
All connections between EPs are tagged with a source port and a
destination port. Ports are internal addresses that EPs can use to
distinguish between inputs and outputs. A port specifier can be any
hashable Python object. If not specified, the input and output ports
for a connection default to None.
src_ports distinguish different types of output that an EP may
produce. When sending output, the EP must call self.send_output()
separately for each port. dest_ports distinguish different types of
input an EP may receive and process. The EP is free to interpret the
input port designation on an incoming event in any way it chooses.
An example dest_port might be for an EP that receives 'ordinary'
neural activity on the default port, and receives a separate
modulatory signal that influences learning. The originator of the
modulatory signal might have a connection to the EP with dest_port =
'Modulation'. Multiple ports can be grouped by a dest EP by assuming
a convention that the keys are tuples,
e.g. ('JointNormalize','Group1'), ('JointNormalize','Group2').
An example src_port use might be an EP that sends different events to
itself than it sends out to other EPs. In this case the self
connections might have src_port = 'Recurrent', and probably also a
special dest_port.
"""
import param
from copy import copy, deepcopy
import time
import bisect
from holoviews.interface.collector import AttrDict
#: Default path to the current simulation, from main
#: Only to be used by script_repr(), to allow it to generate
#: a runnable script
_simulation_path="topo.sim"
class EventProcessor(param.Parameterized):
"""
Base class for EventProcessors, i.e. objects that can accept and
handle events. This base class handles the basic mechanics of
connections and sending events, and stores both incoming and outgoing
connections.
The dest_ports attribute specifies which dest_ports are supported
by this class; subclasses can augment or change this list if they
wish. The special value dest_ports=None means to accept
connections to any dest_port, while dest_ports=[None,'Trigger']
means that only connections to port None or port 'Trigger' are
accepted.
Similarly, the src_ports attribute specifies which src_ports will
be given output by this class.
"""
__abstract = True
dest_ports=[None]
src_ports=[None]
def __init__(self,**params):
"""
Create an EventProcessor.
Note that just creating an EventProcessor does not mean it is
part of the simulation (i.e. it is not in the simulation's list
of EventProcessors, and it will not have its start() method called).
To add an EventProcessor e to a simulation s, simply do
s['name_of_e']=e. At this point, e's 'name' attribute will be set
to 'name_of_e'.
"""
super(EventProcessor,self).__init__(**params)
# A subclass could use another data stucture to optimize operations
# specific to itself, if it also overrides _dest_connect().
self.in_connections = []
self.out_connections = []
self.simulation = None
def _port_match(self,key,portlist):
"""
Returns True if the given key matches any port on the given list.
In the default implementation, a port is considered a match if
the port is == to the key, but subclasses of EventProcessor can
override this to allow weaker forms of matching.
"""
return key in portlist
# if extra parameters are required for an EP subclass, a
# dictionary could be added to Simulation.connect() to hold
# them, and passed on here
def _src_connect(self,conn):
"""
Add the specified connection to the list of outgoing connections.
Should only be called from Simulation.connect().
"""
if self.src_ports and not self._port_match(conn.src_port,self.src_ports):
raise ValueError("%s is not on the list of ports provided for outgoing connections for %s: %s." %
(str(conn.src_port), self.__class__, str(self.src_ports)))
# CB: outgoing connection must be uniquely named among others
# going to the same destination.
for existing_connection in self.out_connections:
if existing_connection.name==conn.name and existing_connection.dest==conn.dest:
raise ValueError('A connection out of an EventProcessor must have a unique name among connections to a particular destination; "%s" out of %s into %s already exists'%(conn.name,conn.dest,self.name))
# CB: alternative: outgoing connection must have a unique name
## for existing_connection in self.out_connections:
## if existing_connection.name==conn.name:
## raise ValueError('A connection out of an EventProcessor must have a unique name; "%s" out of %s already exists'%(conn.name,self.name))
self.out_connections.append(conn)
def _dest_connect(self,conn):
"""
Add the specified connection to the list of incoming connections.
Should only be called from Simulation.connect().
"""
if self.dest_ports and not self._port_match(conn.dest_port,self.dest_ports):
raise ValueError("%s is not on the list of ports allowed for incoming connections for %s: %s." %
(str(conn.dest_port), self.__class__, str(self.dest_ports)))
for existing_connection in self.in_connections:
if existing_connection.name == conn.name:
raise ValueError('A connection into an EventProcessor must have a unique name; "%s" into %s already exists'%(conn.name,self.name))
self.in_connections.append(conn)
def __dir__(self):
"""
Extend dir() to include in_connections of an EventProcessor.
Useful for software that examines the list of possible
in_connections, such as tab completion in IPython.
"""
default_dir = dir(type(self)) + list(self.__dict__)
return sorted(set(default_dir + [conn.name for conn in self.in_connections]))
def __getattr__(self, name):
"""
Provide a simpler attribute-like syntax for accessing the
in_connections of an EventProcessor (e.g. obj.conn, for
in_connection "conn" of EventProcessor obj).
"""
for conn in self.in_connections:
if conn.name == name: return conn
raise AttributeError
def start(self):
"""
Called by the simulation when the EventProcessor is added to
the simulation.
If an EventProcessor needs to have any code run when it is
added to the simulation, the code can be put into this method
in the subclass.
"""
pass
### JABALERT: Should change send_output to accept a list of src_ports, not a single src_port.
def send_output(self,src_port=None,data=None):
"""
Send some data out to all connections on the given src_port.
The data is deepcopied before it is sent out, to ensure that
future changes to the data are not reflected in events from
the past.
"""
out_conns_on_src_port = [conn for conn in self.out_connections
if self._port_match(conn.src_port,[src_port])]
data=deepcopy(data)
for conn in out_conns_on_src_port:
#self.verbose("Sending output on src_port %s via connection %s to %s" % (str(src_port), conn.name, conn.dest.name))
e=EPConnectionEvent(self.simulation.convert_to_time_type(conn.delay)+self.simulation.time(),conn,data,deep_copy=False)
self.simulation.enqueue_event(e)
def input_event(self,conn,data):
"""
Called by the simulation when an EPConnectionEvent is delivered;
the EventProcessor should process the data somehow.
"""
raise NotImplementedError
def process_current_time(self):
"""
Called by the simulation before advancing the simulation
time. Allows the event processor to do any computation that
requires that all events for this time have been delivered.
Computations performed in this method should not generate any
events with a zero time delay, or else causality could be
violated. (By default, does nothing.)
"""
pass
def script_repr(self,imports=[],prefix=" "):
"""Generate a runnable command for creating this EventProcessor."""
return _simulation_path+"['"+self.name+"']="+\
super(EventProcessor,self).script_repr(imports=imports,prefix=prefix)
class EventProcessorParameter(param.Parameter):
"""Parameter whose value can be any EventProcessor instance."""
def __init__(self,default=EventProcessor(),**params):
super(EventProcessorParameter,self).__init__(default=default,**params)
def __set__(self,obj,val):
if not isinstance(val,EventProcessor):
raise ValueError("Parameter must be an EventProcessor.")
else:
super(EventProcessorParameter,self).__set__(obj,val)
from param import parameterized
class EPConnection(param.Parameterized):
"""
EPConnection stores basic information for a connection between
two EventProcessors.
"""
## JPALERT: This type-checking is redundant, since
## Simulation.connect() only allows the user to create connections
## between existing simulation objects, which must be EPs. Type
## checking here means that it is impossible to ever instantiate
## an EPConnection in any situation (including debugging) w/o
## making src and dest be EPs. However, there is nothing I can
## find that requires that the src or dest be EPs. While some
## *subclasses* of EPConnection (such as Projection) do require
## that their src and dest support the interfaces of some
## *subclasses* of EventProcessor (e.g. Sheet.activity), there is
## no reason that those objects have to be EPs, per se. IMO,
## excessive type checking removes much of the power of using a
## dynamic language like Python.
## src = EventProcessorParameter(default=None,constant=True,precedence=0.10,doc=
## """The EventProcessor from which messages originate.""")
## dest = EventProcessorParameter(default=None,constant=True,precedence=0.11,doc=
## """The EventProcessor to which messages are delivered.""")
src = param.Parameter(default=None,constant=True,precedence=0.10,doc=
"""The EventProcessor from which messages originate.""")
dest = param.Parameter(default=None,constant=True,precedence=0.11,doc=
"""The EventProcessor to which messages are delivered.""")
src_port = param.Parameter(default=None,precedence=0.20,doc=
"""
Identifier that can be used to distinguish different types of outgoing connections.
EventProcessors that generate only a single type of
outgoing event will typically use a src_port of None. However,
if multiple types of communication are meaningful, the
EventProcessor can accept other values for src_port. It is up
to the src EventProcessor to deliver appropriate data to each
port, and to declare what will be sent over that port.
""")
dest_port = param.Parameter(default=None,precedence=0.21,doc=
"""
Identifier that can be used to distinguish different types of incoming connections.
EventProcessors that accept only a single type of incoming
event will typically use a src_port of None. However, if
multiple types of communication are meaningful, the
EventProcessor can accept other values for dest_port. It is up
to the dest EventProcessor to process the data appropriately
for each port, and to define what is expected to be sent to
that port.
""")
# Should the lower bound be exclusive?
delay = param.Number(default=0.05,bounds=(0,None),doc="""
Simulation time between generation of an Event by the src and delivery to the dest.
Should normally be nonzero, to represent a causal with a well-defined ordering
of events.""")
private = param.Boolean(default=False,doc=
"""Set to true if this connection is for internal use only, not to be manipulated by a user.""")
# CEBALERT: should be reimplemented. It's difficult to understand,
# and contains the same code twice. But it does work.
def remove(self):
"""
Remove this connection from its src's list of out_connections and its
dest's list of in_connections.
"""
# remove from EPs that have this as in_connection
i = 0
to_del = []
for in_conn in self.dest.in_connections:
if in_conn is self:
to_del.append(i)
i+=1
for i in to_del:
del self.dest.in_connections[i]
# remove from EPs that have this as out_connection
i = 0
to_del = []
for out_conn in self.src.out_connections:
if out_conn is self:
to_del.append(i)
i+=1
for i in to_del:
del self.src.out_connections[i]
def script_repr(self,imports=[],prefix=" "):
"""Generate a runnable command for creating this connection."""
if self.private:
return ""
settings=[]
for name,val in self.get_param_values():
try: # There may be a better way to figure out which parameters specify classes
if issubclass(val,object):
rep=val.__name__
# Generate import statement
cls = val.__name__
mod = val.__module__
imports.append("from %s import %s" % (mod,cls))
except TypeError:
if name=="src" or name=="dest":
rep=None
else:
rep = parameterized.script_repr(val,imports,prefix,settings)
if rep is not None:
settings.append('%s=%s' % (name,rep))
# add import statement
cls = self.__class__.__name__
mod = self.__module__
imports.append("from %s import %s" % (mod,cls))
return _simulation_path+".connect('"+self.src.name+"','"+self.dest.name+ \
"',connection_type="+self.__class__.__name__+ \
",\n"+prefix+(",\n"+prefix).join(settings) + ")"
# CB: event is not a Parameterized because of a (small) performance hit.
class Event(object):
"""Hierarchy of classes for storing simulation events of various types."""
def __init__(self,time):
self.time = time
def __call__(self,sim):
"""
Cause some computation to be performed, deliver a message, etc.,
as appropriate for each subtype of Event. Should be passed the
simulation object, to allow access to .time() etc.
"""
raise NotImplementedError
def __cmp__(self,ev):
"""
Implements event comparison by time, allowing sorting,
and queue maintenance using bisect module or minheap
implementations, if needed.
NOTE: identity comparisons should always be done using the
'is' operator, not '=='.
"""
if self.time > ev.time:
return 1
elif self.time < ev.time:
return -1
else:
return 0
class EPConnectionEvent(Event):
"""
An Event for delivery to an EPConnection.
Provides access to a data field, which can be used for anything
the src wants to provide, and a link to the connection over which
it has arrived, so that the dest can determine what to do with the
data.
By default, the data is deepcopied before being added to this
instance for safety (e.g. so that future changes to data
structures do not affect messages arriving from the past).
However, if you can ensure that the copying is not
necessary (e.g. if you deepcoy before sending a set of
identical messages), then you can pass deep_copy=False
to avoid the copy.
"""
def __init__(self,time,conn,data=None,deep_copy=True):
super(EPConnectionEvent,self).__init__(time)
assert isinstance(conn,EPConnection)
self.data = deepcopy(data) if deep_copy else data
self.conn = conn
def __call__(self,sim):
self.conn.dest.input_event(self.conn,self.data)
def __repr__(self):
return "EPConnectionEvent(time="+`self.time`+",conn="+`self.conn`+")"
class CommandEvent(Event):
"""An Event consisting of a command string to execute."""
def __init__(self,time,command_string):
"""
Add the event to the simulation.
Raises an exception if the command_string contains a syntax
error.
"""
self.command_string = command_string
self.__test()
super(CommandEvent,self).__init__(time)
def __repr__(self):
return "CommandEvent(time="+`self.time`+", command_string='"+self.command_string+"')"
def script_repr(self,imports=[],prefix=" "):
"""Generate a runnable command for creating this CommandEvent."""
return _simulation_path+'.schedule_command('\
+`self.time`+',"'+self.command_string+'")'
def __call__(self,sim):
"""
exec's the command_string in __main__.__dict__.
Be sure that any required items will be present in
__main__.__dict__; in particular, consider what will be present
after the network is saved and restored. For instance, results of
scripts you have run, or imports they make---all currently
available in __main__.__dict__---will not be saved with the
network.
"""
# Presumably here to avoid importing __main__ into the rest of the file
import __main__
param.Parameterized(name='CommandEvent').message("Running command %s",
self.command_string)
try:
exec self.command_string in __main__.__dict__
except:
print "Error in scheduled command:"
raise
def __test(self):
"""
Check for SyntaxErrors in the command.
"""
try:
compile(self.command_string,"CommandString","single")
except SyntaxError:
print "Error in scheduled command:"
raise
class FunctionEvent(Event):
"""
Event that executes a given function function(*args,**kw).
"""
def __init__(self,time,fn,*args,**kw):
super(FunctionEvent,self).__init__(time)
self.fn = fn
self.args = args
self.kw = kw
def __call__(self,sim):
self.fn(*self.args,**self.kw)
def __repr__(self):
return 'FunctionEvent(%s,%s,*%s,**%s)' % (`self.time`,`self.fn`,`self.args`,`self.kw`)
class EventSequence(Event):
"""
Event that contains a sequence of other events to be scheduled and
executed.
The .time attributes of the events in the sequence are interpreted
as offsets relative to the start time of the sequence itself.
"""
def __init__(self,time,sequence):
super(EventSequence,self).__init__(time)
self.sequence = sequence
def __call__(self,sim):
# Enqueue all the events in the sequence, offsetting their
# times from the current time
sched_time = sim.time()
for ev in self.sequence:
new_ev = copy(ev)
sched_time += ev.time
new_ev.time = sched_time
sim.enqueue_event(new_ev)
def __repr__(self):
return 'EventSequence(%s,%s)' % (`self.time`,`self.sequence`)
class PeriodicEventSequence(EventSequence):
"""
An EventSequence that reschedules itself periodically
Takes a period argument that determines how often the sequence
will be scheduled. If the length of the sequence is longer than
the period, then the length of the sequence will be used as the period.
"""
## JPHACKALERT: This should really be refactored into a
## PeriodicEvent class that periodically executes a single event,
## then the user can construct a periodic sequence using a
## combination of PeriodicEvent and EventSequence. This would
## change the behavior if the sequence length is longer than the
## period, but I'm not sure how important that is, and it might
## actually be useful the other way.
def __init__(self,time,period,sequence):
super(PeriodicEventSequence,self).__init__(time,sequence)
self.period = period
def __call__(self,sim):
super(PeriodicEventSequence,self).__call__(sim)
# Find the timed length of the sequence
seq_length = sum(e.time for e in self.sequence)
if seq_length < self.period:
# If the sequence is shorter than the period, then reschedule
# the sequence to occur again after the period
self.time += self.period
else:
# If the sequence is longer than the period, then
# reschedule to start after the sequence ends.
self.time += seq_length
sim.enqueue_event(self)
def __repr__(self):
return 'PeriodicEventSequence(%s,%s,%s)' % (`self.time`,`self.period`,`self.sequence`)
# CB: code that previously existed in various places now collected
# together. The original timing code was not properly tested, and the
# current code has not been tested either: needs writing cleanly and
# testing. This whole class is pretty difficult to follow.
#
### JP: Is it possible that some or all of this can be more cleanly
### implemented using PeriodicEvents?
from math import floor
class SomeTimer(param.Parameterized):
"""
Provides a countdown timer for functions that run repeatedly.
There are two distinct ways to use the timer.
The first, via call_and_time(), is for calling some function every
specified number of steps for a specified duration. Currently
call_and_time() is used for timing calls to simulation.run() every
1.0 steps for 100 iterations. See the Simulation class for an
example of using the timer in this way.
The second, via call_fixed_num_times(), is for calling some
function repeatedly a specified number of times. A case to use
call_fixed_num_times() would be timing pattern presentations,
where the number of times the pattern_presenter will be called is
known in advance. Additionally, this method allows a list of
arguments to be passed to the function (in this case, the
permutation for each call).
"""
# * parameters to control formatting?
# * the parameter types for some of the following could be more specific
step = param.Parameter(default=2,doc=
"""Only relevant with call_and_time(), not call_fixed_num_times().
Each iteration, func is called as func(step).
For example, step=1 with func set to topo.sim.time would cause
the simulation time to advance once per iteration.
The default value (None) gives 50 iterations for any value of simulation_duration
passed to call_and_time(simulation_duration).""")
estimate_interval = param.Number(default=50,doc=
"""Interval in simulation time between estimates.""")
func = param.Parameter(default=None,instantiate=True,doc=
"""Function to be timed.""")
## func_args = Parameter(default=None,instantiate=True,doc=
## """Arguments passed to func at time of calling.""")
simulation_time_fn = param.Parameter(default=None,instantiate=True,doc=
"""Function that returns the simulation time.""")
real_time_fn = param.Parameter(default=time.time,instantiate=True,doc=
"""Function that returns the wallclock time.""")
receive_info = param.Parameter(default=[],instantiate=True,doc=
"""List of objects that will receive timing information.
Each must have a timing_info() method.""")
stop = param.Boolean(default=False,doc=
"""If set to True, execution of func (and timing) will cease at the end of
the current iteration.""")
def __pass_out_info(self,time,percent,name,duration,remaining):
[thing(time,percent,name,duration,remaining) for thing in self.receive_info]
# CB: this used to say how long the operation took (in wallclock time)
def __measure(self,fduration,step,arg_list=None):
if not arg_list:
# no list of arguments means not being called set number of times
fixed_num_calls = False
else:
fixed_num_calls = True
iters = int(floor(fduration/step))
recenttimes=[]
if not fixed_num_calls: arg_list=[step]*iters
simulation_starttime = self.simulation_time_fn()
self.stop = False
for i in xrange(iters):
recenttimes.append(self.real_time_fn())
length = len(recenttimes)
if (length>self.estimate_interval):
recenttimes.pop(0)
length-=1
self.func(arg_list[i])
percent = 100.0*i/iters
estimate = (iters-i)*(recenttimes[-1]-recenttimes[0])/length
self.__pass_out_info(time=self.simulation_time_fn(),
percent=percent,
name=self.func.__name__,
duration=fduration,
remaining=estimate)
## JABALERT: Needs to be fixed to avoid calling topo from base/
## HACK refresh windows for camera in simulation time
import topo
if hasattr(topo, 'guimain'):
topo.guimain.refresh_activity_windows()
##
if self.stop: break
if not self.stop:
if not fixed_num_calls:
# ensure specified duration has been respected, since code above might not
# complete specified duration (integer number of iterations)
leftover = fduration+simulation_starttime-self.simulation_time_fn()
if leftover>0: self.func(leftover)
percent = 100
self.__pass_out_info(time=self.simulation_time_fn(),
percent=percent,
name=self.func.__name__,
duration=fduration,
remaining=0)
def call_fixed_num_times(self,args_for_iterations):
"""
Call self.func(args_for_iterations[i]) for all i in args_for_iterations.
"""
self.__measure(len(args_for_iterations),1.0,arg_list=args_for_iterations)
def call_and_time(self,fduration):
"""
Call self.func(self.step or fduration/50.0) for fduration.
"""
# default to 50 steps unless someone set otherwise
step = self.step or fduration/50.0
self.__measure(fduration,step)
def update_timer(self,name,current_presentation,total_presentations):
if current_presentation == 0:
self.recenttimes=[]
if current_presentation == total_presentations-1:
percent = 100
estimate = 0
else:
self.recenttimes.append(self.real_time_fn())
length = len(self.recenttimes)
if (length>self.estimate_interval):
self.recenttimes.pop(0)
length-=1
try:
percent = 100.0*current_presentation/total_presentations
except:
percent = 100
estimate = (total_presentations-current_presentation)* \
(self.recenttimes[-1]-self.recenttimes[0])/length
self.__pass_out_info(time=current_presentation,
percent=percent,
name=name,
duration=total_presentations,
remaining=estimate)
# CEBALERT: This singleton-producing mechanism is pretty complicated,
# and it would be great if someone could simplify it. Getting all of
# the behavior we want for e.g. Simulation is tricky, but there are
# tests for it. Note that:
# (1) There should only ever be one single Simulation instance for
# which register is True. Creating, copying, and unpickling
# need to take this into account.
# (2) A Simulation instance for which register is False should
# behave the same as any normal Python object.
#
# For how to use, see topo.base.simulation.Simulation or
# topo.misc.commandline.GlobalParams.
class OptionalSingleton(object):
_inst = None
def __new__(cls,singleton):
"""
Return the single instance stored in _inst if singleton is
True; otherwise, return a new instance.
"""
if singleton:
if cls is not type(cls._inst):
cls._inst = object.__new__(cls)
cls._inst._singleton = True
return cls._inst
else:
new_inst = object.__new__(cls)
new_inst._singleton = False
return new_inst
def __getnewargs__(self):
return (self._singleton,)
def __copy__(self):
# An OptionalSingleton(singleton=False) instance is copied, while the
# OptionalSingleton(singleton=True) instance is not copied.
if self._singleton:
return self
else:
# Ideally we'd just call "object.__copy__", but apparently
# there's no such method.
# CB: I *think* this is how to do a copy. Any better
# ideas? Python's copy.copy() function calls an object's
# __reduce__ method and then reconstructs the object from
# that using copy._reconstruct().
new_obj = self.__class__(self._singleton)
new_obj.__dict__ = copy(self.__dict__)
return new_obj
def __deepcopy__(self,m):
if self._singleton:
return self
else:
new_obj = self.__class__(self._singleton)
new_obj.__dict__ = deepcopy(self.__dict__,m)
return new_obj
# CB: I might have bound __copy__ (& __deepcopy__) just to the
# Simulation(singleton=True) instance to avoid the Simulation
# class having a __copy__ method at all, but copy() only checks
# the *class* for the existence of __copy__.
# Simulation stores its events in a linear-time priority queue (i.e., a
# sorted list.) For efficiency, e.g. for spiking neuron simulations,
# we'll probably need to replace the linear priority queue with a more
# efficient one. Jeff has an O(log N) minheap implementation, but
# there are likely to be many others to select from.
#
class Simulation(param.Parameterized,OptionalSingleton):
"""
A simulation class that uses a simple sorted event list (instead of
e.g. a sched.scheduler object) to manage events and dispatching.
Simulation is a singleton: there is only one instance of
Simulation, no matter how many times it is instantiated.
"""
register = param.Boolean(default=True,constant=True,doc="""
Whether or not to register this Simulation. If True, this
Simulation (when created explicitly or when unpickled)
will replace any existing registered Simulation (if one exists).
Thus only one Simulation with register=True can exist at
any one time, which makes it simpler to handle defining
and reloading a series of simulations without polluting the
memory space with unused simulations.""")
startup_commands = param.Parameter(instantiate=True,default=[],doc="""
List of string commands that will be exec'd in
__main__.__dict__ (i.e. as if they were entered at the
command prompt) every time this simulation is unpickled
(and will be executed before the simulation is itself
unpickled).
For example, allows items to be imported before
scheduled_commands are run.
""")
time = param.Callable(default=param.Dynamic.time_fn, doc="""
The time object is a callable that can be set, incremented and
decremented with a chosen numeric type as necessary.
""")
time_printing_format = param.String("%(_time)09.2f",doc="""
Format string to be used when the simulation time must be
formatted as a string, e.g. for display or for basename().
When the string is evaluated, the time will be available as
the attribute '_time'.
""")
basename_format = param.String("%(name)s_%(timestr)s",doc="""
Format string to be used by the basename() function.
When the string is evaluated, the formatted time from
time_printing_format will be available as the attribute
'timestr'.
""")
eps_to_start = []
name = param.Parameter(constant=False)
forever = param.Infinity()
### Simulation(register=True) is a singleton
#
#
# There is only ever one instance of Simulation(register=True).
# This instance is stored in the '_inst' attribute; when __new__
# is called and register is True, this instance is created if it
# doesn't already exist, and returned otherwise. copying or
# deepcopying this instance returns the instance.
#
# For a Simulation with register False, calling __new__ results in
# a new object as usual for Python objects. copying and
# deepcopying returns a new Simulation with a copy or deepcopy
# (respectively) of the original Simulation's __dict__.
#
# See OptionalSingleton for more information.
def __new__(cls,*args,**kw):
# simulate behavior of a parameter for register
if 'register' in kw:
register = kw['register']
# this elif shouldn't be required, but is needed for
# unpickling: OptionalSingleton's __getnewargs__ is called
# with register as the first argument (I don't know how else
# to set register on unpickling).
elif len(args)==1:
register = args[0]
else:
register = cls.register
n = OptionalSingleton.__new__(cls,register)
# CEBALERT: without removing references to the Sheets from
# from instances of Slice, those instances of Slice and the
# Sheets they refer to are never garbage collected.
#
# This temporary implementation of cleanup code explicitly
# removes references to Sheets from Slice instances for
# typical simulations.
#
# 1: Better than having cleanup code here would be to make a
# change to Slice, so that a Slice either doesn't have a
# reference to a Sheet, or doesn't hold onto that reference.
#
# 2: Some cleanup code will always be required here in
# Simulation.__new__: As well as removing references to Sheets
# from Slices, it is also necessary to remove references to
# sheets from Simulation's lists of EPs - otherwise the sheets
# are not garbage collected and memory usage will go up every
# time a new Simulation is created. This cleanup must be in
# Simulation.__new__ so that it runs whenever a simulation is
# created or unpickled (it can't be done e.g. in
# load_snapshot).
#
# 3: this particular implementation assumes the only instances
# of Slice are in ConnectionFields, which is true for our
# simulations. (This won't matter when the slice cleanup
# becomes unnecessary.)
if hasattr(n,'_cleanup'):
n._cleanup()
# if we don't collect() here (exactly here - not in _cleanup,
# and not later), gc seems to lose track of some objects and
# there is still a (smaller) memory increase with every call
# to load_snapshot()
import gc
gc.collect()
return n
# CEBALERT: see gc alert in __new__()
def _cleanup(self):
# will always be required: in case eps haven't been started
# so are still in the list
if hasattr(self,'eps_to_start'):
self.eps_to_start[:]=[]
if hasattr(self,'_event_processors'):
for name,EP in self._event_processors.items():
for c in EP.in_connections:
if hasattr(c,'_cleanup'):
c._cleanup()
# will always be required
self._event_processors[name]=None
# (check when cleaning up existing mechanism for
# adding sheets e.g. sim['x']=sheet could first set
# sim['x'] to None if there is already a sheet with
# name x...)
# CEBALERT: if we're keeping this, should have a better name
def convert_to_time_type(self,time):
"""
Convert the supplied time to the Simulation's time_type.
"""
return (self.forever if time == self.forever else self.time.time_type(time))
# Note that __init__ can still be called after the
# Simulation(register=True) instance has been created. E.g. with
# Simulation.register is True,
# Simulation(name='A'); Simulation(name='B')
#
# would leave the single Simulation(register=True) instance with