Debian Codegraph @

pymusic/pymusic.pyx

raw
1 #
2 # distutils: language = c++
3 # cython: c_string_encoding = default
4
5 from libc.stdlib cimport malloc, free
6
7 import mpi4py.MPI as MPI
8 from six.moves import cPickle as pickle
9
10 ###########################################################
11
12 class MUSICError(Exception):
13 """
14 All exceptions in pymusic are MUSICError's
15 """
16 pass
17
18 class NoWidth(MUSICError):
19 """
20 Thrown if Port.width() is called, and port doesn't
21 have a width defined.
22 """
23 def __init__(self):
24 MUSICError.__init__(self, "No width defined")
25
26 class UndefinedConfig(MUSICError):
27 """
28 Thrown if a configuration value is requested
29 via Setup.config(varname) for a variable name
30 that has not been defined within the configuration.
31 """
32 def __init__(self, var):
33 MUSICError.__init__(
34 self,
35 "Config variable {} is not defined".
36 format(var)
37 )
38
39 ###########################################################
40
41 # """
42 # Just pass args as a named tuple for C functions that
43 # take the command line parameters:
44 # int argc
45 # char** argv
46 # argv = [exec, op[1], ..., op[argc-1], NULL]
47 # """
48 ctypedef struct Args:
49 int argc
50 char** argv
51
52 cdef Args argv_toc(list argv):
53 """
54 Convert an argv python list to a correct C argv & argc
55 values with null termination, returned as an Args tuple
56 """
57 cdef Args r
58 r.argc = len(argv)
59 if r.argc <= 0:
60 raise MUSICError("argv can't be empty")
61
62 r.argv = <char**> malloc((r.argc+1) * sizeof(char*))
63 if r.argv is NULL:
64 raise MUSICError("couldn't allocate argv")
65
66 cdef string
67 try:
68 r.argv[r.argc] = NULL
69 for i in range(0, r.argc):
70 s = argv[i].encode()
71 r.argv[i] = s
72 return r
73 except:
74 free(r.argv)
75 raise
76
77 ###########################################################
78
79 def predictRank(list argv=None):
80 """
81 Map into mpidep/predict_rank for config methods.
82 AP: What is this really used for?
83 """
84 cdef Args r = argv_toc(argv if argv is not None else
85 sys.argv)
86 return CPredictRank(r.argc, r.argv)
87
88 ###########################################################
89
90 cdef class Port(object):
91 """
92 Base Port class.
93
94 The underlying pointer is not deallocated here, since in MUSIC the
95 port is owned by Setup/Runtime. This does null the value when we
96 believe the underlying object may be deallocated by the
97 container.
98 """
99 def __cinit__(self):
100 """
101 When a Port object is created, it needs to have an underlying
102 C++ class assigned to ptr from a Setup.publish* method.
103 """
104 self.ptr = NULL
105
106 def __hash__(self):
107 """
108 Hash function: pointer value % to an int.
109 """
110 return <int><size_t> self.ptr
111
112 cpdef null(self):
113 """
114 When Setup or Runtime no longer needs ports and so may deallocate
115 them, we first must clear the references to them here. This
116 may be overridden to give up references to other members by
117 the descendants
118 """
119 self.ptr = NULL
120
121 def isConnected(self):
122 """
123 return True iff the port is actually connected via the config
124 file.
125 """
126 return self.ptr.isConnected()
127
128 def width(self):
129 """
130 Returns the width set in the MUSIC config file
131 which defines the number of indices transferred
132 along this port. If no width is defined, raise a NoWidth
133 exception.
134 """
135 if not self.ptr.hasWidth(): raise NoWidth()
136 return self.ptr.width()
137
138 cdef class ContInputPort(Port):
139 """
140 ContInputPort maps data indices between sources and sinks. This is
141 the sink side; source is ContOutputPort. Created by
142 Setup.publishContInputPort(portname).
143 """
144 def map(self,
145 object data,
146 int base=0,
147 object perm=None,
148 double delay=0,
149 cbool interpolate=True,
150 int maxBuffered=-1):
151 """
152 map data as source for this port. (Can you do a multiple mapping?)
153
154 object data: object to be shared that has a buffer interface.
155 That interface needs to be contiguous formed of
156 simple items that can be mapped to simple MPI
157 data types.
158 int base (=0), object perm (=None): used to construct an
159 IndexMap (with number of items in data). See that
160 class for more information. Defines mapping for data
161 between this input source and the output sinks.
162 double delay (=0): this is the delay of measurement relative
163 to "something" which I haven't been able to
164 figure out yet --- needs to be explained.
165 interpolate (=True): whether to do a linear interpolation of
166 the values that are being delayed. Once
167 again, needs to be better explained.
168 maxBuffered (=-1): buffer up to maxBuffered ticks. If -1, use
169 a "reasonable value" (???). What does this
170 mean on the input side?
171 """
172 cdef Buffer buf = Buffer(data)
173 cdef IndexMap imap = IndexMap(perm, base, buf.items)
174 cdef DataMap d = DataMap(buf, imap)
175 cdef CContInputPort* ptr = dc_CContInputPort(self.ptr)
176 mapImpl(ptr, d.ptr, delay, maxBuffered, interpolate)
177
178 cdef class ContOutputPort(Port):
179 """
180 ContOutputPort maps data indices between sources and sinks. This
181 is the source side; ContInputPort is the sink. Created by
182 Setup.publishContOutputPort(portname).
183 """
184 def map(self, object data,
185 int base=0, object perm=None,
186 int maxBuffered=-1):
187 """
188 map data as sink for this port. (Can you do a multiple mapping?)
189
190 object data: object to be shared that has a buffer interface.
191 That interface needs to be contiguous formed of
192 simple items that can be mapped to simple MPI
193 data types.
194 int base (=0), object perm (=None): used to construct an
195 IndexMap (with number of items in data). See that
196 class for more information. Defines mapping for data
197 between this input source and the output sinks.
198 maxBuffered (=-1): buffer up to maxBuffered ticks. If -1, use
199 a "reasonable value" (???).
200 """
201 cdef Buffer buf = Buffer(data)
202 cdef IndexMap imap = IndexMap(perm, base, buf.items)
203 cdef DataMap d = DataMap(buf, imap)
204 cdef CContOutputPort* ptr = dc_CContOutputPort(self.ptr)
205 mapImpl(ptr, d.ptr, maxBuffered)
206
207 cdef class EventInputPort(Port):
208 """
209 Event sink. Maps 'events' to handlers. Events are spike-like
210 events at a defined time associated with an id, either/or
211 global/local in some (unclear to me) way.
212
213 Since these 'events' must be protected from deallocation as long
214 as the port exists (until finalization), we keep a set of them
215 here and drop the reference when this object is null'd (events member).
216 """
217 def __cinit__(self):
218 """
219 Store a set of references to the event handlers
220 """
221 self.events = set()
222
223 cpdef null(self):
224 """
225 Not just null pointer, but give up the associated event
226 handlers.
227 """
228 Port.null(self)
229 self.events = None
230
231 def map(self, func, IndexType t,
232 double accLatency=0, int maxBuffered=-1,
233 object perm=None, int base=-1, int size=-1):
234 """
235 Map events to this sink.
236 func is:
237 void func(double value, IndexType GLOBAL|LOCAL, int index)
238 IndexType is (?) the index type to map the incoming sources
239 passed to the func (why, if we already know this?)
240 accLatency is the delivery delay relative to calculation time
241 (? is it ? What formula are we using here?)
242 maxBuffered is ticks to buffer
243 perm, base & size are passed to IndexMap
244 """
245 cdef IndexMap imap = IndexMap(perm, base, size)
246 cdef EventHandler eh = EventHandler(func, t)
247 cdef CEventInputPort* ptr = dc_CEventInputPort(self.ptr)
248 cdef CEventHandlerPtr hndl = getEventHandlerPtr(t, eh.ptr)
249 mapImpl(ptr, imap.ptr, t, hndl, accLatency, maxBuffered)
250 self.events.add(eh)
251
252 cdef class EventOutputPort(Port):
253 """
254 Map events from this sink. See EventInputPort for description of
255 events.
256 """
257 def map(self, IndexType t, int maxBuffered=-1,
258 object perm=None, int base=-1, int size=-1):
259 """
260 IndexType: LOCAL/GLOBAL
261 maxBuffered: tick to buffer (why on both sides?)
262 perm, base, size: define IndexMap (see that class)
263 """
264 cdef IndexMap m = IndexMap(perm, base, size)
265 cdef CEventOutputPort* ptr = dc_CEventOutputPort(self.ptr)
266 mapImpl(ptr, m.ptr, t, maxBuffered)
267
268 def insertEvent(self, double time, int index, IndexType t):
269 """
270 double time: time of event (must be during current tick)
271 int index: local or global index of event
272 IndexType t: LOCAL|GLOBAL
273 """
274 cdef CEventOutputPort* ptr = dc_CEventOutputPort(self.ptr)
275 insertEventImpl(ptr, time, index)
276
277 cdef class MessageInputPort(Port):
278 """
279 Maps 'events' to handlers.
280
281 Since these 'events' must be protected from deallocation as long
282 as the port exists (until finalization), we keep a set of them
283 here and drop the reference when this object is null'd.
284 """
285 def __cinit__(self):
286 self.events = set()
287
288 cpdef null(self):
289 """
290 Remember to remove the references to events...
291 """
292 Port.null(self)
293 self.events = None
294
295 def map(self, func, double accLatency=0, int maxBuffered=-1, bint pickled=True):
296 """
297 The message handling function.
298 func: callable object as follows
299 void func(double time, object msg):
300 time: the set insertion time of the message
301 msg: an object which may have been pickled and fed through music
302 accLatency(0): "acceptable latency" (???)
303 maxBuffered(-1): ticks that can be buffered (-1 means unknown
304 amount (???))
305 pickled(True): pickle objects on both ends; else, the object should be
306 a buffer object and we'll receive a bytearray
307 """
308 cdef MessageHandler eh = MessageHandler(func, pickled)
309 cdef CMessageInputPort* ptr = dc_CMessageInputPort(self.ptr)
310 mapImpl(ptr, eh.ptr, accLatency, maxBuffered)
311 self.events.add(eh)
312
313 cdef class MessageOutputPort(Port):
314 """
315 The source of "messages". A message is a python object that is
316 pickled and fed to the other end, associated with a time.
317 """
318 def map(self, int maxBuffered=-1, bint pickled=True):
319 """
320 map only sets the buffering ticks.
321 maxBuffered (-1): ticks to buffer (-1 means "reasonable" ???)
322 pickled (True): whether messages objects inserted her are automatically
323 pickled, else the object should be a buffer-type and
324 the other end will get a bytearray.
325 """
326 self.pickled = pickled
327 cdef CMessageOutputPort* ptr = dc_CMessageOutputPort(self.ptr)
328 mapImpl(ptr, maxBuffered)
329
330 def insertMessage(self, double time, object msg):
331 """
332 insert a python object as a message at a time during the
333 current tick.
334 time: ms times (??)
335 msg: a python object that can be cPickled if self.pickled == True
336 else something that has a buffer interface.
337 """
338 cdef CMessageOutputPort* ptr = dc_CMessageOutputPort(self.ptr)
339 cdef bytearray pmsg = \
340 <bytearray> pickle.dumps(msg, pickle.HIGHEST_PROTOCOL) \
341 if self.pickled \
342 else <bytearray> msg
343 ptr.insertMessage(time, <char*> pmsg, len(pmsg))
344
345 ###########################################################
346
347 import sys
348 cdef class Setup(object):
349 """
350 API to setup the music interface.
351 Becomes invalid after a Runtime object is created.
352 It gives access to config variables (*.music file),
353 and creates sinks and sources which can then be configured with
354 the respective map method of each.
355 """
356
357 def __cinit__(self, list argv=None, required=None):
358 """
359 Takes the command line arguments and the required threading
360 level.
361 string[] argv (None): comand line args; if None, use sys.argv
362 int required (None): the MPI threading level for MPI-2. If
363 None, don't set at all, but provided level in object set to
364 MPI_THREAD_SINGLE. Also stores command line arguments.
365 Calls CSetup object and connects with communicator.
366 """
367
368 cdef int argc
369 cdef char** argv_c
370 cdef int provided
371
372 cdef Args r = argv_toc(argv if argv is not None
373 else sys.argv)
374 try:
375 if required is None:
376 self.ptr = new CSetup(r.argc, r.argv)
377 self.provided = MPI_THREAD_SINGLE
378 else:
379 self.ptr = new CSetup(r.argc, r.argv, required, &provided)
380 self.provided = provided
381 self.argv = [r.argv[i] for i in xrange(r.argc)]
382 finally:
383 free(r.argv)
384
385 cdef MPI.Intracomm comm = MPI.Intracomm()
386 comm.ob_mpi = communicator(self.ptr)
387 self.comm = comm
388
389 self.ports = set()
390
391 def __dealloc__(self):
392 """
393 If runtime has been made and setup is invalid, do nothing.
394 Otherwise, deallocate or remove references to all objects.
395 """
396
397 if self.ptr is NULL:
398 return
399
400 del self.ptr
401 for p in self.ports:
402 del p.ptr
403 p.null()
404 self.null()
405
406 cpdef MPI.Intracomm getcomm(self):
407 """
408 Get an MPI communicator between the processes on this current
409 side of music
410 """
411 return self.comm
412
413 cdef null(self):
414 """
415 Invalidate this object --- called when runtime is
416 created. Music & runtime is now responsible for deallocating C
417 objects and clearing references to them.
418 """
419 self.ptr = NULL
420 self.comm = <MPI.Intracomm> MPI.COMM_NULL
421 self.ports = None
422
423 ####
424 def config(self, string var):
425 """
426 Get the value for var in config file.
427 string var: configuration variable for current group of
428 processes, including default and inherited settings.
429 The value is returned as an int if it matches the patter,
430 otherwise a float, otherwise a string.
431 Throws UndefinedConfig error if no such variable is defined.
432 """
433 cdef string vs
434
435 if not self.ptr.config(var, &vs):
436 raise UndefinedConfig(var)
437
438 try: return int(vs)
439 except ValueError: pass
440
441 try: return float(vs)
442 except ValueError: pass
443
444 return vs
445 ####
446
447 def publishContInput(self, string s):
448 """
449 Continuous Floating point value sink
450 string s: port name for music config
451 """
452 cdef ContInputPort p = ContInputPort()
453 p.ptr = self.ptr.publishContInput(s) # can't pass pointers directly to init
454 self.ports.add(p)
455 return p
456
457 def publishContOutput(self, string s):
458 """
459 Continuous Floating point value source
460 string s: port name for music config
461 """
462 cdef ContOutputPort p = ContOutputPort()
463 p.ptr = self.ptr.publishContOutput(s)
464 self.ports.add(p)
465 return p
466
467 def publishEventOutput(self, string s):
468 """
469 Discrete boolean source
470 string s: port name for music config
471 """
472 cdef EventOutputPort p = EventOutputPort()
473 p.ptr = self.ptr.publishEventOutput(s)
474 self.ports.add(p)
475 return p
476
477 def publishEventInput(self, string s):
478 """
479 Discrete boolean sink
480 string s: port name for music config
481 """
482 cdef EventInputPort p = EventInputPort()
483 p.ptr = self.ptr.publishEventInput(s)
484 self.ports.add(p)
485 return p
486
487 def publishMessageOutput(self, string s):
488 """
489 Discrete python object source
490 string s: port name for music config
491 """
492 cdef MessageOutputPort p = MessageOutputPort()
493 p.ptr = self.ptr.publishMessageOutput(s)
494 self.ports.add(p)
495 return p
496
497 def publishMessageInput(self, string s):
498 """
499 Discrete python object sink
500 string s: port name for music config
501 """
502 cdef MessageInputPort p = MessageInputPort()
503 p.ptr = self.ptr.publishMessageInput(s)
504 self.ports.add(p)
505 return p
506
507 def runtime(self, double timestep):
508 """
509 Create a runtime.
510 After return, this Setup object is invalid
511 double timestep: size of timestep (?? units)
512 """
513 return Runtime(self, timestep)
514
515 ###########################################################
516
517 cdef class Runtime(object):
518 def __cinit__(self, Setup setup, double h):
519 self.ptr = new CRuntime(setup.ptr, h)
520 self.ports = setup.ports
521 self.isFinalized = 0
522 setup.null()
523
524 cdef MPI.Intracomm comm = MPI.Intracomm()
525 comm.ob_mpi = communicator(self.ptr)
526 self.comm = comm
527
528 def __dealloc__(self):
529 if not self.isFinalized:
530 self.ptr.finalize()
531
532 for p in self.ports:
533 p.null()
534
535 del self.ptr
536
537 def time(self): return self.ptr.time()
538
539 def tick(self): tick(self.ptr)
540
541 def finalize(self):
542 self.isFinalized = 1
543 self.ptr.finalize()
544
545 def __iter__(self):
546 cdef CRuntime* ptr = self.ptr
547 while True:
548 yield ptr.time()
549 tick(ptr)
550
551 ###########################################################
552
553 from music.pybuffer import Buffer
554
555 from cpython cimport array
556 from array import array
557
558 cdef class IndexMap:
559 """
560 Internal:
561 Contains a C++ LinearIndex or PermutationIndex.
562 These map between "local" index i to "global" index j
563 LinearIndex: g = l + base, for l < size
564 PermutationIndex: g = perm[l], where perm is an array
565 """
566 def __cinit__(self, object perm=None, int base=0, int size=-1):
567 """
568 Created internally
569 Either perm is None, or we have a base, size pair
570 perm is buffer of integers mapping local to global
571 (local[i] -> global[perm[i]])
572 otherwise base is the first global index for size elements
573 (local[0] -> global[base])
574 """
575 cdef array.array arr
576
577 if perm is None:
578 self.buf = None
579 self.ptr = new LinearIndex(GlobalIndex(base), size)
580 else:
581 self.buf = Buffer(perm)
582 if self.buf.dtype.size() != sizeof(int):
583 arr = array('i', perm)
584 self.buf = Buffer(arr)
585 self.ptr = new PermutationIndex(<GlobalIndex*>
586 self.buf.pybuf.buf,
587 self.buf.items)
588
589 def __dealloc__(self):
590 del self.ptr
591
592 cdef class DataMap(object):
593 """
594 Internal:
595 An ArrayData object. Takes a data object as a Buffer and possibly an
596 IndexMap to construct a mapping for the Cont*Port transfers.
597 """
598 def __cinit__(self, Buffer buf, IndexMap index_map=None, int index=0):
599 """
600 Maps the Buffer of a data object between local and global indices.
601 Buffer buf: some simple array type that will be pushed through mpi
602 IndexMap index_map (None): an option index mapping from local to global
603 index (0): if index_map is None, this is the base offset for constructing
604 a linear index
605 """
606 self.buf = buf
607 self.ptr = new CArrayData(buf.pybuf.buf,
608 buf.dtype.ob_mpi,
609 index, buf.items) \
610 if index_map is None else \
611 new CArrayData(buf.pybuf.buf,
612 buf.dtype.ob_mpi,
613 index_map.ptr)
614
615 def __dealloc__(self): del self.ptr
616
617 cdef class EventHandler:
618 """
619 Internal:
620 An EventHandler is the python wrapper around a global
621 or local EventHandler object for EventInputPort
622 """
623 def __cinit__(self, object func, IndexType t):
624 """
625 func: a callable of the form
626 func(double d, IndexType t, int i) where
627 double d: the event time
628 IndexType t: local or global index enum
629 int i: the index value
630 IndexType t: the IndexType to receive in func
631 (??? Why is this so complex?? Do we need
632 to generalize func like this??)
633 """
634 self.ptr = <CEventHandler*> \
635 new CEHGlobal(<PyObject*>func) \
636 if t == IndexGLOBAL else \
637 <CEventHandler*> \
638 new CEHLocal(<PyObject*>func)
639 self.func = func
640
641 def __dealloc__(self): del self.ptr
642
643 cdef class _Index:
644 """
645 Internal: the type of the variable Index
646 that encapsulates the enum mapping
647 GLOBAL and LOCAL are the ints of the C enums
648 backmap maps from the enum to a string for output
649 purposes
650 """
651 cdef readonly int GLOBAL
652 cdef readonly int LOCAL
653 cdef readonly dict backmap
654
655 def __cinit__(self):
656 """ SINGLETON """
657 self.GLOBAL = IndexGLOBAL
658 self.LOCAL = IndexLOCAL
659 self.backmap = {
660 IndexGLOBAL: "GLOBAL",
661 IndexLOCAL: "LOCAL"
662 };
663
664 def tostr(self, int index):
665 """" tostring(Index.{GLOBAL,LOCAL}) --> "{GLOBAL,LOCAL}" """
666 return self.backmap[index]
667
668 # And here is the singleton def
669 Index = _Index()
670
671 cdef cbool EventCallback(PyObject* func,
672 double d,
673 IndexType t,
674 int i) \
675 except False:
676 """
677 Internal: C code can map back into python through this callback
678 func: callable object of func(d, t, i)
679 double d: time of event
680 IndexType t: LOCAL/GLOBAL int
681 int i: index of event
682 """
683 (<object>func)(d, t, i)
684 return True
685
686 cdef class MessageHandler:
687 """
688 MessageHandler wraps up Message*Port communications between C & python,
689 wrapping n particular the C++ MessageHandler object bound with a function.
690 It may (or may not) depickle messages
691 """
692 def __cinit__(self, object func, bint pickled):
693 """
694 func: The function to be called on a message, of the form
695 func(double t, object msg) where:
696 double t: the message time
697 msg: Either a bytearray, or an arbitrary unpickled python object
698 pickled: if true, the msg needs to be depickled
699 """
700 self.ptr = new CMHandler(<PyObject*>func, pickled)
701 self.func = func
702
703 def __dealloc__(self): del self.ptr
704
705 cdef cbool MessageCallback(PyObject* func,
706 double t,
707 void* msg,
708 size_t s,
709 cbool pickled) \
710 except False:
711 """
712 The function to return a Message from C to Python.
713 func: callable of the form
714 func(double t, object/bytearray obj) where:
715 t: is the time of the message
716 obj: is either the unpickled object if the port unpickles
717 or simply a bytearray of data (you figure out the source)
718 """
719 #cdef str pobj = (<char*>msg)[:s]
720 cdef bytearray pobj = (<char*>msg)[:s]
721 cdef object obj = pickle.loads(pobj) if pickled else pobj
722 (<object>func)(t, obj)
723 return True
724
725 #############################################################################
726 #
727 # And for handling errors at the C/Python interface
728 #
729 # pythonError: true if a python error is being stored until we get out of C
730 # etype, evalue, etraceback: three bits of data to recreate the exception
731 # so that it can be thrown
732 #
733 pythonError = False
734 etype = NULL
735 evalue = NULL
736 etraceback = NULL