-
Notifications
You must be signed in to change notification settings - Fork 148
Expand file tree
/
Copy path__init__.py
More file actions
1837 lines (1461 loc) · 55.4 KB
/
Copy path__init__.py
File metadata and controls
1837 lines (1461 loc) · 55.4 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
"""
neuron
======
For empirically-based simulations of neurons and networks of neurons in Python.
This is the top-level module of the official python interface to
the NEURON simulation environment (http://neuron.yale.edu/neuron/).
Documentation is available in the docstrings.
For a list of available names, try dir(neuron).
Example:
$ ipython
In [1]: import neuron
NEURON -- VERSION 6.2 2008-08-22
Duke, Yale, and the BlueBrain Project -- Copyright 1984-2007
See http://neuron.yale.edu/credits.html
In [2]: neuron.h ?
Important names and sub-packages
---------------------
For help on these useful functions, see their docstrings:
load_mechanisms
neuron.h
The top-level Hoc interpreter.
Execute Hoc commands by calling h with a string argument:
>>> h('objref myobj')
>>> h('myobj = new Vector(10)')
All Hoc defined variables are accessible by attribute access to h.
Example:
>>> print h.myobj.x[9]
Hoc Classes are also defined, for example:
>>> v = h.Vector([1,2,3])
>>> soma = h.Section()
More help is available for the respective class by looking in the object docstring:
>>> help(h.Vector)
neuron.gui
Import this package if you are using NEURON as an extension to Python,
and you would like to use the NEURON GUI.
If you are using NEURON with embedded python, "nrniv -python",
use rather "nrngui -python" if you would like to use the NEURON GUI.
$Id: __init__.py,v 1.1 2008/05/26 11:39:44 hines Exp hines $
"""
## With Python launched under Linux, shared libraries are apparently imported
## using RTLD_LOCAL. For --with-paranrn=dynamic, this caused a failure when
## libnrnmpi.so is dynamically loaded because nrnmpi_myid (and other global
## variables in src/nrnmpi/nrnmpi_def_cinc) were not resolved --- even though
## all those variables are defined in src/oc/nrnmpi_dynam.c and that
## does a dlopen("libnrnmpi.so", RTLD_NOW | RTLD_GLOBAL) .
## In this case setting the dlopenflags below fixes the problem. But it
## seems that DLFCN is often not available.
## This situation is conceptually puzzling because there
## never seems to be a problem dynamically loading libnrnmech.so, though it
## obviously makes use of many names in the rest of NEURON. Anyway,
## we make the following available in case it is ever needed at least to
## verify that some import problem is traceable to this issue.
## The problem can be resolved in two ways. 1) see src/nrnmpi/nrnmpi_dynam.c
## which promotes liboc.so and libnrniv.so to RTLD_GLOBAL (commented out).
## 2) The better way of specifying those libraries to libnrnmpi_la_LIBADD
## in src/nrnmpi/Makefile.am . This latter also explains why libnrnmech.so
## does not have this problem.
# try:
# import sys
# import DLFCN
# sys.setdlopenflags(DLFCN.RTLD_NOW | DLFCN.RTLD_GLOBAL)
# except:
# pass
import sys
import os
import warnings
import weakref
embedded = True if "hoc" in sys.modules else False
try: # needed since python 3.8 on windows if python launched
# do this here as NEURONHOME may be changed below
nrnbindir = os.path.abspath(os.environ["NEURONHOME"] + "/bin")
os.add_dll_directory(nrnbindir)
except:
pass
# With pip we need to rewrite the NEURONHOME
nrn_path = os.path.abspath(os.path.join(os.path.dirname(__file__), ".data/share/nrn"))
if os.path.isdir(nrn_path):
os.environ["NEURONHOME"] = nrn_path
# On OSX, dlopen might fail if not using full library path
try:
from sys import platform
if platform == "darwin":
from ctypes.util import find_library
mpi_library_path = find_library("mpi")
if mpi_library_path and "MPI_LIB_NRN_PATH" not in os.environ:
os.environ["MPI_LIB_NRN_PATH"] = mpi_library_path
except:
pass
try:
from . import hoc
except:
import neuron.hoc
import nrn
import _neuron_section
h = hoc.HocObject()
version = h.nrnversion(5)
__version__ = version
_original_hoc_file = None
if not hasattr(hoc, "__file__"):
# first try is to derive from neuron.__file__
origin = None # path to neuron/__init__.py
from importlib import util
mspec = util.find_spec("neuron")
if mspec:
origin = mspec.origin
if origin is not None:
import sysconfig
hoc_path = (
origin.rstrip("__init__.py")
+ "hoc"
+ sysconfig.get_config_var("EXT_SUFFIX")
)
setattr(hoc, "__file__", hoc_path)
else:
_original_hoc_file = hoc.__file__
# As a workaround to importing doc at neuron import time
# (which leads to chicken and egg issues on some platforms)
# define a dummy help function which imports doc,
# calls the real help function, and reassigns neuron.help to doc.help
# (thus replacing the dummy)
def help(request=None):
global help
from neuron import doc
doc.help(request)
help = doc.help
try:
import pydoc
pydoc.help = help
except:
pass
# Global test-suite function
def test(exitOnError=True):
"""Runs a global battery of unit tests on the neuron module."""
import neuron.tests
import unittest
runner = unittest.TextTestRunner(verbosity=2)
result = runner.run(neuron.tests.suite()).wasSuccessful()
if exitOnError and result is False:
sys.exit(1)
return result
def test_rxd(exitOnError=True):
"""Runs a tests on the rxd and crxd modules."""
import neuron.tests
import unittest
runner = unittest.TextTestRunner(verbosity=2)
result = runner.run(neuron.tests.test_rxd.suite()).wasSuccessful()
if exitOnError and result is False:
sys.exit(1)
return result
# ------------------------------------------------------------------------------
# class factory for subclassing h.anyclass
# h.anyclass methods may be overridden. If so the base method can be called
# using the idiom self.basemethod = self.baseattr('methodname')
# ------------------------------------------------------------------------------
import sys, types
from neuron.hclass3 import HocBaseObject, hclass
# global list of paths already loaded by load_mechanisms
nrn_dll_loaded = []
def load_mechanisms(path, warn_if_already_loaded=True):
"""
load_mechanisms(path)
Search for and load NMODL mechanisms from the path given.
This function will not load a mechanism path twice.
The path should specify the directory in which nrnivmodl or mknrndll was run,
and in which the directory 'i686' (or 'x86_64' or 'powerpc' depending on your platform)
was created"""
import platform
global nrn_dll_loaded
if path in nrn_dll_loaded:
if warn_if_already_loaded:
print("Mechanisms already loaded from path: %s. Aborting." % path)
return True
# in case NEURON is assuming a different architecture to Python,
# we try multiple possibilities
libname = "libnrnmech.so"
libsubdir = ".libs"
arch_list = [platform.machine(), "i686", "x86_64", "powerpc", "umac"]
# windows loads nrnmech.dll
if h.unix_mac_pc() == 3:
libname = "nrnmech.dll"
libsubdir = ""
arch_list = [""]
for arch in arch_list:
lib_path = os.path.join(path, arch, libsubdir, libname)
if os.path.exists(lib_path):
h.nrn_load_dll(lib_path)
nrn_dll_loaded.append(path)
return True
print("NEURON mechanisms not found in %s." % path)
return False
import os, sys
if "NRN_NMODL_PATH" in os.environ:
nrn_nmodl_path = os.environ["NRN_NMODL_PATH"].split(":")
print("Auto-loading mechanisms:")
print("NRN_NMODL_PATH=%s" % os.environ["NRN_NMODL_PATH"])
for x in nrn_nmodl_path:
# print "from path %s:" % x
load_mechanisms(x)
# print "\n"
print("Done.\n")
# ------------------------------------------------------------------------------
# Python classes and functions without a Hoc equivalent, mainly for internal
# use within this file.
# ------------------------------------------------------------------------------
class HocError(Exception):
pass
class Wrapper(object):
"""Base class to provide attribute access for HocObjects."""
def __getattr__(self, name):
if name == "hoc_obj":
return self.__dict__["hoc_obj"]
else:
try:
return self.__getattribute__(name)
except AttributeError:
return self.hoc_obj.__getattribute__(name)
def __setattr__(self, name, value):
try:
self.hoc_obj.__setattr__(name, value)
except LookupError:
object.__setattr__(self, name, value)
def new_point_process(name, doc=None):
"""
Returns a Python-wrapped hoc class where the object needs to be associated
with a section.
doc - specify a docstring for the new pointprocess class
"""
h("obfunc new_%s() { return new %s($1) }" % (name, name))
class someclass(Wrapper):
__doc__ = doc
def __init__(self, section, position=0.5):
assert 0 <= position <= 1
section.push()
self.__dict__["hoc_obj"] = getattr(h, "new_%s" % name)(
position
) # have to put directly in __dict__ to avoid infinite recursion with __getattr__
h.pop_section()
someclass.__name__ = name
return someclass
def new_hoc_class(name, doc=None):
"""
Returns a Python-wrapped hoc class where the object does not need to be
associated with a section.
doc - specify a docstring for the new hoc class
"""
h("obfunc new_%s() { return new %s() }" % (name, name))
class someclass(Wrapper):
__doc__ = doc
def __init__(self, **kwargs):
self.__dict__["hoc_obj"] = getattr(h, "new_%s" % name)()
for k, v in list(kwargs.items()):
setattr(self.hoc_obj, k, v)
someclass.__name__ = name
return someclass
# ------------------------------------------------------------------------------
# Python equivalents to Hoc functions
# ------------------------------------------------------------------------------
def xopen(*args, **kwargs):
"""
Syntax:
``neuron.xopen("hocfile")``
``neuron.xopen("hocfile", "RCSrevision")``
Description:
``h.xopen()`` executes the commands in ``hocfile``. This is a convenient way
to define user functions and procedures.
An optional second argument is the RCS revision number in the form of a
string. The RCS file with that revision number is checked out into a
temporary file and executed. The temporary file is then removed. A file
of the same primary name is unaffected.
This function is deprecated and will be removed in a future release.
Use ``h.xopen`` instead.
"""
warnings.warn(
"neuron.xopen is deprecated; use h.xopen instead",
DeprecationWarning,
stacklevel=2,
)
return h.xopen(*args, **kwargs)
def quit(*args, **kwargs):
"""
Exits the program. Can be used as the action of a button. If edit buffers
are open you will be asked if you wish to save them before the final exit.
This function is deprecated and will be removed in a future release.
Use ``h.quit()`` or ``sys.exit()`` instead. (Note: sys.exit will not prompt
for saving edit buffers.)
"""
warnings.warn(
"neuron.quit() is deprecated; use h.quit() or sys.exit() instead",
DeprecationWarning,
stacklevel=2,
)
return h.quit(*args, **kwargs)
def hoc_execute(hoc_commands, comment=None):
assert isinstance(hoc_commands, list)
if comment:
logging.debug(comment)
for cmd in hoc_commands:
logging.debug(cmd)
success = hoc.execute(cmd)
if not success:
raise HocError('Error produced by hoc command "%s"' % cmd)
def hoc_comment(comment):
logging.debug(comment)
def psection(section):
"""
function psection(section):
Print info about section in a hoc format which is executable.
(length, parent, diameter, membrane information)
Use section.psection() instead to get a data structure that
contains the same information and more.
This function is deprecated and will be removed in a future
release.
See:
https://www.neuron.yale.edu/neuron/static/py_doc/modelspec/programmatic/topology.html?#psection
"""
warnings.warn(
"neuron.psection() is deprecated; use print(sec.psection()) instead",
DeprecationWarning,
stacklevel=2,
)
h.psection(sec=section)
def init():
"""
function init():
Initialize the simulation kernel. This should be called before a run(tstop) call.
** This function exists for historical purposes. Use in new code is not recommended. **
Use h.finitialize() instead, which allows you to specify the membrane potential
to initialize to; via e.g. h.finitialize(-65)
This function is deprecated and will be removed in a future
release.
By default, the units used by h.finitialize are in mV, but you can be explicit using
NEURON's unit's library, e.g.
.. code-block:: python
from neuron.units import mV
h.finitialize(-65 * mV)
https://www.neuron.yale.edu/neuron/static/py_doc/simctrl/programmatic.html?#finitialize
"""
warnings.warn(
"neuron.init() is deprecated; use h.init() instead",
DeprecationWarning,
stacklevel=2,
)
h.finitialize()
def run(tstop):
"""
function run(tstop)
Run the simulation (advance the solver) until tstop [ms]
`h.run()` and `h.continuerun(tstop)` are more powerful solutions defined in the `stdrun.hoc` library.
** This function exists for historical purposes. Use in new code is not recommended. **
This function is deprecated and will be removed in a future
release.
For running a simulation, consider doing the following instead:
Begin your code with
.. code-block:: python
from neuron import h
from neuron.units import ms, mV
h.load_file('stdrun.hoc')
Then when it is time to initialize and run the simulation:
.. code-block:: python
h.finitialize(-65 * mV)
h.continuerun(100 * ms)
where the initial membrane potential and the simulation run time are adjusted as appropriate
for your model.
"""
warnings.warn(
"neuron.run(tstop) is deprecated; use h.stdinit() and h.continuerun(tstop) instead",
DeprecationWarning,
stacklevel=2,
)
h("tstop = %g" % tstop)
h("while (t < tstop) { fadvance() }")
# what about pc.psolve(tstop)?
_nrn_dll = None
_nrn_hocobj_ptr = None
_double_ptr = None
_double_size = None
def numpy_element_ref(numpy_array, index):
"""Return a HOC reference into a numpy array.
Parameters
----------
numpy_array : :class:`numpy.ndarray`
the numpy array
index : int
the index into the numpy array
.. warning::
No bounds checking.
.. warning::
Assumes a contiguous array of doubles. In particular, be careful when
using slices. If the array is multi-dimensional,
the user must figure out the integer index to the desired element.
"""
global _nrn_dll, _double_ptr, _double_size, _nrn_hocobj_ptr
import ctypes
if _nrn_hocobj_ptr is None:
_nrn_hocobj_ptr = nrn_dll_sym("nrn_hocobj_ptr")
_nrn_hocobj_ptr.restype = ctypes.py_object
_double_ptr = ctypes.POINTER(ctypes.c_double)
_double_size = ctypes.sizeof(ctypes.c_double)
void_p = (
ctypes.cast(numpy_array.ctypes.data_as(_double_ptr), ctypes.c_voidp).value
+ index * _double_size
)
return _nrn_hocobj_ptr(ctypes.cast(void_p, _double_ptr))
def nrn_dll_sym(name, type=None):
"""return the specified object from the NEURON dlls.
Parameters
----------
name : string
the name of the object (function, integer, etc...)
type : None or ctypes type (e.g. ctypes.c_int)
the type of the object (if None, assumes function pointer)
"""
# TODO: this won't work under Windows; will need to search through until
# can find the right dll (should we cache the results of the search?)
import os
if os.name == "nt":
return nrn_dll_sym_nt(name, type)
dll = nrn_dll()
if type is None:
return dll.__getattr__(name)
else:
return type.in_dll(dll, name)
nt_dlls = []
def nrn_dll_sym_nt(name, type):
"""return the specified object from the NEURON dlls.
helper for nrn_dll_sym(name, type). Try to find the name in either
nrniv.dll or libnrnpython1013.dll
"""
global nt_dlls
import ctypes
import os
if len(nt_dlls) == 0:
b = "bin"
if h.nrnversion(8).find("i686") == 0:
b = "bin"
path = os.path.join(h.neuronhome().replace("/", "\\"), b)
fac = 10 if sys.version_info[1] < 10 else 100 # 3.9 is 39 ; 3.10 is 310
p = sys.version_info[0] * fac + sys.version_info[1]
for dllname in ["libnrniv.dll", "libnrnpython%d.dll" % p]:
p = os.path.join(path, dllname)
try:
nt_dlls.append(ctypes.cdll[p])
except:
pass
for dll in nt_dlls:
try:
a = dll.__getattr__(name)
except:
a = None
if a:
if type is None:
return a
else:
return type.in_dll(dll, name)
raise Exception("unable to connect to the NEURON library containing " + name)
def nrn_dll(printpath=False):
"""Return a ctypes object corresponding to the NEURON library.
.. warning::
This provides access to the C-language internals of NEURON and should
be used with care.
"""
import ctypes
import glob
import os
import sys
try:
# extended? if there is a __file__, then use that
if printpath:
print("hoc.__file__ %s" % _original_hoc_file)
the_dll = ctypes.pydll[_original_hoc_file]
return the_dll
except:
pass
success = False
if sys.platform == "msys" or sys.platform == "win32":
p = "hoc%d%d" % (sys.version_info[0], sys.version_info[1])
else:
p = "hoc"
try:
# maybe hoc.so in this neuron module
base_path = os.path.join(os.path.split(__file__)[0], p)
dlls = glob.glob(base_path + "*.*")
for dll in dlls:
try:
the_dll = ctypes.pydll[dll]
if printpath:
print(dll)
return the_dll
except:
pass
except:
pass
# maybe old default module location
neuron_home = os.path.split(os.path.split(h.neuronhome())[0])[0]
base_path = os.path.join(neuron_home, "lib", "python", "neuron", p)
for extension in ["", ".dll", ".so", ".dylib"]:
dlls = glob.glob(base_path + "*" + extension)
for dll in dlls:
try:
the_dll = ctypes.pydll[dll]
if printpath:
print(dll)
success = True
except:
pass
if success:
break
if success:
break
else:
raise Exception("unable to connect to the NEURON library")
return the_dll
def _modelview_mechanism_docstrings(dmech, tree):
if dmech.name not in ("Ra", "capacitance"):
docs = getattr(h, dmech.name).__doc__
if docs.strip():
for line in docs.split("\n"):
tree.append(line, dmech.location, 0)
# TODO: put this someplace else
# can't be in rxd because that would break things if no scipy
_sec_db = {}
def _declare_contour(secobj, obj, name):
array, i = _parse_import3d_name(name)
if obj is None:
sec = getattr(h, array)[i]
else:
sec = getattr(obj, array)[i]
j = secobj.first
center_vec = secobj.contourcenter(
secobj.raw.getrow(0), secobj.raw.getrow(1), secobj.raw.getrow(2)
)
x0, y0, z0 = [center_vec.x[i] for i in range(3)]
# store a couple of points to check if the section has been moved
pts = [(sec.x3d(i), sec.y3d(i), sec.z3d(i)) for i in [0, sec.n3d() - 1]]
# (is_stack, x, y, z, xcenter, ycenter, zcenter)
_sec_db[sec.hoc_internal_name()] = (
True if secobj.contour_list else False,
secobj.raw.getrow(0).c(j),
secobj.raw.getrow(1).c(j),
secobj.raw.getrow(2).c(j),
x0,
y0,
z0,
pts,
)
def _create_all_list(obj):
# used by import3d
obj.all = []
def _create_sections_in_obj(obj, name, numsecs):
# used by import3d to instantiate inside of a Python object
setattr(
obj,
name,
[h.Section(name="%s[%d]" % (name, i), cell=obj) for i in range(int(numsecs))],
)
def _connect_sections_in_obj(obj, childsecname, childx, parentsecname, parentx):
# used by import3d
childarray, childi = _parse_import3d_name(childsecname)
parentarray, parenti = _parse_import3d_name(parentsecname)
getattr(obj, childarray)[childi].connect(
getattr(obj, parentarray)[parenti](parentx), childx
)
def _parse_import3d_name(name):
if "[" in name:
import re
array, i = re.search(r"(.*)\[(\d*)\]", name).groups()
i = int(i)
else:
array = name
i = 0
return array, i
def _pt3dstyle_in_obj(obj, name, x, y, z):
# used by import3d
array, i = _parse_import3d_name(name)
h.pt3dstyle(1, x, y, z, sec=getattr(obj, array)[i])
def _pt3dadd_in_obj(obj, name, x, y, z, d):
array, i = _parse_import3d_name(name)
h.pt3dadd(x, y, z, d, sec=getattr(obj, array)[i])
def numpy_from_pointer(cpointer, size):
buf_from_mem = ctypes.pythonapi.PyMemoryView_FromMemory
buf_from_mem.restype = ctypes.py_object
buf_from_mem.argtypes = (ctypes.c_void_p, ctypes.c_int, ctypes.c_int)
cbuffer = buf_from_mem(cpointer, size * numpy.dtype(float).itemsize, 0x200)
return numpy.ndarray((size,), float, cbuffer, order="C")
try:
import ctypes
import numpy
import traceback
vec_to_numpy_prototype = ctypes.CFUNCTYPE(
ctypes.py_object, ctypes.c_int, ctypes.POINTER(ctypes.c_double)
)
def vec2numpy(size, data):
try:
return numpy_from_pointer(data, size)
except:
traceback.print_exc()
return None
vec_to_numpy_callback = vec_to_numpy_prototype(vec2numpy)
set_vec_as_numpy = nrn_dll_sym("nrnpy_set_vec_as_numpy")
set_vec_as_numpy(vec_to_numpy_callback)
except:
pass
class _WrapperPlot:
def __init__(self, data):
"""do not call directly"""
self._data = data
def __repr__(self):
return "{}.plot()".format(repr(self._data))
class _RangeVarPlot(_WrapperPlot):
"""Plots the current state of the RangeVarPlot on the graph.
Additional arguments and keyword arguments are passed to the graph's
plotting method.
Example, showing plotting to NEURON graphics, bokeh, matplotlib,
plotnine/ggplot, and plotly:
.. code::
from matplotlib import pyplot
from neuron import h, gui
import bokeh.plotting as b
import plotly
import plotly.graph_objects as go
import plotnine as p9
import math
dend = h.Section(name='dend')
dend.nseg = 55
dend.L = 6.28
# looping over dend.allseg instead of dend to set 0 and 1 ends
for seg in dend.allseg():
seg.v = math.sin(dend.L * seg.x)
r = h.RangeVarPlot('v', dend(0), dend(1))
# matplotlib
graph = pyplot.gca()
r.plot(graph, linewidth=10, color='r')
# NEURON Interviews graph
g = h.Graph()
r.plot(g, 2, 3)
g.exec_menu('View = plot')
# Bokeh
bg = b.Figure()
r.plot(bg, line_width=10)
b.show(bg)
# plotly
r.plot(plotly).show()
# also plotly
fig = go.Figure()
r.plot(fig)
fig.show()
pyplot.show()
# plotnine/ggplot
p9.ggplot() + r.plot(p9)
# alternative plotnine/ggplot
r.plot(p9.ggplot())
"""
def __call__(self, graph, *args, **kwargs):
yvec = h.Vector()
xvec = h.Vector()
self._data.to_vector(yvec, xvec)
if isinstance(graph, hoc.HocObject):
return yvec.line(graph, xvec, *args)
str_type_graph = str(type(graph))
if str_type_graph == "<class 'plotly.graph_objs._figure.Figure'>":
# plotly figure
import plotly.graph_objects as go
kwargs.setdefault("mode", "lines")
return graph.add_trace(go.Scatter(x=xvec, y=yvec, *args, **kwargs))
if str_type_graph == "<class 'plotnine.ggplot.ggplot'>":
# ggplot object
import plotnine as p9
import pandas as pd
return graph + p9.geom_line(
*args,
data=pd.DataFrame({"x": xvec, "y": yvec}),
mapping=p9.aes(x="x", y="y"),
**kwargs,
)
str_graph = str(graph)
if str_graph.startswith("<module 'plotly' from "):
# plotly module
import plotly.graph_objects as go
fig = go.Figure()
kwargs.setdefault("mode", "lines")
return fig.add_trace(go.Scatter(x=xvec, y=yvec, *args, **kwargs))
if str_graph.startswith("<module 'plotnine' from "):
# plotnine module (contains ggplot)
import plotnine as p9
import pandas as pd
return p9.geom_line(
*args,
data=pd.DataFrame({"x": xvec, "y": yvec}),
mapping=p9.aes(x="x", y="y"),
**kwargs,
)
if hasattr(graph, "plot"):
# works with e.g. pyplot or a matplotlib axis
return graph.plot(xvec, yvec, *args, **kwargs)
if hasattr(graph, "line"):
# works with e.g. bokeh
return graph.line(xvec, yvec, *args, **kwargs)
if str_type_graph == "<class 'matplotlib.figure.Figure'>":
raise Exception("plot to a matplotlib axis not a matplotlib figure")
raise Exception("Unable to plot to graphs of type {}".format(type(graph)))
class _PlotShapePlot(_WrapperPlot):
"""Plots the currently selected data on an object.
Currently only pyplot is supported, e.g.
from matplotlib import pyplot
ps = h.PlotShape(False)
ps.variable('v')
ps.plot(pyplot)
pyplot.show()
Limitations: many. Currently only supports plotting a full cell colored based on a variable."""
# TODO: handle pointmark, specified sections, color
def __call__(self, graph, *args, **kwargs):
from neuron.gui2.utilities import _segment_3d_pts
def _get_pyplot_axis3d(fig):
"""requires matplotlib"""
from matplotlib.pyplot import cm
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
class Axis3DWithNEURON(Axes3D):
def auto_aspect(self):
"""sets the x, y, and z range symmetric around the center
Probably needs a square figure to preserve lengths as you rotate."""
bounds = [self.get_xlim(), self.get_ylim(), self.get_zlim()]
half_delta_max = max([(item[1] - item[0]) / 2 for item in bounds])
xmid = sum(bounds[0]) / 2
ymid = sum(bounds[1]) / 2
zmid = sum(bounds[2]) / 2
self.auto_scale_xyz(
[xmid - half_delta_max, xmid + half_delta_max],
[ymid - half_delta_max, ymid + half_delta_max],
[zmid - half_delta_max, zmid + half_delta_max],
)
def mark(self, segment, marker="or", **kwargs):
"""plot a marker on a segment
Args:
segment = the segment to mark
marker = matplotlib marker
**kwargs = passed to matplotlib's plot
"""
x, y, z = _get_3d_pt(segment)
self.plot([x], [y], [z], marker)
return self
def _do_plot(
self, val_min, val_max, sections, variable, cmap=cm.cool, **kwargs
):
"""
Plots a 3D shapeplot
Args:
sections = list of h.Section() objects to be plotted
**kwargs passes on to matplotlib (e.g. linewidth=2 for thick lines)
Returns:
lines = list of line objects making up shapeplot
"""
# Adapted from
# https://github.com/ahwillia/PyNeuron-Toolbox/blob/master/PyNeuronToolbox/morphology.py
# Accessed 2019-04-11, which had an MIT license
# Default is to plot all sections.
if sections is None:
sections = list(h.allsec())
h.define_shape()