-
Notifications
You must be signed in to change notification settings - Fork 118
/
nrnpy_hoc.cpp
3453 lines (3225 loc) · 119 KB
/
nrnpy_hoc.cpp
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
#include "cabcode.h"
#include "ivocvect.h"
#include "neuron/container/data_handle.hpp"
#include "neuron/unique_cstr.hpp"
#include "nrniv_mf.h"
#include "nrn_pyhocobject.h"
#include "nrnoc2iv.h"
#include "nrnpy.h"
#include "nrnpy_utils.h"
#include "nrnpython.h"
#include "convert_cxx_exceptions.hpp"
#include "nrnwrap_dlfcn.h"
#include "ocfile.h"
#include "ocjump.h"
#include "oclist.h"
#include "shapeplt.h"
#include <cstdint>
#include <vector>
#include <sstream>
#include <unordered_map>
#include <nanobind/nanobind.h>
namespace nb = nanobind;
extern PyTypeObject* psection_type;
extern std::vector<const char*> py_exposed_classes;
#include "parse.hpp"
extern void (*nrnpy_sectionlist_helper_)(void*, Object*);
extern void* (*nrnpy_get_pyobj)(Object* obj);
extern void (*nrnpy_restore_savestate)(int64_t, char*);
extern void (*nrnpy_store_savestate)(char** save_data, uint64_t* save_data_size);
extern void (*nrnpy_decref)(void* pyobj);
extern void lvappendsec_and_ref(void* sl, Section* sec);
extern void hoc_pushs(Symbol*);
extern double* hoc_evalpointer();
extern double cable_prop_eval(Symbol* sym);
extern Symlist* hoc_top_level_symlist;
extern Symlist* hoc_built_in_symlist;
extern Inst* hoc_pc;
extern void hoc_push_string();
extern char** hoc_strpop();
extern void hoc_objectvar();
extern Object* hoc_newobj1(Symbol*, int);
extern int ivoc_list_count(Object*);
extern Object** hoc_objpop();
extern Object* hoc_obj_look_inside_stack(int);
extern void hoc_object_component();
extern int nrn_inpython_;
extern int hoc_stack_type();
extern void hoc_call();
extern Objectdata* hoc_top_level_data;
extern void hoc_tobj_unref(Object**);
extern void hoc_unref_defer();
extern void sec_access_push();
extern bool hoc_valid_stmt(const char*, Object*);
PyObject* nrnpy_nrn();
extern PyObject* nrnpy_cas(PyObject*, PyObject*);
extern PyObject* nrnpy_cas_safe(PyObject*, PyObject*);
extern PyObject* nrnpy_forall_safe(PyObject*, PyObject*);
extern PyObject* nrnpy_newsecobj_safe(PyObject*, PyObject*, PyObject*);
extern int section_object_seen;
extern Symbol* nrn_child_sym;
extern int nrn_secref_nchild(Section*);
static void pyobject_in_objptr(Object**, PyObject*);
extern IvocVect* (*nrnpy_vec_from_python_p_)(void*);
extern Object** (*nrnpy_vec_to_python_p_)(void*);
extern Object** (*nrnpy_vec_as_numpy_helper_)(int, double*);
extern Object* (*nrnpy_rvp_rxd_to_callable)(Object*);
extern Symbol* ivoc_alias_lookup(const char* name, Object* ob);
class NetCon;
extern int nrn_netcon_weight(NetCon*, double**);
extern int nrn_matrix_dim(void*, int);
extern PyObject* pmech_types; // Python map for name to Mechanism
extern PyObject* rangevars_; // Python map for name to Symbol
extern int hoc_max_builtin_class_id;
extern int hoc_return_type_code;
static cTemplate* hoc_vec_template_;
static cTemplate* hoc_list_template_;
static cTemplate* hoc_sectionlist_template_;
static std::unordered_map<Symbol*, PyTypeObject*> sym_to_type_map;
static std::unordered_map<PyTypeObject*, Symbol*> type_to_sym_map;
static std::vector<std::string> exposed_py_type_names;
// typestr returned by Vector.__array_interface__
// byteorder (first element) is modified at import time
// to reflect the system byteorder
// Allocate one extra character space in case we have a two character integer of
// bytes per double
// i.e. 16
static char array_interface_typestr[5] = "|f8";
// static pointer to neurons.doc.get_docstring function initialized at import
// time
static PyObject* pfunc_get_docstring = NULL;
// Methods unique to the HocTopLevelInterpreter type of HocObject
// follow the add_methods implementation of python3.6.2 in typeobject.c
// and the GenericGetAttr implementation in object.c
static PyObject* topmethdict = NULL;
static void add2topdict(PyObject*);
static const char* hocobj_docstring = "class neuron.hoc.HocObject - Hoc Object wrapper";
#if 1
#include "hoccontext.h"
#else
extern Object* hoc_thisobject;
#define HocTopContextSet \
if (hoc_thisobject) { \
abort(); \
} \
assert(hoc_thisobject == 0);
#define HocContextRestore /**/
#endif
static PyObject* rvp_plot = NULL;
static PyObject* plotshape_plot = NULL;
static PyObject* cpp2refstr(char** cpp);
static PyObject* get_mech_object_ = NULL;
static PyObject* nrnpy_rvp_pyobj_callback = NULL;
PyTypeObject* hocobject_type;
static PyObject* hocobj_call(PyHocObject* self, PyObject* args, PyObject* kwrds);
struct hocclass {
PyTypeObject head;
Symbol* sym;
};
static int hocclass_init(hocclass* cls, PyObject* args, PyObject* kwds) {
if (PyType_Type.tp_init((PyObject*) cls, args, kwds) < 0) {
return -1;
}
return 0;
}
static PyObject* hocclass_getitem(PyObject* self, Py_ssize_t ix) {
hocclass* hclass = (hocclass*) self;
Symbol* sym = hclass->sym;
assert(sym);
assert(sym->type == TEMPLATE);
hoc_Item *q, *ql = sym->u.ctemplate->olist;
Object* ob;
ITERATE(q, ql) {
ob = OBJ(q);
if (ob->index == ix) {
return nrnpy_ho2po(ob);
}
}
char e[200];
Sprintf(e, "%s[%ld] instance does not exist", sym->name, ix);
PyErr_SetString(PyExc_IndexError, e);
return NULL;
}
// Note use of slots was informed by nanobind (search for nb_meta)
static PyType_Slot hocclass_slots[] = {{Py_tp_base, nullptr}, // &PyType_Type : not obvious why it
// must be set at runtime
{Py_tp_init, (void*) hocclass_init},
{Py_sq_item, (void*) hocclass_getitem},
{0, NULL}};
static PyType_Spec hocclass_spec = {"hoc.HocClass",
0, // .basicsize fill later
0, // .itemsize
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE,
hocclass_slots};
bool nrn_chk_data_handle(const neuron::container::data_handle<double>& pd) {
if (pd) {
return true;
}
PyErr_SetString(PyExc_ValueError, "Invalid data_handle");
return false;
}
/** @brief if hoc_evalpointer calls hoc_execerror, return 1
**/
static int hoc_evalpointer_err() {
try {
hoc_evalpointer();
} catch (std::exception const& e) {
std::ostringstream oss;
oss << "subscript out of range (array size or number of dimensions changed?)";
PyErr_SetString(PyExc_IndexError, oss.str().c_str());
return 1;
}
return 0;
}
static PyObject* nrnexec(PyObject* self, PyObject* args) {
const char* cmd;
if (!PyArg_ParseTuple(args, "s", &cmd)) {
return NULL;
}
bool b = hoc_valid_stmt(cmd, 0);
return b ? Py_True : Py_False;
}
static PyObject* nrnexec_safe(PyObject* self, PyObject* args) {
return nrn::convert_cxx_exceptions(nrnexec, self, args);
}
static PyObject* hoc_ac(PyObject* self, PyObject* args) {
PyArg_ParseTuple(args, "|d", &hoc_ac_);
return Py_BuildValue("d", hoc_ac_);
}
static PyObject* hoc_ac_safe(PyObject* self, PyObject* args) {
return nrn::convert_cxx_exceptions(hoc_ac, self, args);
}
static PyMethodDef HocMethods[] = {
{"execute",
nrnexec_safe,
METH_VARARGS,
"Execute a hoc command, return True on success, False on failure."},
{"hoc_ac", hoc_ac_safe, METH_VARARGS, "Get (or set) the scalar hoc_ac_."},
{NULL, NULL, 0, NULL}};
static void hocobj_dealloc(PyHocObject* self) {
// printf("hocobj_dealloc %p\n", self);
if (self->ho_) {
hoc_obj_unref(self->ho_);
}
if (self->type_ == PyHoc::HocRefStr && self->u.s_) {
// delete [] self->u.s_;
free(self->u.s_);
}
if (self->type_ == PyHoc::HocRefObj && self->u.ho_) {
hoc_obj_unref(self->u.ho_);
}
if (self->indices_) {
delete[] self->indices_;
}
if (self->type_ == PyHoc::HocRefPStr && self->u.pstr_) {
// nothing deleted
}
((PyObject*) self)->ob_type->tp_free((PyObject*) self);
// Deferred deletion of HOC Objects is unnecessary when a HocObject is
// destroyed. And we would like to have prompt deletion if this HocObject
// wrapped a HOC Object whose refcount was 1.
hoc_unref_defer();
}
static PyObject* hocobj_new(PyTypeObject* subtype, PyObject* args, PyObject* kwds) {
PyObject* base;
PyHocObject* hbase = nullptr;
auto subself = nb::steal(subtype->tp_alloc(subtype, 0));
// printf("hocobj_new %s %p %p\n", subtype->tp_name, subtype, subself.ptr());
if (!subself) {
return nullptr;
}
PyHocObject* self = (PyHocObject*) subself.ptr();
self->ho_ = NULL;
self->u.x_ = 0.;
self->sym_ = NULL;
self->indices_ = NULL;
self->nindex_ = 0;
self->type_ = PyHoc::HocTopLevelInterpreter;
self->iteritem_ = 0;
// if subtype is a subclass of some NEURON class, then one of its
// tp_mro's is in sym_to_type_map
for (Py_ssize_t i = 0; i < PyTuple_Size(subtype->tp_mro); i++) {
PyObject* item = PyTuple_GetItem(subtype->tp_mro, i);
auto symbol_result = type_to_sym_map.find((PyTypeObject*) item);
if (symbol_result != type_to_sym_map.end()) {
hbase = (PyHocObject*) hocobj_new(hocobject_type, 0, 0);
hbase->type_ = PyHoc::HocFunction;
hbase->sym_ = symbol_result->second;
break;
}
}
if (kwds && PyDict_Check(kwds) && (base = PyDict_GetItemString(kwds, "hocbase"))) {
if (PyObject_TypeCheck(base, hocobject_type)) {
hbase = (PyHocObject*) base;
} else {
PyErr_SetString(PyExc_TypeError, "HOC base class not valid");
return nullptr;
}
PyDict_DelItemString(kwds, "hocbase");
}
if (hbase and hbase->type_ == PyHoc::HocFunction && hbase->sym_->type == TEMPLATE) {
// printf("hocobj_new base %s\n", hbase->sym_->name);
// remove the hocbase keyword since hocobj_call only allows
// the "sec" keyword argument
auto r = nb::steal(hocobj_call(hbase, args, kwds));
if (!r) {
return nullptr;
}
PyHocObject* rh = (PyHocObject*) r.ptr();
self->type_ = rh->type_;
self->ho_ = rh->ho_;
hoc_obj_ref(self->ho_);
}
return subself.release().ptr();
}
static int hocobj_init(PyObject* subself, PyObject* args, PyObject* kwds) {
// printf("hocobj_init %s %p\n",
// ((PyTypeObject*)PyObject_Type(subself))->tp_name, subself);
#if 0
if (subself != NULL) {
PyHocObject* self = (PyHocObject*)subself;
if (self->ho_) { hoc_obj_unref(self->ho_); }
self->ho_ = NULL;
self->u.x_ = 0.;
self->sym_ = NULL;
self->indices_ = NULL;
self->nindex_ = 0;
self->type_ = 0;
}
#endif
return 0;
}
static void pyobject_in_objptr(Object** op, PyObject* po) {
Object* o = nrnpy_pyobject_in_obj(po);
if (*op) {
hoc_obj_unref(*op);
}
*op = o;
}
static PyObject* hocobj_name(PyObject* pself, PyObject* args) {
auto* const self = reinterpret_cast<PyHocObject*>(pself);
std::string cp;
if (self->type_ == PyHoc::HocObject) {
cp = hoc_object_name(self->ho_);
} else if (self->type_ == PyHoc::HocFunction || self->type_ == PyHoc::HocArray) {
if (self->ho_) {
cp.append(hoc_object_name(self->ho_));
cp.append(1, '.');
}
cp.append(self->sym_->name);
if (self->type_ == PyHoc::HocArray) {
for (int i = 0; i < self->nindex_; ++i) {
cp.append(1, '[');
cp.append(std::to_string(self->indices_[i]));
cp.append(1, ']');
}
cp.append("[?]");
} else {
cp.append("()");
}
} else if (self->type_ == PyHoc::HocRefNum) {
cp.append("<hoc ref value ");
cp.append(std::to_string(self->u.x_));
cp.append(1, '>');
} else if (self->type_ == PyHoc::HocRefStr) {
cp.append("<hoc ref str \"");
cp.append(self->u.s_);
cp.append("\">");
} else if (self->type_ == PyHoc::HocRefPStr) {
cp.append("<hoc ref pstr \"");
cp.append(*self->u.pstr_);
cp.append("\">");
} else if (self->type_ == PyHoc::HocRefObj) {
cp.append("<hoc ref value \"");
cp.append(hoc_object_name(self->u.ho_));
cp.append("\">");
} else if (self->type_ == PyHoc::HocForallSectionIterator) {
cp.append("<all section iterator next>");
} else if (self->type_ == PyHoc::HocSectionListIterator) {
cp.append("<SectionList iterator>");
} else if (self->type_ == PyHoc::HocScalarPtr) {
std::ostringstream oss;
oss << self->u.px_;
cp = std::move(oss).str();
} else if (self->type_ == PyHoc::HocArrayIncomplete) {
cp.append("<incomplete pointer to hoc array ");
cp.append(self->sym_->name);
cp.append(1, '>');
} else {
cp.append("<TopLevelHocInterpreter>");
}
return Py_BuildValue("s", cp.c_str());
}
static PyObject* hocobj_name_safe(PyObject* pself, PyObject* args) {
return nrn::convert_cxx_exceptions(hocobj_name, pself, args);
}
static PyObject* hocobj_repr(PyObject* p) {
return hocobj_name(p, NULL);
}
static Inst* save_pc(Inst* newpc) {
Inst* savpc = hoc_pc;
hoc_pc = newpc;
return savpc;
}
// also called from nrnpy_nrn.cpp
int hocobj_pushargs(PyObject* args, std::vector<neuron::unique_cstr>& s2free) {
int i, narg = PyTuple_Size(args);
for (i = 0; i < narg; ++i) {
PyObject* po = PyTuple_GetItem(args, i);
// PyObject_Print(po, stdout, 0);
// printf(" pushargs %d\n", i);
if (nrnpy_numbercheck(po)) {
nb::float_ pn(po);
hoc_pushx(static_cast<double>(pn));
} else if (is_python_string(po)) {
char** ts = hoc_temp_charptr();
Py2NRNString str(po, /* disable_release */ true);
if (str.err()) {
// Since Python error has been set, need to clear, or hoc_execerror
// printing with Printf will generate a
// Exception ignored on calling ctypes callback function.
// So get the message, clear, and make the message
// part of the execerror.
auto err = neuron::unique_cstr(str.get_pyerr());
*ts = err.c_str();
s2free.push_back(std::move(err));
hoc_execerr_ext("python string arg cannot decode into c_str. Pyerr message: %s",
*ts);
}
*ts = str.c_str();
s2free.push_back(neuron::unique_cstr(*ts));
hoc_pushstr(ts);
} else if (PyObject_TypeCheck(po, hocobject_type)) {
// The PyObject_TypeCheck above used to be PyObject_IsInstance. The
// problem with the latter is that it calls the __class__ method of
// the object which can raise an error for nrn.Section, nrn.Segment,
// etc. if the internal Section is invalid (Section.prop == NULL).
// That, in consequence, will generate an
// Exception ignored on calling ctypes callback function: <function Printf
// thus obscuring the actual error, such as
// nrn.Segment associated with deleted internal Section.
PyHocObject* pho = (PyHocObject*) po;
PyHoc::ObjectType tp = pho->type_;
if (tp == PyHoc::HocObject) {
hoc_push_object(pho->ho_);
} else if (tp == PyHoc::HocRefNum) {
hoc_pushpx(&pho->u.x_);
} else if (tp == PyHoc::HocRefStr) {
hoc_pushstr(&pho->u.s_);
} else if (tp == PyHoc::HocRefObj) {
hoc_pushobj(&pho->u.ho_);
} else if (tp == PyHoc::HocScalarPtr) {
if (!pho->u.px_) {
hoc_execerr_ext("Invalid pointer (arg %d)", i);
}
hoc_push(pho->u.px_);
} else if (tp == PyHoc::HocRefPStr) {
hoc_pushstr(pho->u.pstr_);
} else {
// make a hoc python object and push that
Object* ob = NULL;
pyobject_in_objptr(&ob, po);
hoc_push_object(ob);
hoc_obj_unref(ob);
}
} else { // make a hoc PythonObject and push that?
Object* ob = NULL;
if (po != Py_None) {
pyobject_in_objptr(&ob, po);
}
hoc_push_object(ob);
hoc_obj_unref(ob);
}
}
return narg;
}
static Symbol* getsym(char* name, Object* ho, int fail) {
Symbol* sym = 0;
if (ho) {
sym = hoc_table_lookup(name, ho->ctemplate->symtable);
if (!sym && strcmp(name, "delay") == 0) {
sym = hoc_table_lookup("del", ho->ctemplate->symtable);
} else if (!sym && ho->aliases) {
sym = ivoc_alias_lookup(name, ho);
}
} else {
sym = hoc_table_lookup(name, hoc_top_level_symlist);
if (!sym) {
sym = hoc_table_lookup(name, hoc_built_in_symlist);
}
}
if (sym && sym->type == UNDEF) {
sym = 0;
}
if (!sym && fail) {
char e[200];
Sprintf(e, "'%s' is not a defined hoc variable name.", name);
PyErr_SetString(PyExc_LookupError, e);
}
return sym;
}
// on entry the stack order is indices, args, object
// on exit all that is popped and the result is on the stack
// returns hoc_return_is_int if called on a builtin (i.e. 2 if bool, 1 if int, 0 otherwise)
static int component(PyHocObject* po) {
Inst fc[6];
int var_type = 0;
hoc_return_type_code = 0;
fc[0].sym = po->sym_;
fc[1].i = 0;
fc[2].i = 0;
fc[5].i = 0;
int stk_offset = 0; // scalar
if (po->type_ == PyHoc::HocFunction) {
fc[2].i = po->nindex_;
fc[5].i = 1;
stk_offset = po->nindex_;
} else if (po->type_ == PyHoc::HocArray || po->type_ == PyHoc::HocArrayIncomplete) {
fc[1].i = po->nindex_;
stk_offset = po->nindex_ + 1; // + 1 because of stack_ndim_datum
}
Object* stack_value = hoc_obj_look_inside_stack(stk_offset);
assert(stack_value == po->ho_);
fc[3].i = po->ho_->ctemplate->id;
fc[4].sym = po->sym_;
Inst* pcsav = save_pc(fc);
hoc_object_component();
hoc_pc = pcsav;
// only return a type if we're calling a built-in (these are all registered first)
if (po->ho_->ctemplate->id <= hoc_max_builtin_class_id) {
var_type = hoc_return_type_code;
}
hoc_return_type_code = 0;
return (var_type);
}
int nrnpy_numbercheck(PyObject* po) {
// PyNumber_Check can return 1 for things that should not reasonably
// be cast to float but should stay as python objects.
// e.g. numpy.arange(1,5) and 5J
// The complexity here is partly due to SAGE having its own
// number system, e.g. type(1) is <type 'sage.rings.integer.Integer'>
int rval = PyNumber_Check(po);
// but do not allow sequences
if (rval == 1 && po->ob_type->tp_as_sequence) {
rval = 0;
}
// or things that fail when float(po) fails. ARGGH! This
// is a lot more expensive than I would like.
if (rval == 1) {
nb::float_ tmp(po);
if (!tmp) {
PyErr_Clear();
rval = 0;
}
}
return rval;
}
PyObject* nrnpy_ho2po(Object* o) {
// o may be NULLobject, or encapsulate a Python object (via
// the PythonObject class in hoc (see Py2Nrn in nrnpy_p2h.cpp),
// or be a native hoc class instance such as Graph.
// The return value is None, or the encapsulated PyObject or
// an encapsulating PyHocObject
PyObject* po;
if (!o) {
po = Py_BuildValue("");
} else if (o->ctemplate->sym == nrnpy_pyobj_sym_) {
po = nrnpy_hoc2pyobject(o);
Py_INCREF(po);
} else {
po = hocobj_new(hocobject_type, 0, 0);
((PyHocObject*) po)->ho_ = o;
((PyHocObject*) po)->type_ = PyHoc::HocObject;
auto location = sym_to_type_map.find(o->ctemplate->sym);
if (location != sym_to_type_map.end()) {
Py_INCREF(location->second);
po->ob_type = location->second;
}
hoc_obj_ref(o);
}
return po;
}
// not static because it's used in nrnpy_nrn.cpp
Object* nrnpy_po2ho(PyObject* po) {
// po may be None, or encapsulate a hoc object (via the
// PyHocObject, or be a native Python instance such as [1,2,3]
// The return value is None, or the encapsulated hoc object,
// or a hoc object of type PythonObject that encapsulates the
// po.
Object* o;
if (po == Py_None) {
o = NULL;
} else if (PyObject_TypeCheck(po, hocobject_type)) {
PyHocObject* pho = (PyHocObject*) po;
if (pho->type_ == PyHoc::HocObject) {
o = pho->ho_;
hoc_obj_ref(o);
} else if (pho->type_ == PyHoc::HocRefObj) {
o = pho->u.ho_;
hoc_obj_ref(o);
} else {
// all the rest encapsulate
o = nrnpy_pyobject_in_obj(po);
}
} else { // even if Python string or number
o = nrnpy_pyobject_in_obj(po);
}
return o;
}
PyObject* nrnpy_hoc_pop(const char* mes) {
PyObject* result = 0;
Object* ho;
Object** d;
switch (hoc_stack_type()) {
case STRING:
result = Py_BuildValue("s", *hoc_strpop());
break;
case VAR: {
// remove mes arg when test coverage development completed
// printf("VAR nrnpy_hoc_pop %s\n", mes);
auto const px = hoc_pop_handle<double>();
if (nrn_chk_data_handle(px)) {
// unfortunately, this is nonsense if NMODL POINTER is pointing
// to something other than a double.
result = Py_BuildValue("d", *px);
}
} break;
case NUMBER:
result = Py_BuildValue("d", hoc_xpop());
break;
case OBJECTVAR:
case OBJECTTMP:
d = hoc_objpop();
ho = *d;
// printf("Py2Nrn %p %p\n", ho->ctemplate->sym, nrnpy_pyobj_sym_);
result = nrnpy_ho2po(ho);
hoc_tobj_unref(d);
break;
default:
printf("nrnpy_hoc_pop error: stack type = %d\n", hoc_stack_type());
}
return result;
}
static int set_final_from_stk(PyObject* po) {
int err = 0;
switch (hoc_stack_type()) {
case STRING:
char* s;
if (PyArg_Parse(po, "s", &s) == 1) {
hoc_assign_str(hoc_strpop(), s);
} else {
err = 1;
}
break;
case VAR: {
if (double x; PyArg_Parse(po, "d", &x) == 1) {
auto px = hoc_pop_handle<double>();
if (px) {
// This is a future crash if NMODL POINTER is pointing
// to something other than a double.
*px = x;
} else {
PyErr_SetString(PyExc_AttributeError, "POINTER is NULL");
return -1;
}
} else {
err = 1;
}
} break;
case OBJECTVAR:
PyHocObject* pho;
if (PyArg_Parse(po, "O!", hocobject_type, &pho) == 1) {
Object** pobj = hoc_objpop();
if (pho->sym_) {
PyErr_SetString(PyExc_TypeError, "argument cannot be a hoc object intermediate");
return -1;
}
Object* ob = *pobj;
hoc_obj_ref(pho->ho_);
hoc_obj_unref(ob);
*pobj = pho->ho_;
} else {
err = 1;
}
break;
default:
printf("set_final_from_stk() error: stack type = %d\n", hoc_stack_type());
err = 1;
break;
}
return err;
}
static void* nrnpy_hoc_int_pop() {
return (void*) Py_BuildValue("i", (long) hoc_xpop());
}
static void* nrnpy_hoc_bool_pop() {
return (void*) PyBool_FromLong((long) hoc_xpop());
}
static void* fcall(void* vself, void* vargs) {
PyHocObject* self = (PyHocObject*) vself;
if (self->ho_) {
hoc_push_object(self->ho_);
}
std::vector<neuron::unique_cstr> strings_to_free;
int narg = hocobj_pushargs((PyObject*) vargs, strings_to_free);
int var_type;
if (self->ho_) {
self->nindex_ = narg;
var_type = component(self);
switch (var_type) {
case 2:
return nrnpy_hoc_bool_pop();
case 1:
return nrnpy_hoc_int_pop();
default:
// No callable hoc function returns a data handle.
return nrnpy_hoc_pop("self->ho_ fcall");
}
}
if (self->sym_->type == BLTIN) {
if (narg != 1) {
hoc_execerror("must be one argument for", self->sym_->name);
}
double d = hoc_call_func(self->sym_, 1);
hoc_pushx(d);
} else if (self->sym_->type == TEMPLATE) {
Object* ho = hoc_newobj1(self->sym_, narg);
PyHocObject* result = (PyHocObject*) hocobj_new(hocobject_type, 0, 0);
result->ho_ = ho;
result->type_ = PyHoc::HocObject;
// Note: I think the only reason we're not using ho2po here is because we don't have to
// hocref ho since it was created by hoc_newobj1... but it would be better if we did
// so we could avoid repetitive code
auto location = sym_to_type_map.find(ho->ctemplate->sym);
if (location != sym_to_type_map.end()) {
Py_INCREF(location->second);
((PyObject*) result)->ob_type = location->second;
}
return result;
} else {
HocTopContextSet
Inst fc[4];
// ugh. so a potential call of hoc_get_last_pointer_symbol will return nullptr.
fc[0].in = STOP;
fc[1].sym = self->sym_;
fc[2].i = narg;
fc[3].in = STOP;
Inst* pcsav = save_pc(fc + 1);
hoc_call();
hoc_pc = pcsav;
HocContextRestore;
}
return nrnpy_hoc_pop("laststatement fcall");
}
static PyObject* curargs_;
PyObject* hocobj_call_arg(int i) {
return PyTuple_GetItem(curargs_, i);
}
static PyObject* hocobj_call(PyHocObject* self, PyObject* args, PyObject* kwrds) {
// Hack to allow some python only methods to get the python args.
// without losing info about type bool, int, etc.
// eg pc.py_broadcast, pc.py_gather, pc.py_allgather
PyObject* prevargs_ = curargs_;
curargs_ = args;
PyObject* section = 0;
PyObject* result{};
if (kwrds && PyDict_Check(kwrds)) {
#if 0
PyObject* keys = PyDict_Keys(kwrds);
assert(PyList_Check(keys));
int n = PyList_Size(keys);
for (int i = 0; i < n; ++i) {
PyObject* key = PyList_GetItem(keys, i);
PyObject* value = PyDict_GetItem(kwrds, key);
printf("%s %s\n", PyUnicode_AsUTF8(key), PyUnicode_AsUTF8(PyObject_Str(value)));
}
#endif
section = PyDict_GetItemString(kwrds, "sec");
int num_kwargs = PyDict_Size(kwrds);
if (num_kwargs > 1) {
PyErr_SetString(PyExc_RuntimeError, "invalid keyword argument");
curargs_ = prevargs_;
return NULL;
}
if (section) {
if (PyObject_TypeCheck(section, psection_type)) {
Section* sec = ((NPySecObj*) section)->sec_;
if (!sec->prop) {
nrnpy_sec_referr();
curargs_ = prevargs_;
return NULL;
}
nrn_pushsec(sec);
} else {
PyErr_SetString(PyExc_TypeError, "sec is not a Section");
curargs_ = prevargs_;
return NULL;
}
} else {
if (num_kwargs) {
PyErr_SetString(PyExc_RuntimeError, "invalid keyword argument");
curargs_ = prevargs_;
return NULL;
}
}
}
if (self->type_ == PyHoc::HocTopLevelInterpreter) {
result = nrnexec((PyObject*) self, args);
} else if (self->type_ == PyHoc::HocFunction) {
try {
result = static_cast<PyObject*>(OcJump::fpycall(fcall, self, args));
} catch (std::exception const& e) {
std::ostringstream oss;
oss << "hocobj_call error: " << e.what();
PyErr_SetString(PyExc_RuntimeError, oss.str().c_str());
}
hoc_unref_defer();
} else {
PyErr_SetString(PyExc_TypeError, "object is not callable");
curargs_ = prevargs_;
return NULL;
}
if (section) {
nrn_popsec();
}
curargs_ = prevargs_;
return result;
}
static Arrayinfo* hocobj_aray(Symbol* sym, Object* ho) {
if (!sym->arayinfo) {
return nullptr;
}
if (ho) { // objectdata or not?
int cplus = (ho->ctemplate->sym->subtype & (CPLUSOBJECT | JAVAOBJECT));
if (cplus) {
return sym->arayinfo;
} else {
return ho->u.dataspace[sym->u.oboff + 1].arayinfo;
}
} else {
if (sym->type == VAR &&
(sym->subtype == USERDOUBLE || sym->subtype == USERINT || sym->subtype == USERFLOAT)) {
return sym->arayinfo;
} else {
return hoc_top_level_data[sym->u.oboff + 1].arayinfo;
}
}
}
static PyHocObject* intermediate(PyHocObject* po, Symbol* sym, int ix) {
PyHocObject* ponew = (PyHocObject*) hocobj_new(hocobject_type, 0, 0);
if (po->ho_) {
ponew->ho_ = po->ho_;
hoc_obj_ref(po->ho_);
}
if (ix > -1) { // array, increase dimension by one
int j;
assert(po->sym_ == sym);
assert(po->type_ == PyHoc::HocArray || po->type_ == PyHoc::HocArrayIncomplete);
ponew->sym_ = sym;
ponew->nindex_ = po->nindex_ + 1;
ponew->type_ = po->type_;
ponew->indices_ = new int[ponew->nindex_];
for (j = 0; j < po->nindex_; ++j) {
ponew->indices_[j] = po->indices_[j];
}
ponew->indices_[po->nindex_] = ix;
} else { // make it an array (no indices yet)
ponew->sym_ = sym;
ponew->type_ = PyHoc::HocArray;
}
return ponew;
}
// when called, nindex is 1 less than reality
static void hocobj_pushtop(PyHocObject* po, Symbol* sym, int ix) {
int i;
int n = po->nindex_++;
// printf("hocobj_pushtop n=%d", po->nindex_);
for (i = 0; i < n; ++i) {
hoc_pushx((double) po->indices_[i]);
// printf(" %d", po->indices_[i]);
}
hoc_pushx((double) ix);
// printf(" %d\n", ix);
hoc_push_ndim(n + 1);
if (sym) {
hoc_pushs(sym);
}
}
static int hocobj_objectvar(Symbol* sym) {
int err{0};
try {
Inst fc;
fc.sym = sym;
Inst* pcsav = save_pc(&fc);
hoc_objectvar();
hoc_pc = pcsav;
} catch (std::exception const& e) {
std::ostringstream oss;
oss << "number of dimensions error:" << e.what();
PyErr_SetString(PyExc_IndexError, oss.str().c_str());
err = 1;
}
return err;
}
static PyObject* hocobj_getsec(Symbol* sym) {
Inst fc;
fc.sym = sym;
Inst* pcsav = save_pc(&fc);
sec_access_push();
hoc_pc = pcsav;
PyObject* result = nrnpy_cas(0, 0);
nrn_popsec();
return result;
}
// leave pointer on stack ready for get/set final
static void eval_component(PyHocObject* po, int ix) {
hoc_push_object(po->ho_);
hocobj_pushtop(po, 0, ix);
component(po);
--po->nindex_;
}
PyObject* nrn_hocobj_handle(neuron::container::data_handle<double> d) {
PyObject* result = hocobj_new(hocobject_type, 0, 0);
auto* const po = reinterpret_cast<PyHocObject*>(result);
po->type_ = PyHoc::HocScalarPtr;
po->u.px_ = d;
return result;
}
extern "C" NRN_EXPORT PyObject* nrn_hocobj_ptr(double* pd) {
return nrn_hocobj_handle(neuron::container::data_handle<double>{pd});
}
int nrn_is_hocobj_ptr(PyObject* po, neuron::container::data_handle<double>& pd) {
int ret = 0;
if (PyObject_TypeCheck(po, hocobject_type)) {
auto* const hpo = reinterpret_cast<PyHocObject*>(po);
if (hpo->type_ == PyHoc::HocScalarPtr) {
pd = hpo->u.px_;
ret = 1;
}
}
return ret;
}
static void symlist2dict(Symlist* sl, PyObject* dict) {
auto nn = nb::steal(Py_BuildValue(""));
for (Symbol* s = sl->first; s; s = s->next) {
if (s->type == UNDEF) {
continue;
}
if (s->cpublic == 1 || sl == hoc_built_in_symlist || sl == hoc_top_level_symlist) {
if (strcmp(s->name, "del") == 0) {
PyDict_SetItemString(dict, "delay", nn.ptr());
} else {
PyDict_SetItemString(dict, s->name, nn.ptr());
}
}
}
}
static int setup_doc_system() {
PyObject* pdoc;
if (pfunc_get_docstring) {
return 1;
}
pdoc = PyImport_ImportModule("neuron.doc");
if (pdoc == NULL) {
PyErr_SetString(PyExc_ImportError, "Failed to import neuron.doc documentation module.");