This repository has been archived by the owner on Sep 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
PyRegion.cpp
1286 lines (1094 loc) · 38.2 KB
/
PyRegion.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
/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
#include <py_region/PyRegion.hpp>
#include <numpy/arrayobject.h>
#include <iostream>
#include <sstream>
#include <memory>
#include <capnp/any.h>
#include <nupic/engine/Spec.hpp>
#include <nupic/engine/Region.hpp>
#include <nupic/engine/Input.hpp>
#include <nupic/engine/Output.hpp>
#include <nupic/utils/Log.hpp>
#include <nupic/ntypes/ObjectModel.hpp> // IWrite/ReadBuffer
#include <nupic/ntypes/Value.hpp>
#include <nupic/ntypes/Array.hpp>
#include <nupic/ntypes/ArrayRef.hpp>
#include <nupic/types/BasicType.hpp>
#include <nupic/ntypes/BundleIO.hpp>
#include <nupic/utils/Log.hpp>
#include <nupic/os/Path.hpp>
#include <py_support/PyArray.hpp>
using namespace nupic;
#define LAST_ERROR_LENGTH 1024
static char lastError[LAST_ERROR_LENGTH];
static bool finalizePython;
extern "C"
{
// NTA_initPython() must be called by the MultinodeFactory before any call to
// NTA_createPyNode()
NTA_EXPORT void NTA_initPython()
{
finalizePython = false;
// Initialize Python if it is not initialized already. Python will be initialized
// if NuPIC is accessed through the Python bindings and hence is already runnning
// inside a Python process.
if (!Py_IsInitialized())
{
//NTA_DEBUG << "Called Py_Initialize()";
Py_Initialize();
NTA_ASSERT(Py_IsInitialized());
finalizePython = true;
}
else
{
// Set the PyHelpers flag so it knows its running under Python.
// This is necessary for PyHelpers to determine if it should
// clear or restore Python exceptions (see NPC-113)
py::setRunningUnderPython();
}
// Important! the following statements must be outside the PyInitialize()
// conditional block because Python may already be initialized if used
// through the Python bindings.
// Initialize numpy.
import_array();
}
// NTA_finalizePython() must be called before unloading the pynode dynamic library
// to ensure proper cleanup.
NTA_EXPORT void NTA_finalizePython()
{
if (finalizePython)
{
//NTA_DEBUG << "Called Py_Finalize()";
Py_Finalize();
}
}
// createPyNode is used by the MultinodeFactory to create a C++ PyNode instance
// That references a Python instance. The function tries to create a NuPIC 2.0
// Py node first and if it fails it tries to create a NuPIC 1.x Py node
NTA_EXPORT void * NTA_createPyNode(const char * module, void * nodeParams,
void * region, void ** exception, const char* className)
{
try
{
NTA_CHECK(nodeParams != NULL);
NTA_CHECK(region != NULL);
ValueMap * valueMap = static_cast<nupic::ValueMap *>(nodeParams);
Region * r = static_cast<nupic::Region*>(region);
RegionImpl * p = NULL;
p = new nupic::PyRegion(module, *valueMap, r, className);
return p;
}
catch (nupic::Exception & e)
{
*exception = new nupic::Exception(e);
return NULL;
}
catch (...)
{
return NULL;
}
}
// deserializePyNode is used by the MultinodeFactory to create a C++ PyNode instance
// that references a Python instance which has been deserialized from saved state
NTA_EXPORT void * NTA_deserializePyNode(const char * module, void * bundle,
void * region, void ** exception, const char* className="")
{
try
{
NTA_CHECK(region != NULL);
Region * r = static_cast<nupic::Region*>(region);
BundleIO *b = static_cast<nupic::BundleIO*>(bundle);
RegionImpl * p = NULL;
p = new PyRegion(module, *b, r, className);
return p;
}
catch (nupic::Exception & e)
{
*exception = new nupic::Exception(e);
return NULL;
}
catch (...)
{
return NULL;
}
}
// getLatError() returns the last error message
NTA_EXPORT const char * NTA_getLastError()
{
return lastError;
}
// createSpec is used by the RegionImplFactory to get the node spec
// and cache it. It is a static function so there is no need to instantiate
// a dummy node, just to get its node spec.
NTA_EXPORT void * NTA_createSpec(const char * nodeType, void ** exception, const char* className="")
{
try
{
return PyRegion::createSpec(nodeType, className);
}
catch (nupic::Exception & e)
{
*exception = new nupic::Exception(e);
return NULL;
}
catch (...)
{
return NULL;
}
}
// destroySpec is used by the RegionImplFactory to destroy
// a cached node spec.
NTA_EXPORT int NTA_destroySpec(const char * nodeType, const char* className="")
{
try
{
PyRegion::destroySpec(nodeType, className);
return 0;
}
catch (...)
{
return -1;
}
}
}
// This map stores the node specs for all the Python nodes
std::map<std::string, Spec> PyRegion::specs_;
//
// Get the node spec from the underlying Python node
// and populate a dynamically C++ node spec object.
// Return the node spec pointer (that will be owned
// by RegionImplFactory.
//
Spec * PyRegion::createSpec(const char * nodeType, const char* className)
{
// If the node spec for a node type is requested more than once
// return the exisiting one from the map.
std::string name(nodeType);
std::string realClassName(className);
name = name + ".";
if (!realClassName.empty())
{
name = name + realClassName;
}
if (specs_.find(name) != specs_.end())
{
Spec & ns = specs_[name];
return &ns;
}
Spec ns;
createSpec(nodeType, ns, className);
specs_[name] = ns;
//NTA_DEBUG << "node type: " << nodeType << std::endl;
//NTA_DEBUG << specs_[name].toString() << std::endl;
return &specs_[name];
}
void PyRegion::destroySpec(const char * nodeType, const char* className)
{
std::string name(nodeType);
std::string realClassName(className);
name = name + ".";
if (!realClassName.empty())
{
name = name + realClassName;
}
specs_.erase(name);
}
namespace nupic
{
class RegionImpl;
static PyObject * makePyValue(const Value & v)
{
if (v.isArray())
return array2numpy(*(v.getArray().get()));
if (v.isString())
{
return py::String(*(v.getString().get())).release();
}
switch (v.getType())
{
case NTA_BasicType_Byte:
NTA_THROW << "Scalar parameters of type Byte are not supported";
break;
case NTA_BasicType_Int16:
return py::Long(v.getScalarT<NTA_Int16>()).release();
case NTA_BasicType_Int32:
return py::Long(v.getScalarT<NTA_Int32>()).release();
case NTA_BasicType_Int64:
return py::LongLong(v.getScalarT<NTA_Int64>()).release();
case NTA_BasicType_UInt16:
return py::UnsignedLong(v.getScalarT<NTA_UInt16>()).release();
case NTA_BasicType_UInt32:
return py::UnsignedLong(v.getScalarT<NTA_UInt32>()).release();
case NTA_BasicType_UInt64:
return py::UnsignedLongLong(v.getScalarT<NTA_UInt64>()).release();
case NTA_BasicType_Real32:
{
std::stringstream ss;
ss << v.getScalarT<NTA_Real32>();
return py::Float(ss.str().c_str()).release();
}
case NTA_BasicType_Real64:
return py::Float(v.getScalarT<NTA_Real64>()).release();
case NTA_BasicType_Handle:
return (PyObject *)(v.getScalarT<NTA_Handle>());
default:
NTA_THROW << "Invalid type: " << v.getType();
}
}
static void prepareCreationParams(const ValueMap & vm, py::Dict & d)
{
ValueMap::const_iterator it;
for (it = vm.begin(); it != vm.end(); ++it)
{
try
{
py::Ptr v(makePyValue(*(it->second)));
d.setItem(it->first, v);
} catch (Exception& e) {
NTA_THROW << "Unable to create a Python object for parameter '"
<< it->first << ": " << e.what();
}
}
};
PyRegion::PyRegion(const char * module, const ValueMap & nodeParams, Region *
region, const char* className) :
RegionImpl(region),
module_(module),
className_(className)
{
NTA_CHECK(region != NULL);
std::string realClassName(className);
if (realClassName.empty())
{
realClassName = Path::getExtension(module_);
}
// Prepare the creation params as a tuple of PyObject pointers
py::Tuple args((Py_ssize_t)0);
py::Dict kwargs;
prepareCreationParams(nodeParams, kwargs);
// Instantiate a node and assign it to the node_ member
node_.assign(py::Instance(module_, realClassName, args, kwargs));
NTA_CHECK(node_);
}
PyRegion::PyRegion(const char* module, BundleIO& bundle, Region * region, const
char* className) :
RegionImpl(region),
module_(module),
className_(className)
{
deserialize(bundle);
// XXX ADD CHECK TO MAKE SURE THE TYPE MATCHES!
}
PyRegion::~PyRegion()
{
for (std::map<std::string, Array*>::iterator i = inputArrays_.begin();
i != inputArrays_.end();
i++)
{
delete i->second;
i->second = NULL;
}
}
void PyRegion::serialize(BundleIO& bundle)
{
// 1. serialize main state using pickle
// 2. call class method to serialize external state
// 1. Serialize main state
// f = open(path, "wb")
py::Tuple args(2);
std::string path = bundle.getPath("pkl");
py::String filename(path);
py::String openmode("wb");
args.setItem(0, filename);
args.setItem(1, openmode);
py::Instance f("__builtin__", "file", args);
// cPickle.dump(node_, f, HIGHEST_PROTOCOL)
py::Module pickle("cPickle");
py::Tuple args2(3);
args2.setItem(0, node_);
args2.setItem(1, f);
args2.setItem(2, py::Int(2));
py::Ptr none(pickle.invoke("dump", args2));
// f.close()
py::Tuple args3(Py_ssize_t(0));
py::Ptr none2(f.invoke("close", args3));
// 2. External state
// Call the Python serializeExtraData() method
std::string externalPath = bundle.getPath("xtra");
py::Tuple args1(1);
args1.setItem(0, py::String(externalPath));
// Need to put the None result in py::Ptr to decrement the ref count
py::Ptr none1(node_.invoke("serializeExtraData", args1));
}
void PyRegion::deserialize(BundleIO& bundle)
{
// 1. deserialize main state using pickle
// 2. call class method to deserialize external state
// 1. de-serialize main state using pickle
// f = open(path, "rb") # binary mode needed on windows
py::Tuple args(2);
std::string path = bundle.getPath("pkl");
py::String filename(path);
args.setItem(0, filename);
py::String mode("rb");
args.setItem(1, mode);
py::Instance f("__builtin__", "file", args);
// node_ = cPickle.load(f)
py::Module pickle("cPickle");
py::Tuple args2(1);
args2.setItem(0, f);
node_.assign(py::Ptr(pickle.invoke("load", args2)));
// f.close()
py::Tuple args3((Py_ssize_t)0);
py::Ptr none2(f.invoke("close", args3));
// 2. External state
// Call the Python deSerializeExtraData() method
std::string externalPath = bundle.getPath("xtra");
py::Tuple args1(1);
args1.setItem(0, py::String(externalPath));
// Need to put the None result in py::Ptr to decrement the ref count
py::Ptr none1(node_.invoke("deSerializeExtraData", args1));
}
void PyRegion::write(capnp::AnyPointer::Builder& proto) const
{
NTA_THROW << "Unimplemented method PyRegion::write.";
}
void PyRegion::read(capnp::AnyPointer::Reader& proto)
{
NTA_THROW << "Unimplemented method PyRegion::read.";
}
const Spec & PyRegion::getSpec()
{
return *(PyRegion::createSpec(module_.c_str(), className_.c_str()));
}
////
//// Get the node spec from the underlying Python node
//// and populate a dynamically C++ node spec object.
//// Return the node spec pointer (that will be owned
//// by RegionImplFactory.
////
//void PyRegion::createSpec(const char * nodeType, Spec & ns)
//{
// // Get the Python class object
// std::string className = Path::getExtension(nodeType);
// py::Class nodeClass(nodeType, className);
//
// // Get the node spec from the Python class
// py::Dict nodeSpec(nodeClass.invoke("getSpec", py::Tuple()));
// //NTA_DEBUG << "'node spec' type: " << nodeSpec.getTypeName();
//
// // Extract the 4 dicts from the node spec
// py::Dict inputs(nodeSpec.getItem("inputs", py::Dict()));
// py::Dict outputs(nodeSpec.getItem("outputs", py::Dict()));
// py::Dict parameters(nodeSpec.getItem("parameters", py::Dict()));
// py::Dict commands(nodeSpec.getItem("commands", py::Dict()));
//
// // key, value and pos are used to iterate over the
// // inputs, outputs, parameters and commands dicts
// // of the Python node spec
// PyObject * key;
// PyObject * value;
// Py_ssize_t pos;
//
// // Add inputs
// pos = 0;
// while (PyDict_Next(inputs, &pos, &key, &value))
// {
// // key and value are borrowed from the dict. Their ref count
// // must be incremented so they can be used with
// // the Py helpers safely
// Py_INCREF(key);
// Py_INCREF(value);
//
// std::string name((const char *)(py::String(key)));
// py::Dict input(value);
//
// // Add an InputSpec object for each input spec dict
//
// std::string description(py::String(input.getItem("description")));
// std::string dt(py::String(input.getItem("dataType")));
// NTA_BasicType dataType(BasicType::parse(dt));
// UInt32 count = py::Int(input.getItem("count"));
// bool required = py::Int(input.getItem("required")) != 0;
// bool regionLevel = py::Int(input.getItem("regionLevel")) != 0;
// bool isDefaultInput = py::Int(input.getItem("isDefaultInput")) != 0;
// bool requireSplitterMap = py::Int(input.getItem("requireSplitterMap")) != 0;
// ns.inputs.add(
// name,
// InputSpec(
// description,
// dataType,
// count,
// required,
// regionLevel,
// isDefaultInput,
// requireSplitterMap));
// }
//
// // Add outputs
// pos = 0;
// while (PyDict_Next(outputs, &pos, &key, &value))
// {
// // key and value are borrowed from the dict. Their ref count
// // must be incremented so they can be used with
// // the Py helpers safely
// Py_INCREF(key);
// Py_INCREF(value);
//
// std::string name((const char *)(py::String(key)));
// py::Dict output(value);
//
// // Add an OutputSpec object for each output spec dict
// std::string description(py::String(output.getItem("description")));
// std::string dt(py::String(output.getItem("dataType")));
// NTA_BasicType dataType(BasicType::parse(dt));
// UInt32 count = py::Int(output.getItem("count"));
// bool regionLevel = py::Int(output.getItem("regionLevel")) != 0;
// bool isDefaultOutput = py::Int(output.getItem("isDefaultOutput")) != 0;
// ns.outputs.add(
// name,
// OutputSpec(
// description,
// dataType,
// count,
// regionLevel,
// isDefaultOutput));
// }
//
// // Add parameters
// pos = 0;
// while (PyDict_Next(parameters, &pos, &key, &value))
// {
// // key and value are borrowed from the dict. Their ref count
// // must be incremented so they can be used with
// // the Py helpers safely
// Py_INCREF(key);
// Py_INCREF(value);
//
// std::string name((const char *)(py::String(key)));
// py::Dict parameter(value);
//
// // Add an ParameterSpec object for each output spec dict
// std::string description(py::String(parameter.getItem("description")));
// std::string dt(py::String(parameter.getItem("dataType")));
// NTA_BasicType dataType(BasicType::parse(dt));
// UInt32 count = py::Int(parameter.getItem("count"));
// std::string constraints(py::String(parameter.getItem("constraints")));
// std::string defaultValue(py::String(parameter.getItem("defaultValue")));
// if (defaultValue == "None")
// defaultValue = "";
//
// ParameterSpec::AccessMode accessMode;
// std::string am(py::String(parameter.getItem("accessMode")));
// if (am == "Create")
// accessMode = ParameterSpec::CreateAccess;
// else if (am == "Read")
// accessMode = ParameterSpec::ReadOnlyAccess;
// else if (am == "ReadWrite")
// accessMode = ParameterSpec::ReadWriteAccess;
// else
// NTA_THROW << "Invalid access mode: " << am;
//
// ns.parameters.add(
// name,
// ParameterSpec(
// description,
// dataType,
// count,
// constraints,
// defaultValue,
// accessMode));
// }
//}
template <typename T, typename PyT>
T PyRegion::getParameterT(const std::string & name, Int64 index)
{
py::Tuple args(2);
args.setItem(0, py::String(name));
args.setItem(1, py::LongLong(index));
PyT result(node_.invoke("getParameter", args));
return T(result);
}
template <typename T, typename PyT>
void PyRegion::setParameterT(const std::string & name, Int64 index, T value)
{
py::Tuple args(3);
args.setItem(0, py::String(name));
args.setItem(1, py::LongLong(index));
args.setItem(2, PyT(value));
// Must catch the None return value and decrement
py::Ptr none(node_.invoke("setParameter", args));
}
Byte PyRegion::getParameterByte(const std::string& name, Int64 index)
{
return getParameterT<Byte, py::Int>(name, index);
}
Int32 PyRegion::getParameterInt32(const std::string& name, Int64 index)
{
//return getParameterT<Int32, py::Long>(name, index);
return getParameterT<Int32, py::Int>(name, index);
}
UInt32 PyRegion::getParameterUInt32(const std::string& name, Int64 index)
{
return getParameterT<UInt32, py::UnsignedLong>(name, index);
}
Int64 PyRegion::getParameterInt64(const std::string& name, Int64 index)
{
return getParameterT<Int64, py::LongLong>(name, index);
}
UInt64 PyRegion::getParameterUInt64(const std::string& name, Int64 index)
{
return getParameterT<UInt64, py::LongLong>(name, index);
}
Real32 PyRegion::getParameterReal32(const std::string& name, Int64 index)
{
return getParameterT<Real32, py::Float>(name, index);
}
Real64 PyRegion::getParameterReal64(const std::string& name, Int64 index)
{
return getParameterT<Real64, py::Float>(name, index);
}
Handle PyRegion::getParameterHandle(const std::string& name, Int64 index)
{
if (name == std::string("self"))
{
PyObject * o = (PyObject *)node_;
Py_INCREF(o);
return o;
}
return getParameterT<Handle, py::Ptr>(name, index);
}
void PyRegion::setParameterByte(const std::string& name, Int64 index, Byte value)
{
setParameterT<Byte, py::Int>(name, index, value);
}
void PyRegion::setParameterInt32(const std::string& name, Int64 index, Int32 value)
{
setParameterT<Int32, py::Long>(name, index, value);
}
void PyRegion::setParameterUInt32(const std::string& name, Int64 index, UInt32 value)
{
setParameterT<UInt32, py::UnsignedLong>(name, index, value);
}
void PyRegion::setParameterInt64(const std::string& name, Int64 index, Int64 value)
{
setParameterT<Int64, py::LongLong>(name, index, value);
}
void PyRegion::setParameterUInt64(const std::string& name, Int64 index, UInt64 value)
{
setParameterT<UInt64, py::UnsignedLongLong>(name, index, value);
}
void PyRegion::setParameterReal32(const std::string& name, Int64 index, Real32 value)
{
setParameterT<Real32, py::Float>(name, index, value);
}
void PyRegion::setParameterReal64(const std::string& name, Int64 index, Real64 value)
{
setParameterT<Real64, py::Float>(name, index, value);
}
void PyRegion::setParameterHandle(const std::string& name, Int64 index, Handle value)
{
setParameterT<PyObject *, py::Ptr>(name, index, (PyObject *)value);
}
void PyRegion::getParameterArray(const std::string& name, Int64 index, Array & a)
{
py::Tuple args(3);
args.setItem(0, py::String(name));
args.setItem(1, py::LongLong(index));
args.setItem(2, py::Ptr(array2numpy(a)));
// Must catch the None return value and decrement
py::Ptr none(node_.invoke("getParameterArray", args));
}
void PyRegion::setParameterArray(const std::string& name, Int64 index, const Array & a)
{
py::Tuple args(3);
args.setItem(0, py::String(name));
args.setItem(1, py::LongLong(index));
args.setItem(2, py::Ptr(array2numpy(a)));
// Must catch the None return value and decrement
py::Ptr none(node_.invoke("setParameterArray", args));
}
std::string PyRegion::getParameterString(const std::string& name, Int64 index)
{
py::Tuple args(2);
args.setItem(0, py::String(name));
args.setItem(1, py::LongLong(index));
py::String result(node_.invoke("getParameter", args));
return (const char*)result;
}
void PyRegion::setParameterString(const std::string& name, Int64 index, const std::string& value)
{
py::Tuple args(3);
args.setItem(0, py::String(name));
args.setItem(1, py::LongLong(index));
args.setItem(2, py::String(value));
py::Ptr none(node_.invoke("setParameter", args));
}
void PyRegion::getParameterFromBuffer(const std::string& name,
Int64 index,
IWriteBuffer& value)
{
// we override getParameterX for every type, so this should never
// be called
NTA_THROW << "::getParameterFromBuffer should not have been called";
}
void PyRegion::setParameterFromBuffer(const std::string& name,
Int64 index,
IReadBuffer& value)
{
// we override getParameterX for every type, so this should never
// be called
NTA_THROW << "::setParameterFromBuffer should not have been called";
}
size_t PyRegion::getParameterArrayCount(const std::string& name, Int64 index)
{
py::Tuple args(2);
args.setItem(0, py::String(name));
args.setItem(1, py::LongLong(index));
py::Int result(node_.invoke("getParameterArrayCount", args));
return size_t(result);
}
size_t PyRegion::getNodeOutputElementCount(const std::string& outputName)
{
py::Tuple args(1);
args.setItem(0, py::String(outputName));
py::Long result(node_.invoke("getOutputElementCount", args));
return size_t(result);
}
std::string PyRegion::executeCommand(const std::vector<std::string>& args, Int64 index)
{
py::String cmd(args[0]);
py::Tuple t(args.size() - 1);
for (size_t i = 1; i < args.size(); ++i)
{
py::String s(args[i]);
t.setItem(i-1, s);
}
py::Tuple commandArgs(2);
commandArgs.setItem(0, cmd);
commandArgs.setItem(1, t);
py::Instance res(node_.invoke("executeMethod", commandArgs));
py::String s(res.invoke("__str__", py::Tuple()));
const char * ss = (const char *)s;
std::string result(ss);
NTA_DEBUG << "Result of PyRegion::executeCommand : '" << result << "'";
return ss;
}
void PyRegion::compute()
{
const Spec & ns = getSpec();
// Prepare the inputs dict
py::Dict inputs;
for (size_t i = 0; i < ns.inputs.getCount(); ++i)
{
// Get the current InputSpec object
const std::pair<std::string, InputSpec> & p =
ns.inputs.getByIndex(i);
// Get the corresponding input buffer
Input * inp = region_->getInput(p.first);
NTA_CHECK(inp);
// Set pa to point to the original input array
const Array * pa = &(inp->getData());
// Skip unlinked inputs of size 0
if (pa->getCount() == 0)
continue;
// If the input requires a splitter map then
// Copy the original input array to the stored input array, which is larger
// by one element and put 0 in the extra element. This is needed for splitter map
// access.
if (p.second.requireSplitterMap)
{
// Verify that this input has a stored input array
NTA_ASSERT(inputArrays_.find(p.first) != inputArrays_.end());
Array & a = *(inputArrays_[p.first]);
// Verify that the stored input array is larger by 1 then the original input
NTA_ASSERT(a.getCount() == pa->getCount() + 1);
// Work at the char * level because there is no good way
// to work with the actual data type of the input (since the buffer is void *)
size_t itemSize = BasicType::getSize(p.second.dataType);
char * begin1 = (char *)pa->getBuffer();
char * end1 = begin1 + pa->getCount() * itemSize;
char * begin2 = (char *)a.getBuffer();
char * end2 = begin2 + a.getCount() * itemSize;
// Copy the original input array to the stored array
std::copy(begin1, end1, begin2);
// Put 0 in the last item (the sentinel value)
std::fill(end2 - itemSize, end2, 0);
// Change pa to point to the stored input array (with the sentinel)
pa = &a;
}
// Create a numpy array from pa, which wil be either
// the original input array or a stored input array
// (if a splitter map is needed)
py::Ptr numpyArray(array2numpy(*pa));
inputs.setItem(p.first, numpyArray);
}
// Prepare the outputs dict
py::Dict outputs;
for (size_t i = 0; i < ns.outputs.getCount(); ++i)
{
// Get the current OutputSpec object
const std::pair<std::string, OutputSpec> & p =
ns.outputs.getByIndex(i);
// Get the corresponding output buffer
Output * out = region_->getOutput(p.first);
// Skip optional outputs
if (!out)
continue;
const Array & data = out->getData();
py::Ptr numpyArray(array2numpy(data));
// Insert the buffer to the outputs py::Dict
outputs.setItem(p.first, numpyArray);
}
// Call the Python compute() method
py::Tuple args(2);
args.setItem(0, inputs);
args.setItem(1, outputs);
// Need to put the None result in py::Ptr to decrement the ref count
py::Ptr none(node_.invoke("compute", args));
}
//
// Get the node spec from the underlying Python node
// and populate a dynamically C++ node spec object.
// Return the node spec pointer (that will be owned
// by RegionImplFactory.
//
void PyRegion::createSpec(const char * nodeType, Spec & ns, const char* className)
{
// Get the Python class object
std::string realClassName(className);
if (realClassName.empty())
{
realClassName = Path::getExtension(nodeType);
}
py::Class nodeClass(nodeType, realClassName);
// Get the node spec from the Python class
py::Dict nodeSpec(nodeClass.invoke("getSpec", py::Tuple()));
// Extract the region deascription
py::String description(nodeSpec.getItem("description"));
ns.description = std::string(description);
// Extract the singleNodeOnly attribute
py::Int singleNodeOnly(nodeSpec.getItem("singleNodeOnly"));
ns.singleNodeOnly = singleNodeOnly != 0;
// Extract the 4 dicts from the node spec
py::Dict inputs(nodeSpec.getItem("inputs", py::Dict()));
//NTA_DEBUG << "'inputs' type: " << inputs.getTypeName();
py::Dict outputs(nodeSpec.getItem("outputs", py::Dict()));
py::Dict parameters(nodeSpec.getItem("parameters", py::Dict()));
py::Dict commands(nodeSpec.getItem("commands", py::Dict()));
// key, value and pos are used to iterate over the
// inputs, outputs, parameters and commands dicts
// of the Python node spec
PyObject * key;
PyObject * value;
Py_ssize_t pos;
// Add inputs
pos = 0;
while (PyDict_Next(inputs, &pos, &key, &value))
{
// key and value are borrowed from the dict. Their ref count
// must be incremented so they can be used with
// the Py helpers safely
Py_INCREF(key);
Py_INCREF(value);
std::string name((const char *)(py::String(key)));
py::Dict input(value);
// Add an InputSpec object for each input spec dict
std::ostringstream inputMessagePrefix;
inputMessagePrefix << "Region " << realClassName
<< " spec has missing key for input section " << name << ": ";
NTA_ASSERT(input.getItem("description") != nullptr)
<< inputMessagePrefix.str() << "description";
std::string description(py::String(input.getItem("description")));
NTA_ASSERT(input.getItem("dataType") != nullptr)
<< inputMessagePrefix.str() << "dataType";
std::string dt(py::String(input.getItem("dataType")));
NTA_BasicType dataType(BasicType::parse(dt));
NTA_ASSERT(input.getItem("count") != nullptr)
<< inputMessagePrefix.str() << "count";
UInt32 count = py::Int(input.getItem("count"));
NTA_ASSERT(input.getItem("required") != nullptr)
<< inputMessagePrefix.str() << "required";
bool required = py::Int(input.getItem("required")) != 0;
NTA_ASSERT(input.getItem("regionLevel") != nullptr)
<< inputMessagePrefix.str() << "regionLevel";
bool regionLevel = py::Int(input.getItem("regionLevel")) != 0;
NTA_ASSERT(input.getItem("isDefaultInput") != nullptr)
<< inputMessagePrefix.str() << "isDefaultInput";
bool isDefaultInput = py::Int(input.getItem("isDefaultInput")) != 0;
NTA_ASSERT(input.getItem("requireSplitterMap") != nullptr)
<< inputMessagePrefix.str() << "requireSplitterMap";
bool requireSplitterMap = py::Int(input.getItem("requireSplitterMap")) != 0;
ns.inputs.add(
name,
InputSpec(
description,
dataType,
count,
required,
regionLevel,
isDefaultInput,
requireSplitterMap));
}
// Add outputs
pos = 0;
while (PyDict_Next(outputs, &pos, &key, &value))
{
// key and value are borrowed from the dict. Their ref count
// must be incremented so they can be used with
// the Py helpers safely