From 9ef658e7b78d192987e2617660b2226b0c0b9023 Mon Sep 17 00:00:00 2001 From: Dilawar Singh Date: Sat, 21 Mar 2020 15:15:43 +0530 Subject: [PATCH 1/5] Fix to https://github.com/BhallaLab/moose-core/issues/397 --- pymoose/moosemodule.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/pymoose/moosemodule.cpp b/pymoose/moosemodule.cpp index d2cded75a0..41f82ad26c 100644 --- a/pymoose/moosemodule.cpp +++ b/pymoose/moosemodule.cpp @@ -2873,9 +2873,8 @@ PyObject * moose_element(PyObject* dummy, PyObject * args) Id id; unsigned int numData = 0; - // Parse into str or bytes-like object. Using 's' parses into const char* - // which is portable with bytes often returned when working with python3. - if (PyArg_ParseTuple(args, "s*", &path)) + // Don't use s* here: See https://github.com/BhallaLab/moose-core/issues/397 + if (PyArg_ParseTuple(args, "s", &path)) { oid = ObjId(path); if ( oid.bad() ) From f8dcb12e3778aae27d476c7a92f2bc97bc613663 Mon Sep 17 00:00:00 2001 From: Dilawar Singh Date: Sat, 21 Mar 2020 15:32:02 +0530 Subject: [PATCH 2/5] NUMPY is essential dependency; therefore numpy code is no longer included conditionally. USE_NUMPY is implied and have been removed from cmake. --- pymoose/CMakeLists.txt | 1 - pymoose/moosemodule.cpp | 98 +---------------------------------------- 2 files changed, 1 insertion(+), 98 deletions(-) diff --git a/pymoose/CMakeLists.txt b/pymoose/CMakeLists.txt index 86798d60a8..dbf5b49e82 100644 --- a/pymoose/CMakeLists.txt +++ b/pymoose/CMakeLists.txt @@ -15,7 +15,6 @@ endif() include_directories(${NUMPY_INCLUDE_DIRS}) add_definitions(-std=c++11) -add_definitions(-DUSE_NUMPY) add_definitions(-DNPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION) set(PYTHON_SO_EXTENSION ".so") diff --git a/pymoose/moosemodule.cpp b/pymoose/moosemodule.cpp index 41f82ad26c..67c2a4d083 100644 --- a/pymoose/moosemodule.cpp +++ b/pymoose/moosemodule.cpp @@ -496,92 +496,44 @@ PyObject * to_pytuple(void * obj, char typecode) { vector< double > * vec = static_cast< vector < double >* >(obj); assert(vec != NULL); -#ifndef USE_NUMPY - ret = PyTuple_New((Py_ssize_t)vec->size()); - for (unsigned int ii = 0; ii < vec->size(); ++ii) - { - if (0 != PyTuple_SetItem(ret, ii, PyFloat_FromDouble(vec->at(ii)))) - { - Py_DECREF(ret); - return NULL; - } - } -#else npy_intp size = (npy_intp)(vec->size()); ret = PyArray_SimpleNew(1, &size, NPY_DOUBLE); assert(ret != NULL); char * ptr = PyArray_BYTES((PyArrayObject*)ret); memcpy(ptr, &(*vec)[0], vec->size() * sizeof(double)); -#endif return ret; } case 'i': // vector { vector< int > * vec = static_cast< vector < int >* >(obj); assert(vec != NULL); -#ifndef USE_NUMPY - ret = PyTuple_New((Py_ssize_t)vec->size()); - for (unsigned int ii = 0; ii < vec->size(); ++ii) - { - if (0 != PyTuple_SetItem(ret, ii, PyInt_FromLong(vec->at(ii)))) - { - Py_DECREF(ret); - return NULL; - } - } -#else npy_intp size = (npy_intp)(vec->size()); ret = PyArray_SimpleNew(1, &size, NPY_INT); assert(ret != NULL); char * ptr = PyArray_BYTES((PyArrayObject*)ret); memcpy(ptr, &(*vec)[0], size * sizeof(int)); -#endif return ret; } case 'I': // vector { vector< int > * vec = static_cast< vector < int >* >(obj); assert(vec != NULL); -#ifndef USE_NUMPY - ret = PyTuple_New((Py_ssize_t)vec->size()); - for (unsigned int ii = 0; ii < vec->size(); ++ii) - { - if (0 != PyTuple_SetItem(ret, ii, PyLong_FromLong(vec->at(ii)))) - { - Py_DECREF(ret); - return NULL; - } - } -#else npy_intp size = (npy_intp)(vec->size()); ret = PyArray_SimpleNew(1, &size, NPY_UINT); assert(ret != NULL); char * ptr = PyArray_BYTES((PyArrayObject*)ret); memcpy(ptr, &(*vec)[0], size * sizeof(unsigned int)); -#endif return ret; } case 'l': // vector { vector< long > * vec = static_cast< vector < long >* >(obj); assert(vec != NULL); -#ifndef USE_NUMPY - ret = PyTuple_New((Py_ssize_t)vec->size()); - for (unsigned int ii = 0; ii < vec->size(); ++ii) - { - if (0 != PyTuple_SetItem(ret, ii, PyLong_FromLong(vec->at(ii)))) - { - Py_DECREF(ret); - return NULL; - } - } -#else npy_intp size = (npy_intp)(vec->size()); ret = PyArray_SimpleNew(1, &size, NPY_INT); assert(ret != NULL); char * ptr = PyArray_BYTES((PyArrayObject*)ret); memcpy(ptr, &(*vec)[0], size * sizeof(long)); -#endif return ret; } case 'x': // vector @@ -648,23 +600,11 @@ PyObject * to_pytuple(void * obj, char typecode) { vector< unsigned int > * vec = static_cast< vector < unsigned int >* >(obj); assert(vec != NULL); -#ifndef USE_NUMPY - ret = PyTuple_New((Py_ssize_t)vec->size()); - for (unsigned int ii = 0; ii < vec->size(); ++ii) - { - if (0 != PyTuple_SetItem(ret, ii, PyLong_FromUnsignedLong(vec->at(ii)))) - { - Py_DECREF(ret); - return NULL; - } - } -#else npy_intp size = (npy_intp)(vec->size()); ret = PyArray_SimpleNew(1, &size, NPY_UINT); assert(ret != NULL); char * ptr = PyArray_BYTES((PyArrayObject*)ret); memcpy(ptr, &(*vec)[0], size * sizeof(unsigned int)); -#endif return ret; } case 'L': // vector - this is not used at present @@ -672,68 +612,33 @@ PyObject * to_pytuple(void * obj, char typecode) vector< long long> * vec = static_cast< vector < long long>* >(obj); assert(vec != NULL); ret = PyTuple_New((Py_ssize_t)vec->size()); -#ifndef USE_NUMPY - for (unsigned int ii = 0; ii < vec->size(); ++ii) - { - if (0 != PyTuple_SetItem(ret, ii, PyLong_FromLongLong(vec->at(ii)))) - { - Py_DECREF(ret); - return NULL; - } - } -#else npy_intp size = (npy_intp)(vec->size()); ret = PyArray_SimpleNew(1, &size, NPY_LONGLONG); assert(ret != NULL); char * ptr = PyArray_BYTES((PyArrayObject*)ret); memcpy(ptr, &(*vec)[0], size * sizeof(long long)); -#endif return ret; } case 'K': // vector - this is not used at present { vector< unsigned long long> * vec = static_cast< vector < unsigned long long>* >(obj); assert(vec != NULL); -#ifndef USE_NUMPY - ret = PyTuple_New((Py_ssize_t)vec->size()); - for (unsigned int ii = 0; ii < vec->size(); ++ii) - { - if (0 != PyTuple_SetItem(ret, ii, PyLong_FromUnsignedLongLong(vec->at(ii)))) - { - Py_DECREF(ret); - return NULL; - } - } -#else npy_intp size = (npy_intp)(vec->size()); ret = PyArray_SimpleNew(1, &size, NPY_ULONGLONG); assert(ret != NULL); char * ptr = PyArray_BYTES((PyArrayObject*)ret); memcpy(ptr, &(*vec)[0], size * sizeof(unsigned long long)); -#endif return ret; } case 'F': // vector { vector< float > * vec = static_cast< vector < float >* >(obj); assert(vec != NULL); -#ifndef USE_NUMPY - ret = PyTuple_New((Py_ssize_t)vec->size()); - for (unsigned int ii = 0; ii < vec->size(); ++ii) - { - if (0 != PyTuple_SetItem(ret, ii, PyFloat_FromDouble(vec->at(ii)))) - { - Py_DECREF(ret); - return NULL; - } - } -#else npy_intp size = (npy_intp)(vec->size()); ret = PyArray_SimpleNew(1, &size, NPY_FLOAT); assert(ret != NULL); char * ptr = PyArray_BYTES((PyArrayObject*)ret); memcpy(ptr, &(*vec)[0], size * sizeof(float)); -#endif return ret; } case 's': // vector @@ -3056,9 +2961,8 @@ PyMODINIT_FUNC MODINIT(_moose) { cerr << "Failed to register finalize() to be called at exit. " << endl; } -#ifdef USE_NUMPY import_array(); -#endif + // Add Id type // Py_TYPE(&IdType) = &PyType_Type; // unnecessary - filled in by PyType_Ready IdType.tp_new = PyType_GenericNew; From c4d55aa61b423114b1a4277062c3d6a85eaaf324 Mon Sep 17 00:00:00 2001 From: Dilawar Singh Date: Sat, 21 Mar 2020 15:45:16 +0530 Subject: [PATCH 3/5] Minor cleanup in macros and loggers. numCores now use thread library to determine number of available threads. --- biophysics/CompartmentBase.h | 8 -- pymoose/melement.cpp | 4 - pymoose/pymooseinit.cpp | 160 ++--------------------------------- pymoose/vec.cpp | 2 +- python/moose/server.py | 55 +++++------- shell/Neutral.h | 8 -- 6 files changed, 31 insertions(+), 206 deletions(-) diff --git a/biophysics/CompartmentBase.h b/biophysics/CompartmentBase.h index a494a2c1b4..2be0fa05a7 100644 --- a/biophysics/CompartmentBase.h +++ b/biophysics/CompartmentBase.h @@ -11,14 +11,6 @@ #ifndef _COMPARTMENT_BASE_H #define _COMPARTMENT_BASE_H -#ifdef CYMOOSE - -template -class SrcFinfo1; - - -#endif /* ----- CYMOOSE ----- */ - /** * The CompartmentBase class sets up the interface for all the * derived Compartment classes, used in diff --git a/pymoose/melement.cpp b/pymoose/melement.cpp index 047788dab0..ebc799177f 100644 --- a/pymoose/melement.cpp +++ b/pymoose/melement.cpp @@ -5,10 +5,6 @@ #include #include -#ifdef USE_BOOST_ODE -#include -#endif - #include #include #include diff --git a/pymoose/pymooseinit.cpp b/pymoose/pymooseinit.cpp index e2257ddefe..04f3f87a37 100644 --- a/pymoose/pymooseinit.cpp +++ b/pymoose/pymooseinit.cpp @@ -8,9 +8,12 @@ **********************************************************************/ #include "../basecode/header.h" -#include -#include + +#include +#include #include +#include + #include "../scheduling/Clock.h" #include "../msg/DiagonalMsg.h" #include "../basecode/SparseMatrix.h" @@ -23,76 +26,14 @@ #include "../shell/Shell.h" -#ifdef MACOSX -#include -#endif // MACOSX - -#ifdef DO_UNIT_TESTS -extern void testSync(); -extern void testAsync(); -extern void testSyncArray( unsigned int size, unsigned int method ); -extern void testShell(); -extern void testScheduling(); -extern void testSchedulingProcess(); -extern void testBuiltins(); -extern void testBuiltinsProcess(); - -extern void testMpiScheduling(); -extern void testMpiBuiltins(); -extern void testMpiShell(); -extern void testMsg(); -extern void testMpiMsg(); -extern void testBiophysics(); -extern void testBiophysicsProcess(); -extern unsigned int initMsgManagers(); -extern void destroyMsgManagers(); -#endif // DO_UNIT_TESTS -extern void speedTestMultiNodeIntFireNetwork(unsigned int size, unsigned int runsteps ); - unsigned int getNumCores() { - unsigned int numCPU = 0; -#ifdef WIN_32 - SYSTEM_INFO sysinfo; - GetSystemInfo( &sysinfo ); - - numCPU = sysinfo.dwNumberOfProcessors; -#endif - -#ifdef LINUX - numCPU = sysconf( _SC_NPROCESSORS_ONLN ); -#endif - -#ifdef MACOSX - int mib[4]; - size_t len = sizeof(numCPU); - - /* set the mib for hw.ncpu */ - mib[0] = CTL_HW; - mib[1] = HW_AVAILCPU; // alternatively, try HW_NCPU; - - /* get the number of CPUs from the system */ - sysctl(mib, 2, &numCPU, &len, NULL, 0); - - if( numCPU < 1 ) - { - mib[1] = HW_NCPU; - sysctl( mib, 2, &numCPU, &len, NULL, 0 ); - } -#endif - -#if 0 - if ( numCPU < 1 ) - { - cout << "No CPU information available. Assuming single core." << endl; - numCPU = 1; - } -#endif - return numCPU; + auto numCores = std::thread::hardware_concurrency(); + if(0 == numCores) + numCores = 1; + return numCores; } -bool quitFlag = 0; -////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// void checkChildren( Id parent, const string& info ) @@ -159,88 +100,5 @@ Id init( int argc, char** argv, bool& doUnitTests) Cinfo::makeCinfoElements( classMasterId ); - - // This will be initialized within the Process loop, and better there - // as it flags attempts to call the Reduce operations before ProcessLoop - // Qinfo::clearReduceQ( numCores ); // Initialize the ReduceQ entry. - - - // SetGet::setShell(); - // Msg* m = new OneToOneMsg( shelle, shelle ); - // assert ( m != 0 ); - - while ( isInfinite ) // busy loop for debugging under gdb and MPI. - ; - return shellId; } - -/** - * These tests are meant to run on individual nodes, and should - * not invoke MPI calls. They should not be run when MPI is running. - * These tests do not use the threaded/MPI event loop and are the most - * basic of the set. - */ -void nonMpiTests( Shell* s ) -{ -#ifdef DO_UNIT_TESTS - if ( Shell::myNode() == 0 ) - { - unsigned int numNodes = s->numNodes(); - unsigned int numCores = s->numCores(); - if ( numCores > 0 ) - s->setHardware( 1, 1, 0 ); - testAsync(); - testMsg(); - testShell(); - testScheduling(); - testBuiltins(); - // testKinetics(); - // testKineticSolvers(); - testBiophysics(); - // testHSolve(); - // testGeom(); - // testMesh(); - // testSigNeur(); -#ifdef USE_SMOLDYN - // testSmoldyn(); -#endif - s->setHardware( numCores, numNodes, 0 ); - } -#endif -} - -/** - * These tests involve the threaded/MPI process loop and are the next - * level of tests. - */ -void processTests( Shell* s ) -{ -#ifdef DO_UNIT_TESTS - testSchedulingProcess(); - testBuiltinsProcess(); - // testKineticsProcess(); - testBiophysicsProcess(); - // testKineticSolversProcess(); - // testSimManager(); - // testSigNeurProcess(); -#endif -} - -/** - * These are tests that are MPI safe. They should also run - * properly on single nodes. - */ -void mpiTests() -{ -#ifdef DO_UNIT_TESTS - testMpiMsg(); - cout << "." << flush; - testMpiShell(); - cout << "." << flush; - testMpiBuiltins(); - cout << "." << flush; - testMpiScheduling(); - cout << "." << flush; -#endif -} diff --git a/pymoose/vec.cpp b/pymoose/vec.cpp index 8a3f5b4a1e..c2ba9bd01c 100644 --- a/pymoose/vec.cpp +++ b/pymoose/vec.cpp @@ -5,7 +5,7 @@ // Created: Mon Jul 22 16:46:37 2013 (+0530) #include -#include // This defines the type id macros like T_STRING +#include #include #include diff --git a/python/moose/server.py b/python/moose/server.py index 7f81d2e796..d7b1d05a8e 100644 --- a/python/moose/server.py +++ b/python/moose/server.py @@ -25,23 +25,10 @@ import tarfile import tempfile import threading -import logging import subprocess -# create a logger for this server. -logging.basicConfig( - level=logging.DEBUG, - format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', - datefmt='%m-%d %H:%M', - filename='moose_server.log', - filemode='a' - ) -console = logging.StreamHandler() -console.setLevel(logging.DEBUG) -formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') -console.setFormatter(formatter) -_logger = logging.getLogger('') -_logger.addHandler(console) +import logging +logger_ = logging.getLogger('moose.server') __all__ = [ 'serve' ] @@ -133,7 +120,7 @@ def prefix_data_with_size(data): def signal_handler(signum, frame): global stop_all_ global sock_ - _logger.info( "User terminated all processes." ) + logger_.info( "User terminated all processes." ) stop_all_ = True # sock_.shutdown( socket.SHUT_RDWR ) sock_.close() @@ -149,14 +136,14 @@ def send_msg(msg, conn, prefix='LOG'): if not msg.strip(): return False if prefix != 'TAB': - _logger.debug(msg) + logger_.debug(msg) else: - _logger.debug( 'Sending msg with size %d' % len(msg)) + logger_.debug( 'Sending msg with size %d' % len(msg)) msg = '<%s>%s' % (prefix, msg) conn.sendall(prefix_data_with_size(msg)) def run(cmd, conn, cwd=None): - _logger.info( "Executing %s" % cmd ) + logger_.info( "Executing %s" % cmd ) oldCWD = os.getcwd() if cwd is not None: os.chdir(cwd) @@ -176,7 +163,7 @@ def recv_input(conn, size=1024): try: d = conn.recv(prefixL_, socket.MSG_WAITALL) except Exception: - _logger.error("MSG FORMAT: %d bytes are size of msg."%prefixL_) + logger_.error("MSG FORMAT: %d bytes are size of msg."%prefixL_) continue d, data = int(d), b'' while len(data) < d: @@ -186,12 +173,12 @@ def recv_input(conn, size=1024): def writeTarfile( data ): tfile = os.path.join(tempfile.mkdtemp(), 'data.tar.bz2') with open(tfile, 'wb' ) as f: - _logger.info( "Writing %d bytes to %s" % (len(data), tfile)) + logger_.info( "Writing %d bytes to %s" % (len(data), tfile)) f.write(data) # Sleep for some time so that file can be written to disk. time.sleep(0.1) if not tarfile.is_tarfile(tfile): - _logger.warn( 'Not a valid tar file: %s' % tfile) + logger_.warning( 'Not a valid tar file: %s' % tfile) return None return tfile @@ -210,7 +197,7 @@ def streamer_client(socketPath, conn): # Connect to running socket server. global stop_streamer_ stop = False - _logger.debug( "Trying to connect to server at : %s" % socketPath ) + logger_.debug( "Trying to connect to server at : %s" % socketPath ) while not os.path.exists( socketPath ): #print( 'socket %s is not available yet.' % socketPath ) time.sleep(0.1) @@ -222,12 +209,12 @@ def streamer_client(socketPath, conn): try: stClient.connect(socketPath) except socket.error as e: - _logger.warning('Could not connect: %s' % e) + logger_.warning('Could not connect: %s' % e) return # send streaming data back to client. The streamer send fixed size messages # of 1024/2048 bytes each (see the c++ implmenetation). - _logger.info( "Socket Streamer is connected with server." ) + logger_.info( "Socket Streamer is connected with server." ) stClient.settimeout(0.05) send_msg( b'Now streaming table data.', conn, 'TAB') while not stop: @@ -258,7 +245,7 @@ def run_file(filename, conn, cwd=None): stop_streamer_[streamerThread.name] = True streamerThread.join( timeout = 1) if streamerThread.is_alive(): - _logger.error( "The socket streamer client is still running...") + logger_.error( "The socket streamer client is still running...") def extract_files(tfile, to): userFiles = [] @@ -267,11 +254,11 @@ def extract_files(tfile, to): try: f.extractall( to ) except Exception as e: - _logger.warn( e) + logger_.warning( e) # now check if all files have been extracted properly for f in userFiles: if not os.path.exists(f): - _logger.error( "File %s could not be extracted." % f ) + logger_.error( "File %s could not be extracted." % f ) return userFiles def prepareMatplotlib( cwd ): @@ -288,14 +275,14 @@ def sendResults(tdir, conn, notTheseFiles): resfile = os.path.join(resdir, 'results.tar.bz2') with tarfile.open( resfile, 'w|bz2') as tf: for f in find_files(tdir, ext='png'): - _logger.info( "Adding file %s" % f ) + logger_.info( "Adding file %s" % f ) tf.add(f, os.path.basename(f)) time.sleep(0.01) # now send the tar file back to client with open(resfile, 'rb' ) as f: data = f.read() - _logger.info( 'Total bytes to send to client: %d' % len(data)) + logger_.info( 'Total bytes to send to client: %d' % len(data)) send_bz2(conn, data) shutil.rmtree(resdir) @@ -348,11 +335,11 @@ def savePayload( conn ): def handle_client(conn, ip, port): isActive = True - _logger.info( "Serving request from %s:%s" % (ip, port) ) + logger_.info( "Serving request from %s:%s" % (ip, port) ) while isActive: tarfileName, nBytes = savePayload(conn) if tarfileName is None: - _logger.warn( "Could not recieve data." ) + logger_.warning( "Could not recieve data." ) isActive = False if not os.path.isfile(tarfileName): send_msg("[ERROR] %s is not a valid tarfile. Retry"%tarfileName, conn) @@ -379,9 +366,9 @@ def start_server( host, port, max_requests = 10 ): sock_.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) try: sock_.bind( (host, port)) - _logger.info( "Server created %s:%s" %(host,port) ) + logger_.info( "Server created %s:%s" %(host,port) ) except Exception as e: - _logger.error( "Failed to bind: %s" % e) + logger_.error( "Failed to bind: %s" % e) quit(1) # listen upto 10 of requests diff --git a/shell/Neutral.h b/shell/Neutral.h index 939d396b68..d2f7424103 100644 --- a/shell/Neutral.h +++ b/shell/Neutral.h @@ -11,14 +11,6 @@ #define _NEUTRAL_H -#ifdef CYMOOSE - -#include "../basecode/ProcInfo.h" - -class Cinfo; - -#endif /* ----- CYMOOSE ----- */ - class Neutral { public: From ad58dc5cd8b7ec47cd88f9eb95c41aed621e1c84 Mon Sep 17 00:00:00 2001 From: dilawars Date: Sat, 21 Mar 2020 21:24:21 +0530 Subject: [PATCH 4/5] include cmath in Pool.cpp as well. Failed compilation with gcc5.3 --- kinetics/Pool.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/kinetics/Pool.cpp b/kinetics/Pool.cpp index 9184c0fe22..eef25d480b 100644 --- a/kinetics/Pool.cpp +++ b/kinetics/Pool.cpp @@ -7,6 +7,8 @@ ** See the file COPYING.LIB for the full notice. **********************************************************************/ +#include + #include "../basecode/header.h" #include "../basecode/ElementValueFinfo.h" #include "../utility/print_function.hpp" From 5e660e9982644f33679b822b8404d95a4cba3376 Mon Sep 17 00:00:00 2001 From: dilawars Date: Sat, 21 Mar 2020 21:24:21 +0530 Subject: [PATCH 5/5] include cmath in Pool.cpp as well. Failed compilation with gcc5.3 --- kinetics/Pool.cpp | 2 + pymoose/PyRun.cpp | 289 ++--- pymoose/melement.cpp | 2132 +++++++++++++----------------- pymoose/moosemodule.cpp | 2706 +++++++++++++++++---------------------- pymoose/moosemodule.h | 10 +- pymoose/pymooseinit.cpp | 59 +- pymoose/vec.cpp | 1028 +++++++-------- 7 files changed, 2690 insertions(+), 3536 deletions(-) diff --git a/kinetics/Pool.cpp b/kinetics/Pool.cpp index 9184c0fe22..eef25d480b 100644 --- a/kinetics/Pool.cpp +++ b/kinetics/Pool.cpp @@ -7,6 +7,8 @@ ** See the file COPYING.LIB for the full notice. **********************************************************************/ +#include + #include "../basecode/header.h" #include "../basecode/ElementValueFinfo.h" #include "../utility/print_function.hpp" diff --git a/pymoose/PyRun.cpp b/pymoose/PyRun.cpp index 733ef0a255..95fbc69889 100644 --- a/pymoose/PyRun.cpp +++ b/pymoose/PyRun.cpp @@ -13,32 +13,29 @@ const int PyRun::RUNPROC = 1; const int PyRun::RUNTRIG = 2; const int PyRun::RUNBOTH = 0; -static SrcFinfo1< double >* outputOut() +static SrcFinfo1 *outputOut() { - static SrcFinfo1< double > outputOut( "output", - "Sends out the value of local variable called `output`. Thus, you can" - " have Python statements which compute some value and assign it to the" - " variable called `output` (which is defined at `reinit` call). This" - " will be sent out to any target connected to the `output` field."); + static SrcFinfo1 outputOut( + "output", + "Sends out the value of local variable called `output`. Thus, you can" + " have Python statements which compute some value and assign it to the" + " variable called `output` (which is defined at `reinit` call). This" + " will be sent out to any target connected to the `output` field."); return &outputOut; } - -const Cinfo * PyRun::initCinfo() +const Cinfo *PyRun::initCinfo() { - static ValueFinfo< PyRun, string > runstring( - "runString", - "String to be executed at each time step.", - &PyRun::setRunString, - &PyRun::getRunString); + static ValueFinfo runstring( + "runString", "String to be executed at each time step.", &PyRun::setRunString, &PyRun::getRunString); - static ValueFinfo< PyRun, string > initstring( + static ValueFinfo initstring( "initString", "String to be executed at initialization (reinit).", &PyRun::setInitString, &PyRun::getInitString); - static ValueFinfo< PyRun, string > inputvar( + static ValueFinfo inputvar( "inputVar", "Name of local variable in which input balue is to be stored. Default" " is `input_` (to avoid conflict with Python's builtin function" @@ -46,17 +43,18 @@ const Cinfo * PyRun::initCinfo() &PyRun::setInputVar, &PyRun::getInputVar); - static ValueFinfo< PyRun, string > outputvar( + static ValueFinfo outputvar( "outputVar", "Name of local variable for storing output. Default is `output`.", &PyRun::setOutputVar, &PyRun::getOutputVar); - static ValueFinfo< PyRun, int > mode( - "mode", - "Flag to indicate whether runString should be executed for both trigger and process, or one of them.", - &PyRun::setMode, - &PyRun::getMode); + static ValueFinfo mode("mode", + "Flag to indicate whether runString " + "should be executed for both trigger " + "and process, or one of them.", + &PyRun::setMode, + &PyRun::getMode); static DestFinfo trigger( "trigger", @@ -66,24 +64,23 @@ const Cinfo * PyRun::initCinfo() " `runString` (the underscore is added to avoid conflict with Python's" " builtin function `input`). If debug is True, it prints the input" " value.", - new EpFunc1< PyRun, double >(&PyRun::trigger)); + new EpFunc1(&PyRun::trigger)); - static DestFinfo run( - "run", - "Runs a specified string. Does not modify existing run or init strings.", - new EpFunc1< PyRun, string >(&PyRun::run)); + static DestFinfo run("run", + "Runs a specified string. Does not modify existing " + "run or init strings.", + new EpFunc1(&PyRun::run)); static DestFinfo process( "process", "Handles process call. Runs the current runString.", - new ProcOpFunc< PyRun >(&PyRun::process)); + new ProcOpFunc(&PyRun::process)); - static DestFinfo reinit( - "reinit", - "Handles reinit call. Runs the current initString.", - new ProcOpFunc< PyRun >( &PyRun::reinit )); + static DestFinfo reinit("reinit", + "Handles reinit call. Runs the current initString.", + new ProcOpFunc(&PyRun::reinit)); - static Finfo * processShared[] = { &process, &reinit }; + static Finfo *processShared[] = {&process, &reinit}; static SharedFinfo proc( "proc", "This is a shared message to receive Process messages " @@ -93,60 +90,52 @@ const Cinfo * PyRun::initCinfo() "ProcInfo, which holds lots of information about current " "time, thread, dt and so on. The second entry is a MsgDest " "for the Reinit operation. It also uses ProcInfo. ", - processShared, sizeof( processShared ) / sizeof( Finfo* )); - - static Finfo * pyRunFinfos[] = - { - &runstring, - &initstring, - &mode, - &inputvar, - &outputvar, - &trigger, - outputOut(), - &run, - &proc, - }; - - static string doc[] = - { - "Name", "PyRun", - "Author", "Subhasis Ray", - "Description", "Runs Python statements from inside MOOSE." - }; - static Dinfo< PyRun > dinfo; - static Cinfo pyRunCinfo( - "PyRun", - Neutral::initCinfo(), - pyRunFinfos, - sizeof(pyRunFinfos) / sizeof(Finfo*), - &dinfo, - doc, - sizeof(doc) / sizeof(string)); + processShared, + sizeof(processShared) / sizeof(Finfo *)); + + static Finfo *pyRunFinfos[] = {&runstring, &initstring, &mode, + &inputvar, &outputvar, &trigger, + outputOut(), &run, &proc, }; + + static string doc[] = { + "Name", "PyRun", + "Author", "Subhasis Ray", + "Description", "Runs Python statements from inside MOOSE."}; + static Dinfo dinfo; + static Cinfo pyRunCinfo("PyRun", + Neutral::initCinfo(), + pyRunFinfos, + sizeof(pyRunFinfos) / sizeof(Finfo *), + &dinfo, + doc, + sizeof(doc) / sizeof(string)); return &pyRunCinfo; } -static const Cinfo * pyRunCinfo = PyRun::initCinfo(); - -PyRun::PyRun():mode_(0), initstr_(""), runstr_(""), - globals_(0), locals_(0), - runcompiled_(0), initcompiled_(0), - inputvar_("input_"), outputvar_("output") +static const Cinfo *pyRunCinfo = PyRun::initCinfo(); + +PyRun::PyRun() + : mode_(0), + initstr_(""), + runstr_(""), + globals_(0), + locals_(0), + runcompiled_(0), + initcompiled_(0), + inputvar_("input_"), + outputvar_("output") { locals_ = PyDict_New(); - if (!locals_) - { + if (!locals_) { cerr << "Could not initialize locals dict" << endl; return; } - PyObject * value = PyFloat_FromDouble(0.0); - if (!value && PyErr_Occurred()) - { + PyObject *value = PyFloat_FromDouble(0.0); + if (!value && PyErr_Occurred()) { PyErr_Print(); return; } - if (PyDict_SetItemString(locals_, inputvar_.c_str(), value)) - { + if (PyDict_SetItemString(locals_, inputvar_.c_str(), value)) { PyErr_Print(); } } @@ -209,98 +198,82 @@ int PyRun::getMode() const return mode_; } -void PyRun::trigger(const Eref& e, double input) +void PyRun::trigger(const Eref &e, double input) { - if (!runcompiled_) - { + if (!runcompiled_) { return; } - if (mode_ == 1) - { + if (mode_ == 1) { return; } - PyObject * value = PyDict_GetItemString(locals_, inputvar_.c_str()); - if (value) - { + PyObject *value = PyDict_GetItemString(locals_, inputvar_.c_str()); + if (value) { Py_DECREF(value); } value = PyFloat_FromDouble(input); - if (!value && PyErr_Occurred()) - { + if (!value && PyErr_Occurred()) { PyErr_Print(); } - if (PyDict_SetItemString(locals_, inputvar_.c_str(), value)) - { + if (PyDict_SetItemString(locals_, inputvar_.c_str(), value)) { PyErr_Print(); } PyEval_EvalCode(runcompiled_, globals_, locals_); - if (PyErr_Occurred()) - { - PyErr_Print (); + if (PyErr_Occurred()) { + PyErr_Print(); } value = PyDict_GetItemString(locals_, outputvar_.c_str()); - if (value) - { + if (value) { double output = PyFloat_AsDouble(value); - if (PyErr_Occurred()) - { - PyErr_Print (); - } - else - { + if (PyErr_Occurred()) { + PyErr_Print(); + } else { outputOut()->send(e, output); } } } -void PyRun::run(const Eref&e, string statement) +void PyRun::run(const Eref &e, string statement) { PyRun_SimpleString(statement.c_str()); - PyObject * value = PyDict_GetItemString(locals_, outputvar_.c_str()); - if (value) - { + PyObject *value = PyDict_GetItemString(locals_, outputvar_.c_str()); + if (value) { double output = PyFloat_AsDouble(value); if (PyErr_Occurred()) - PyErr_Print (); + PyErr_Print(); else outputOut()->send(e, output); } } -void PyRun::process(const Eref & e, ProcPtr p) +void PyRun::process(const Eref &e, ProcPtr p) { // Make sure the get the GIL. Ksolve/Gsolve can be multithreaded. PyGILState_STATE gstate = PyGILState_Ensure(); // PyRun_String(runstr_.c_str(), 0, globals_, locals_); // PyRun_SimpleString(runstr_.c_str()); - if (! runcompiled_ || mode_ == 2) - { + if (!runcompiled_ || mode_ == 2) { return; } PyEval_EvalCode(runcompiled_, globals_, locals_); - if (PyErr_Occurred()) - { - PyErr_Print (); + if (PyErr_Occurred()) { + PyErr_Print(); return; } - PyObject * value = PyDict_GetItemString(locals_, outputvar_.c_str()); - if (value) - { + PyObject *value = PyDict_GetItemString(locals_, outputvar_.c_str()); + if (value) { double output = PyFloat_AsDouble(value); - if (PyErr_Occurred()) - { - PyErr_Print (); + if (PyErr_Occurred()) { + PyErr_Print(); return; - } - else + } else outputOut()->send(e, output); } - PyGILState_Release( gstate ); + PyGILState_Release(gstate); } /** @@ -310,83 +283,65 @@ void PyRun::process(const Eref & e, ProcPtr p) void handleError(bool syntax) { PyObject *exc, *val, *trb; - char * msg; + char *msg; - if (syntax && PyErr_ExceptionMatches (PyExc_SyntaxError)) - { - PyErr_Fetch (&exc, &val, &trb); /* clears exception! */ + if (syntax && PyErr_ExceptionMatches(PyExc_SyntaxError)) { + PyErr_Fetch(&exc, &val, &trb); /* clears exception! */ - if (PyArg_ParseTuple (val, "sO", &msg, &trb) && - !strcmp (msg, "unexpected EOF while parsing")) /* E_EOF */ + if (PyArg_ParseTuple(val, "sO", &msg, &trb) && + !strcmp(msg, "unexpected EOF while parsing")) /* E_EOF */ { - Py_XDECREF (exc); - Py_XDECREF (val); - Py_XDECREF (trb); - } - else /* some other syntax error */ + Py_XDECREF(exc); + Py_XDECREF(val); + Py_XDECREF(trb); + } else /* some other syntax error */ { - PyErr_Restore (exc, val, trb); - PyErr_Print (); + PyErr_Restore(exc, val, trb); + PyErr_Print(); } - } - else /* some non-syntax error */ + } else /* some non-syntax error */ { - PyErr_Print (); + PyErr_Print(); } } -void PyRun::reinit(const Eref& e, ProcPtr p) +void PyRun::reinit(const Eref &e, ProcPtr p) { - PyObject * main_module; - if (globals_ == NULL) - { + PyObject *main_module; + if (globals_ == NULL) { main_module = PyImport_AddModule("__main__"); globals_ = PyModule_GetDict(main_module); Py_XINCREF(globals_); } - if (locals_ == NULL) - { + if (locals_ == NULL) { locals_ = PyDict_New(); - if (!locals_) - { + if (!locals_) { cerr << "Could not initialize locals dict" << endl; } } - initcompiled_ = (PYCODEOBJECT*)Py_CompileString( - initstr_.c_str(), - get_program_name().c_str(), - Py_file_input); - if (!initcompiled_) - { + initcompiled_ = (PYCODEOBJECT *)Py_CompileString( + initstr_.c_str(), get_program_name().c_str(), Py_file_input); + if (!initcompiled_) { cerr << "Error compiling initString" << endl; handleError(true); - } - else - { + } else { PyEval_EvalCode(initcompiled_, globals_, locals_); - if (PyErr_Occurred()) - { - PyErr_Print (); + if (PyErr_Occurred()) { + PyErr_Print(); } } - assert( runstr_.size() > 0 ); + assert(runstr_.size() > 0); - runcompiled_ = (PYCODEOBJECT*)Py_CompileString( - runstr_.c_str(), - get_program_name().c_str(), - Py_file_input); - if (!runcompiled_) - { + runcompiled_ = (PYCODEOBJECT *)Py_CompileString( + runstr_.c_str(), get_program_name().c_str(), Py_file_input); + if (!runcompiled_) { cerr << "Error compiling runString" << endl; handleError(true); - } - else - { + } else { PyEval_EvalCode(runcompiled_, globals_, locals_); - if (PyErr_Occurred()) - { - PyErr_Print (); + if (PyErr_Occurred()) { + PyErr_Print(); } } } diff --git a/pymoose/melement.cpp b/pymoose/melement.cpp index ebc799177f..fa4f05a1eb 100644 --- a/pymoose/melement.cpp +++ b/pymoose/melement.cpp @@ -28,84 +28,63 @@ using namespace std; - extern PyTypeObject ObjIdType; extern PyTypeObject IdType; extern int PyType_IsSubtype(PyTypeObject *, PyTypeObject *); - -PyObject * get_ObjId_attr(_ObjId * oid, string attribute) +PyObject *get_ObjId_attr(_ObjId *oid, string attribute) { - if (attribute == "vec") - { + if (attribute == "vec") { return moose_ObjId_getId(oid); - } - else if (attribute == "dindex") - { + } else if (attribute == "dindex") { return moose_ObjId_getDataIndex(oid); - } - else if (attribute == "findex") - { + } else if (attribute == "findex") { return moose_ObjId_getFieldIndex(oid); } return NULL; } -int moose_ObjId_init_from_id(_ObjId * self, PyObject * args, PyObject * kwargs) +int moose_ObjId_init_from_id(_ObjId *self, PyObject *args, PyObject *kwargs) { extern PyTypeObject ObjIdType; - static const char* const kwlist[] = {"id", "dataIndex", "fieldIndex", NULL}; + static const char *const kwlist[] = {"id", "dataIndex", "fieldIndex", NULL}; unsigned int id = 0, data = 0, field = 0; - PyObject * obj = NULL; - if (PyArg_ParseTupleAndKeywords(args, kwargs, - "I|II:moose_ObjId_init_from_id", - (char**)kwlist, - &id, &data, &field)) - { + PyObject *obj = NULL; + if (PyArg_ParseTupleAndKeywords( + args, kwargs, "I|II:moose_ObjId_init_from_id", (char **)kwlist, &id, &data, &field)) { PyErr_Clear(); - if (!Id::isValid(id)) - { + if (!Id::isValid(id)) { RAISE_INVALID_ID(-1, "moose_ObjId_init_from_id"); } - self->oid_ = ObjId(Id(id), data, field ); - if (self->oid_.bad()) - { + self->oid_ = ObjId(Id(id), data, field); + if (self->oid_.bad()) { PyErr_SetString(PyExc_ValueError, "Invalid ObjId"); return -1; } return 0; } PyErr_Clear(); - if (PyArg_ParseTupleAndKeywords(args, kwargs, - "O|II:moose_ObjId_init_from_id", - (char**)kwlist, - &obj, &data, &field)) - { + if (PyArg_ParseTupleAndKeywords( + args, kwargs, "O|II:moose_ObjId_init_from_id", (char **)kwlist, &obj, &data, &field)) { PyErr_Clear(); // If first argument is an Id object, construct an ObjId out of it - if (Id_Check(obj)) - { - if (!Id::isValid(((_Id*)obj)->id_)) - { + if (Id_Check(obj)) { + if (!Id::isValid(((_Id *)obj)->id_)) { RAISE_INVALID_ID(-1, "moose_ObjId_init_from_id"); } - self->oid_ = ObjId(((_Id*)obj)->id_, data, field ); - if (self->oid_.bad()) - { - PyErr_SetString(PyExc_ValueError, "Invalid dataIndex/fieldIndex."); + self->oid_ = ObjId(((_Id *)obj)->id_, data, field); + if (self->oid_.bad()) { + PyErr_SetString(PyExc_ValueError, + "Invalid dataIndex/fieldIndex."); return -1; } return 0; - } - else if (PyObject_IsInstance(obj, (PyObject*)&ObjIdType)) - { - if (!Id::isValid(((_ObjId*)obj)->oid_.id)) - { + } else if (PyObject_IsInstance(obj, (PyObject *)&ObjIdType)) { + if (!Id::isValid(((_ObjId *)obj)->oid_.id)) { RAISE_INVALID_ID(-1, "moose_ObjId_init_from_id"); } - self->oid_ = ((_ObjId*)obj)->oid_; - if (self->oid_.bad()) - { + self->oid_ = ((_ObjId *)obj)->oid_; + if (self->oid_.bad()) { PyErr_SetString(PyExc_ValueError, "Invalid ObjId"); return -1; } @@ -115,33 +94,28 @@ int moose_ObjId_init_from_id(_ObjId * self, PyObject * args, PyObject * kwargs) return -1; } -int moose_ObjId_init_from_path(_ObjId * self, PyObject * args, - PyObject * kwargs) +int moose_ObjId_init_from_path(_ObjId *self, PyObject *args, PyObject *kwargs) { - static const char* const kwlist[] = {"path", "n", "g", "dtype", NULL}; - const char* parsedPath; + static const char *const kwlist[] = {"path", "n", "g", "dtype", NULL}; + const char *parsedPath; unsigned int numData = 1; unsigned int isGlobal = 0; - char* type = NULL; + char *type = NULL; - self->oid_ = ObjId( 0, BADINDEX ); - PyTypeObject * mytype = Py_TYPE(self); + self->oid_ = ObjId(0, BADINDEX); + PyTypeObject *mytype = Py_TYPE(self); string mytypename(mytype->tp_name); // First try to parse the arguments as (parsedPath, n, g, dtype) bool parse_success = false; - if (PyArg_ParseTupleAndKeywords(args, kwargs, - "s|IIs:moose_ObjId_init_from_path", - (char**)kwlist, - &parsedPath, &numData, &isGlobal, &type)) - { + if (PyArg_ParseTupleAndKeywords( + args, kwargs, "s|IIs:moose_ObjId_init_from_path", (char **)kwlist, &parsedPath, &numData, &isGlobal, &type)) { parse_success = true; } // we need to clear the parse error so that the callee can try // other alternative: moose_ObjId_init_from_id PyErr_Clear(); - if (!parse_success) - { + if (!parse_success) { return -2; } @@ -155,79 +129,68 @@ int moose_ObjId_init_from_path(_ObjId * self, PyObject * args, // First see if there is an existing object with at path self->oid_ = ObjId(path); - PyTypeObject* basetype = getBaseClass((PyObject*)self); + PyTypeObject *basetype = getBaseClass((PyObject *)self); string basetype_str; - if (type == NULL) - { - if (basetype == NULL) - { - PyErr_SetString(PyExc_TypeError - , "Unknown class. Need a valid MOOSE class or subclass thereof." - ); + if (type == NULL) { + if (basetype == NULL) { + PyErr_SetString( + PyExc_TypeError, + "Unknown class. Need a valid MOOSE class or subclass thereof."); return -1; } - basetype_str = string(basetype->tp_name).substr(6); // remove `moose.` prefix from type name - } - else - { + basetype_str = string(basetype->tp_name) + .substr(6); // remove `moose.` prefix from type name + } else { basetype_str = string(type); } - // If oid_ is bad, it can be either a nonexistent path or the root. - if (self->oid_.bad()) - { + if (self->oid_.bad()) { // is this the root element? - if ((path == "/") || (path == "/root")) - { - if ((basetype == NULL) || PyType_IsSubtype(mytype, basetype)) - { + if ((path == "/") || (path == "/root")) { + if ((basetype == NULL) || PyType_IsSubtype(mytype, basetype)) { return 0; } - err << "cannot convert moose." << Field::get(self->oid_, "className") - << " to " << mytypename - << "To get the existing object use `moose.element(obj)` instead."; + err << "cannot convert moose." + << Field::get(self->oid_, "className") << " to " + << mytypename << "To get the existing object use " + "`moose.element(obj)` instead."; PyErr_SetString(PyExc_TypeError, err.str().c_str()); return -1; } // no - so we need to create a new element - } - else // this is a non-root existing element + } else // this is a non-root existing element { // If the current class is a subclass of some predefined // moose class, do nothing. string className = self->oid_.element()->cinfo()->name(); - map ::iterator ii = - get_moose_classes().find( className ); + map::iterator ii = get_moose_classes().find(className); - PyTypeObject * basetype = 0; - if ( ii != get_moose_classes().end() ) - { + PyTypeObject *basetype = 0; + if (ii != get_moose_classes().end()) { basetype = ii->second; // remove `moose.` prefix from type name basetype_str = string(basetype->tp_name).substr(6); - } - else - { + } else { err << "Unknown class: " << className << endl; - basetype = getBaseClass((PyObject*)self); + basetype = getBaseClass((PyObject *)self); } // NOTE: Existing paths are handled in Shell::doCreate function. - if ((basetype != NULL) && PyType_IsSubtype(mytype, basetype)) - { + if ((basetype != NULL) && PyType_IsSubtype(mytype, basetype)) { // Fine. This path already exits. - err << "Accessing existing paths using object constrcutors has been deprecated. Use " + err << "Accessing existing paths using object constrcutors has " + "been deprecated. Use " << " moose.element to access existing object. In future " << " this will be an error." << endl; PyErr_WarnEx(PyExc_DeprecationWarning, err.str().c_str(), 1); return 0; } - // element exists at this path, but it does not inherit from any moose class. + // element exists at this path, but it does not inherit from any moose + // class. // throw an error - err << "cannot convert moose." << className - << " to " << mytypename + err << "cannot convert moose." << className << " to " << mytypename << ". To get the existing object use `moose.element(obj)` instead."; PyErr_SetString(PyExc_TypeError, err.str().c_str()); return -1; @@ -237,9 +200,7 @@ int moose_ObjId_init_from_path(_ObjId * self, PyObject * args, Id new_id = create_Id_from_path(path, numData, isGlobal, basetype_str); // vec failed. throw error - if (new_id == Id() && PyErr_Occurred()) - { - // Py_XDECREF(self); + if (new_id == Id() && PyErr_Occurred()) { return -1; } @@ -247,25 +208,22 @@ int moose_ObjId_init_from_path(_ObjId * self, PyObject * args, return 0; } -int moose_ObjId_init(_ObjId * self, PyObject * args, - PyObject * kwargs) +int moose_ObjId_init(_ObjId *self, PyObject *args, PyObject *kwargs) { - if (self && !PyObject_IsInstance((PyObject*)self, (PyObject*)Py_TYPE((PyObject*)self))) - { + if (self && !PyObject_IsInstance((PyObject *)self, + (PyObject *)Py_TYPE((PyObject *)self))) { ostringstream error; - error << "Expected an melement or subclass. Found " - << Py_TYPE(self)->tp_name; + error << "Expected an melement or subclass. Found " << Py_TYPE(self)->tp_name; PyErr_SetString(PyExc_TypeError, error.str().c_str()); return -1; } int ret = moose_ObjId_init_from_path(self, args, kwargs); - if (ret >= -1) - { + if (ret >= -1) { return ret; } - // parsing arguments as (path, dims, classname) failed. See if it is existing Id or ObjId. - if (moose_ObjId_init_from_id(self, args, kwargs) == 0) - { + // parsing arguments as (path, dims, classname) failed. See if it is + // existing Id or ObjId. + if (moose_ObjId_init_from_id(self, args, kwargs) == 0) { return 0; } PyErr_SetString(PyExc_ValueError, @@ -284,10 +242,9 @@ int moose_ObjId_init(_ObjId * self, PyObject * args, opeartions are byte order independent - so they should give the same result on both little- and big-endian systems. */ -long moose_ObjId_hash(_ObjId * self) +long moose_ObjId_hash(_ObjId *self) { - if (!Id::isValid(self->oid_.id)) - { + if (!Id::isValid(self->oid_.id)) { RAISE_INVALID_ID(-1, "moose_ObjId_hash"); } long long id = (long long)(self->oid_.id.value()); @@ -296,20 +253,16 @@ long moose_ObjId_hash(_ObjId * self) /* attempt to make it with 32 bit system - assuming id will * have its value within least significant 16 bits and * dataIndex and fieldIndex will be limited to first 8 bits */ - if (sizeof(size_t) == 8) - { + if (sizeof(size_t) == 8) { return id << 48 | dataIndex << 16 | fieldIndex; - } - else - { + } else { return id << 16 | dataIndex << 8 | fieldIndex; } } -PyObject * moose_ObjId_repr(_ObjId * self) +PyObject *moose_ObjId_repr(_ObjId *self) { - if (!Id::isValid(self->oid_.id)) - { + if (!Id::isValid(self->oid_.id)) { RAISE_INVALID_ID(NULL, "moose_ObjId_repr"); } ostringstream repr; @@ -320,10 +273,9 @@ PyObject * moose_ObjId_repr(_ObjId * self) return PyString_FromString(repr.str().c_str()); } // ! moose_ObjId_repr -PyObject * moose_ObjId_str(_ObjId * self) +PyObject *moose_ObjId_str(_ObjId *self) { - if (!Id::isValid(self->oid_.id)) - { + if (!Id::isValid(self->oid_.id)) { RAISE_INVALID_ID(NULL, "moose_ObjId_str"); } ostringstream repr; @@ -334,27 +286,27 @@ PyObject * moose_ObjId_str(_ObjId * self) return PyString_FromString(repr.str().c_str()); } // ! moose_ObjId_str -PyDoc_STRVAR(moose_ObjId_getId_documentation, - "getId() -> vec\n" - "\n" - "Returns the information of the object's classtype, Id, and path \n" - "in form of a vector.\n" - "\nExample\n" - "-------\n" - " >>> com = moose.Compartment('/com')\n" - " >>> com.getId()\n" - " moose.vec: class=Compartment, id=481, path=/com>" - "\n"); -PyObject* moose_ObjId_getId(_ObjId * self) +PyDoc_STRVAR( + moose_ObjId_getId_documentation, + "getId() -> vec\n" + "\n" + "Returns the information of the object's classtype, Id, and path \n" + "in form of a vector.\n" + "\nExample\n" + "-------\n" + " >>> com = moose.Compartment('/com')\n" + " >>> com.getId()\n" + " moose.vec: class=Compartment, id=481, path=/com>" + "\n"); +PyObject *moose_ObjId_getId(_ObjId *self) { - if (!Id::isValid(self->oid_.id)) - { + if (!Id::isValid(self->oid_.id)) { RAISE_INVALID_ID(NULL, "moose_ObjId_getId"); } extern PyTypeObject IdType; - _Id * ret = PyObject_New(_Id, &IdType); + _Id *ret = PyObject_New(_Id, &IdType); ret->id_ = self->oid_.id; - return (PyObject*)ret; + return (PyObject *)ret; } PyDoc_STRVAR(moose_ObjId_getFieldType_documentation, @@ -371,32 +323,30 @@ PyDoc_STRVAR(moose_ObjId_getFieldType_documentation, " >>> 'string,vector' \n" "\n"); -PyObject * moose_ObjId_getFieldType(_ObjId * self, PyObject * args) +PyObject *moose_ObjId_getFieldType(_ObjId *self, PyObject *args) { - if (!Id::isValid(self->oid_.id)) - { + if (!Id::isValid(self->oid_.id)) { RAISE_INVALID_ID(NULL, "moose_ObjId_getFieldType"); } - char * fieldName = NULL; - if (!PyArg_ParseTuple(args, "s:moose_ObjId_getFieldType", &fieldName)) - { + char *fieldName = NULL; + if (!PyArg_ParseTuple(args, "s:moose_ObjId_getFieldType", &fieldName)) { return NULL; } - string typeStr = getFieldType(Field::get(self->oid_, "className"), - string(fieldName)); - if (typeStr.length() <= 0) - { + string typeStr = + getFieldType(Field::get(self->oid_, "className"), string(fieldName)); + if (typeStr.length() <= 0) { PyErr_SetString(PyExc_ValueError, "Empty string for field type. " "Field name may be incorrect."); return NULL; } - PyObject * type = PyString_FromString(typeStr.c_str()); + PyObject *type = PyString_FromString(typeStr.c_str()); return type; -} // ! moose_Id_getFieldType +} // ! moose_Id_getFieldType /** - Wrapper over getattro to allow direct access as a function with variable argument list + Wrapper over getattro to allow direct access as a function with variable + argument list */ PyDoc_STRVAR(moose_ObjId_getField_documentation, @@ -411,299 +361,246 @@ PyDoc_STRVAR(moose_ObjId_getField_documentation, "\n" " >>> comp.getField('x0')\n" " >>> 0.0 \n"); -PyObject * moose_ObjId_getField(_ObjId * self, PyObject * args) +PyObject *moose_ObjId_getField(_ObjId *self, PyObject *args) { - if (!Id::isValid(self->oid_.id)) - { + if (!Id::isValid(self->oid_.id)) { RAISE_INVALID_ID(NULL, "moose_ObjId_getField"); } - PyObject * attr; - if (!PyArg_ParseTuple(args, "O:moose_ObjId_getField", &attr)) - { + PyObject *attr; + if (!PyArg_ParseTuple(args, "O:moose_ObjId_getField", &attr)) { return NULL; } return moose_ObjId_getattro(self, attr); } /** - 2011-03-28 13:59:41 (+0530) - - Get a specified field. Re-done on: 2011-03-23 14:42:03 (+0530) - - I wonder how to cleanly do this. The Id - ObjId dichotomy is - really ugly. When you don't pass an index, it is just treated - as 0. Then what is the point of having Id separately? ObjId - would been just fine! */ -PyObject * moose_ObjId_getattro(_ObjId * self, PyObject * attr) +PyObject *moose_ObjId_getattro(_ObjId *self, PyObject *attr) { int new_attr = 0; - if (self->oid_.bad()) - { + if (self->oid_.bad()) { RAISE_INVALID_ID(NULL, "moose_ObjId_getattro"); } - // extern PyTypeObject IdType; - // extern PyTypeObject ObjIdType; - const char * field; + const char *field; char ftype; - if (PyString_Check(attr)) - { + if (PyString_Check(attr)) { field = PyString_AsString(attr); + } else { + return PyObject_GenericGetAttr((PyObject *)self, attr); } - else - { - return PyObject_GenericGetAttr((PyObject*)self, attr); - } - PyObject * _ret = get_ObjId_attr(self, field); - if (_ret != NULL) - { + PyObject *_ret = get_ObjId_attr(self, field); + if (_ret != NULL) { return _ret; } string fieldName(field); string className = Field::get(self->oid_, "className"); vector valueFinfos = getFieldNames(className, "valueFinfo"); bool isValueField = false; - for (unsigned int ii = 0; ii < valueFinfos.size(); ++ii) - { - if (fieldName == valueFinfos[ii]) - { + for (unsigned int ii = 0; ii < valueFinfos.size(); ++ii) { + if (fieldName == valueFinfos[ii]) { isValueField = true; break; } } string type = getFieldType(className, fieldName); - if (type.empty() || !isValueField ) - { - // Check if this field name is aliased and update fieldName and type if so. + if (type.empty() || !isValueField) { + // Check if this field name is aliased and update fieldName and type if + // so. map::const_iterator it = get_field_alias().find(fieldName); - if (it != get_field_alias().end()) - { + if (it != get_field_alias().end()) { fieldName = it->second; field = fieldName.c_str(); isValueField = false; - for (unsigned int ii = 0; ii < valueFinfos.size(); ++ii) - { - if (fieldName == valueFinfos[ii]) - { + for (unsigned int ii = 0; ii < valueFinfos.size(); ++ii) { + if (fieldName == valueFinfos[ii]) { isValueField = true; break; } } type = getFieldType(Field::get(self->oid_, "className"), fieldName); - // Update attr for next level (PyObject_GenericGetAttr) in case. - // Py_XDECREF(attr); attr = PyString_FromString(field); new_attr = 1; } } - if (type.empty() || !isValueField) - { - _ret = PyObject_GenericGetAttr((PyObject*)self, attr); - if (new_attr) - { + if (type.empty() || !isValueField) { + _ret = PyObject_GenericGetAttr((PyObject *)self, attr); + if (new_attr) { Py_DECREF(attr); } return _ret; } ftype = shortType(type); - if (!ftype) - { - _ret = PyObject_GenericGetAttr((PyObject*)self, attr); - if (new_attr) - { + if (!ftype) { + _ret = PyObject_GenericGetAttr((PyObject *)self, attr); + if (new_attr) { Py_DECREF(attr); } return _ret; } - fieldName= string(field); - switch(ftype) - { - case 's': - { + fieldName = string(field); + switch (ftype) { + case 's': { string _s = Field::get(self->oid_, fieldName); _ret = Py_BuildValue("s", _s.c_str()); break; } - case 'd': - { - double value = Field< double >::get(self->oid_, fieldName); + case 'd': { + double value = Field::get(self->oid_, fieldName); _ret = to_py(&value, ftype); break; } - case 'i': - { + case 'i': { int value = Field::get(self->oid_, fieldName); _ret = to_py(&value, ftype); break; } - case 'I': - { + case 'I': { unsigned int value = Field::get(self->oid_, fieldName); _ret = to_py(&value, ftype); break; } - case 'l': - { + case 'l': { long value = Field::get(self->oid_, fieldName); _ret = to_py(&value, ftype); break; } - case 'L': - { + case 'L': { long long value = Field::get(self->oid_, fieldName); _ret = to_py(&value, ftype); break; } - case 'k': - { + case 'k': { unsigned long value = Field::get(self->oid_, fieldName); _ret = to_py(&value, ftype); break; } - case 'K': - { + case 'K': { unsigned long long value = Field::get(self->oid_, fieldName); _ret = to_py(&value, ftype); break; } - case 'f': - { + case 'f': { float value = Field::get(self->oid_, fieldName); _ret = to_py(&value, ftype); break; } - case 'x': - { + case 'x': { Id value = Field::get(self->oid_, fieldName); _ret = to_py(&value, ftype); break; } - case 'y': - { + case 'y': { ObjId value = Field::get(self->oid_, fieldName); _ret = to_py(&value, ftype); break; } - case 'z': - { - PyErr_SetString(PyExc_NotImplementedError, "DataId handling not implemented yet."); + case 'z': { + PyErr_SetString(PyExc_NotImplementedError, + "DataId handling not implemented yet."); _ret = NULL; break; } - case 'D': - { - vector< double > value = Field< vector < double > >::get(self->oid_, fieldName); + case 'D': { + vector value = Field>::get(self->oid_, fieldName); _ret = to_py(&value, ftype); break; } - case 'X': // vector + case 'X': // vector { - vector < Id > value = Field >::get(self->oid_, fieldName); + vector value = Field>::get(self->oid_, fieldName); _ret = to_py(&value, ftype); break; } - case 'Y': // vector + case 'Y': // vector { - vector < ObjId > value = Field >::get(self->oid_, fieldName); + vector value = Field>::get(self->oid_, fieldName); _ret = to_py(&value, ftype); break; } - case 'M': - { - vector< long > value = Field< vector >::get(self->oid_, fieldName); + case 'M': { + vector value = Field>::get(self->oid_, fieldName); _ret = to_py(&value, ftype); break; } - case 'P': - { - vector < unsigned long > value = Field< vector < unsigned long > >::get(self->oid_, fieldName); + case 'P': { + vector value = + Field>::get(self->oid_, fieldName); _ret = to_py(&value, ftype); break; } - case 'S': - { - vector < string > value = Field >::get(self->oid_, fieldName); + case 'S': { + vector value = Field>::get(self->oid_, fieldName); _ret = to_py(&value, ftype); break; } - case 'v': - { - vector < int > value = Field >::get(self->oid_, fieldName); + case 'v': { + vector value = Field>::get(self->oid_, fieldName); _ret = to_py(&value, ftype); break; } - case 'N': - { - vector value = Field< vector < unsigned int> >::get(self->oid_, fieldName); + case 'N': { + vector value = Field>::get(self->oid_, fieldName); _ret = to_py(&value, ftype); break; } - case 'T': // vector> + case 'T': // vector> { - vector < vector < unsigned int > > value = Field > >::get(self->oid_, fieldName); + vector> value = + Field>>::get(self->oid_, fieldName); _ret = to_py(&value, ftype); break; } - case 'Q': // vector< vector < int > > + case 'Q': // vector< vector < int > > { - vector < vector < int > > value = Field > >::get(self->oid_, fieldName); + vector> value = Field>>::get(self->oid_, fieldName); _ret = to_py(&value, ftype); break; } - case 'R': // vector< vector < double > > + case 'R': // vector< vector < double > > { - vector < vector < double > > value = Field > >::get(self->oid_, fieldName); + vector> value = + Field>>::get(self->oid_, fieldName); _ret = to_py(&value, ftype); break; } - case 'F': - { - vector value = Field< vector < float > >::get(self->oid_, fieldName); + case 'F': { + vector value = Field>::get(self->oid_, fieldName); _ret = to_py(&value, ftype); break; } - case 'c': - { + case 'c': { char value = Field::get(self->oid_, fieldName); _ret = to_py(&value, ftype); break; } - case 'h': - { + case 'h': { short value = Field::get(self->oid_, fieldName); _ret = to_py(&value, ftype); break; } - case 'H': - { + case 'H': { unsigned short value = Field::get(self->oid_, fieldName); _ret = to_py(&value, ftype); break; } - case 'w': - { - vector < short > value = Field >::get(self->oid_, fieldName); + case 'w': { + vector value = Field>::get(self->oid_, fieldName); _ret = to_py(&value, ftype); break; } - case 'C': - { - vector < char > value = Field >::get(self->oid_, fieldName); + case 'C': { + vector value = Field>::get(self->oid_, fieldName); _ret = to_py(&value, ftype); break; } - case 'b': - { + case 'b': { bool value = Field::get(self->oid_, fieldName); - if (value) - { + if (value) { _ret = Py_True; Py_INCREF(Py_True); - } - else - { + } else { _ret = Py_False; Py_INCREF(Py_False); } @@ -711,11 +608,9 @@ PyObject * moose_ObjId_getattro(_ObjId * self, PyObject * attr) } default: - _ret = PyObject_GenericGetAttr((PyObject*)self, attr); - + _ret = PyObject_GenericGetAttr((PyObject *)self, attr); } - if (new_attr) - { + if (new_attr) { Py_DECREF(attr); } return _ret; @@ -742,16 +637,14 @@ PyDoc_STRVAR(moose_ObjId_setField_documentation, " >>> print comp.x0\n" " 45.25\n"); -PyObject * moose_ObjId_setField(_ObjId * self, PyObject * args) +PyObject *moose_ObjId_setField(_ObjId *self, PyObject *args) { - PyObject * field; - PyObject * value; - if (!PyArg_ParseTuple(args, "OO:moose_ObjId_setField", &field, &value)) - { + PyObject *field; + PyObject *value; + if (!PyArg_ParseTuple(args, "OO:moose_ObjId_setField", &field, &value)) { return NULL; } - if (moose_ObjId_setattro(self, field, value) == -1) - { + if (moose_ObjId_setattro(self, field, value) == -1) { return NULL; } Py_RETURN_NONE; @@ -760,34 +653,30 @@ PyObject * moose_ObjId_setField(_ObjId * self, PyObject * args) /** Set a specified field. Redone on 2011-03-23 14:41:45 (+0530) */ -int moose_ObjId_setattro(_ObjId * self, PyObject * attr, PyObject * value) +int moose_ObjId_setattro(_ObjId *self, PyObject *attr, PyObject *value) { - if (!Id::isValid(self->oid_.id)) - { + if (!Id::isValid(self->oid_.id)) { RAISE_INVALID_ID(-1, "moose_ObjId_setattro"); } - const char * field; - if (PyString_Check(attr)) - { + const char *field; + if (PyString_Check(attr)) { field = PyString_AsString(attr); - } - else - { + } else { PyErr_SetString(PyExc_TypeError, "Attribute name must be a string"); return -1; } - string fieldtype = getFieldType(Field::get(self->oid_, "className"), string(field)); - if (fieldtype.length() == 0) - { + string fieldtype = + getFieldType(Field::get(self->oid_, "className"), string(field)); + if (fieldtype.length() == 0) { // If it is instance of a MOOSE built-in class then throw // error (to avoid silently creating new attributes due to // typos). Otherwise, it must have been subclassed in // Python. Then we allow normal Pythonic behaviour and // consider such mistakes user's responsibility. - string className = ((PyTypeObject*)PyObject_Type((PyObject*)self))->tp_name; - if (get_moose_classes().find(className) == get_moose_classes().end()) - { - return PyObject_GenericSetAttr((PyObject*)self, PyString_FromString(field), value); + string className = ((PyTypeObject *)PyObject_Type((PyObject *)self))->tp_name; + if (get_moose_classes().find(className) == get_moose_classes().end()) { + return PyObject_GenericSetAttr( + (PyObject *)self, PyString_FromString(field), value); } ostringstream msg; msg << "'" << className << "' class has no field '" << field << "'" << endl; @@ -796,349 +685,306 @@ int moose_ObjId_setattro(_ObjId * self, PyObject * attr, PyObject * value) } char ftype = shortType(fieldtype); int ret = 0; - switch(ftype) - { - case 'd': - { + switch (ftype) { + case 'd': { double _value = PyFloat_AsDouble(value); ret = Field::set(self->oid_, string(field), _value); break; } - case 'l': - { + case 'l': { long _value = PyInt_AsLong(value); - if ((_value != -1) || (!PyErr_Occurred())) - { + if ((_value != -1) || (!PyErr_Occurred())) { ret = Field::set(self->oid_, string(field), _value); } break; } - case 'I': - { + case 'I': { unsigned long _value = PyInt_AsUnsignedLongMask(value); ret = Field::set(self->oid_, string(field), (unsigned int)_value); break; } - case 'k': - { + case 'k': { unsigned long _value = PyInt_AsUnsignedLongMask(value); ret = Field::set(self->oid_, string(field), _value); break; } - case 'f': - { + case 'f': { float _value = PyFloat_AsDouble(value); ret = Field::set(self->oid_, string(field), _value); break; } - case 's': - { - char * _value = PyString_AsString(value); - if (_value) - { + case 's': { + char *_value = PyString_AsString(value); + if (_value) { ret = Field::set(self->oid_, string(field), string(_value)); } break; } - case 'x': // Id + case 'x': // Id { - if (value) - { - ret = Field::set(self->oid_, string(field), ((_Id*)value)->id_); - } - else - { - PyErr_SetString(PyExc_ValueError, "Null pointer passed as vec Id value."); + if (value) { + ret = Field::set(self->oid_, string(field), ((_Id *)value)->id_); + } else { + PyErr_SetString(PyExc_ValueError, + "Null pointer passed as vec Id value."); return -1; } break; } - case 'y': // ObjId + case 'y': // ObjId { - if (value) - { - ret = Field::set(self->oid_, string(field), ((_ObjId*)value)->oid_); - } - else - { - PyErr_SetString(PyExc_ValueError, "Null pointer passed as vec Id value."); + if (value) { + ret = Field::set(self->oid_, string(field), ((_ObjId *)value)->oid_); + } else { + PyErr_SetString(PyExc_ValueError, + "Null pointer passed as vec Id value."); return -1; } break; } - case 'D': //SET_VECFIELD(double, d) + case 'D': // SET_VECFIELD(double, d) { - if (!PySequence_Check(value)) - { - PyErr_SetString(PyExc_TypeError, "For setting vector field, specified value must be a sequence." ); - } - else - { + if (!PySequence_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "For setting vector field, specified " + "value must be a sequence."); + } else { Py_ssize_t length = PySequence_Length(value); vector _value; - for ( int ii = 0; ii < length; ++ii) - { - PyObject * vo = PySequence_GetItem(value, ii); + for (int ii = 0; ii < length; ++ii) { + PyObject *vo = PySequence_GetItem(value, ii); double v = PyFloat_AsDouble(vo); Py_XDECREF(vo); _value.push_back(v); } - ret = Field< vector < double > >::set(self->oid_, string(field), _value); + ret = Field>::set(self->oid_, string(field), _value); } break; } - case 'b': - { + case 'b': { bool _value = (Py_True == value) || (PyInt_AsLong(value) != 0); ret = Field::set(self->oid_, string(field), _value); break; } - case 'c': - { - char * _value = PyString_AsString(value); - if (_value && _value[0]) - { + case 'c': { + char *_value = PyString_AsString(value); + if (_value && _value[0]) { ret = Field::set(self->oid_, string(field), _value[0]); } break; } - case 'i': - { + case 'i': { int _value = PyInt_AsLong(value); - if ((_value != -1) || (!PyErr_Occurred())) - { + if ((_value != -1) || (!PyErr_Occurred())) { ret = Field::set(self->oid_, string(field), _value); } break; } - case 'h': - { + case 'h': { short _value = (short)PyInt_AsLong(value); - if ((_value != -1) || (!PyErr_Occurred())) - { + if ((_value != -1) || (!PyErr_Occurred())) { ret = Field::set(self->oid_, string(field), _value); } break; } - case 'z': // DataId + case 'z': // DataId { - PyErr_SetString(PyExc_NotImplementedError, "DataId handling not implemented yet."); + PyErr_SetString(PyExc_NotImplementedError, + "DataId handling not implemented yet."); return -1; } - case 'v': - { - if (!PySequence_Check(value)) - { - PyErr_SetString(PyExc_TypeError, "For setting vector field, specified value must be a sequence." ); + case 'v': { + if (!PySequence_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "For setting vector field, specified " + "value must be a sequence."); } Py_ssize_t length = PySequence_Length(value); vector _value; - for ( int ii = 0; ii < length; ++ii) - { - PyObject * vo = PySequence_GetItem(value, ii); + for (int ii = 0; ii < length; ++ii) { + PyObject *vo = PySequence_GetItem(value, ii); int v = PyInt_AsLong(vo); Py_XDECREF(vo); _value.push_back(v); } - ret = Field< vector < int > >::set(self->oid_, string(field), _value); + ret = Field>::set(self->oid_, string(field), _value); break; } - case 'w': - { - if (!PySequence_Check(value)) - { - PyErr_SetString(PyExc_TypeError, "For setting vector field, specified value must be a sequence." ); - } - else - { + case 'w': { + if (!PySequence_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "For setting vector field, specified " + "value must be a sequence."); + } else { Py_ssize_t length = PySequence_Length(value); vector _value; - for ( int ii = 0; ii < length; ++ii) - { - PyObject * vo = PySequence_GetItem(value, ii); + for (int ii = 0; ii < length; ++ii) { + PyObject *vo = PySequence_GetItem(value, ii); short v = PyInt_AsLong(vo); Py_XDECREF(vo); _value.push_back(v); } - ret = Field< vector < short > >::set(self->oid_, string(field), _value); + ret = Field>::set(self->oid_, string(field), _value); } break; } - case 'L': //SET_VECFIELD(long, l) + case 'L': // SET_VECFIELD(long, l) { - if (!PySequence_Check(value)) - { + if (!PySequence_Check(value)) { PyErr_SetString(PyExc_TypeError, - "For setting vector field, specified value must be a sequence." ); - } - else - { + "For setting vector field, specified " + "value must be a sequence."); + } else { Py_ssize_t length = PySequence_Length(value); vector _value; - for ( int ii = 0; ii < length; ++ii) - { - PyObject * vo = PySequence_GetItem(value, ii); + for (int ii = 0; ii < length; ++ii) { + PyObject *vo = PySequence_GetItem(value, ii); long v = PyInt_AsLong(vo); Py_XDECREF(vo); _value.push_back(v); } - ret = Field< vector < long > >::set(self->oid_, string(field), _value); + ret = Field>::set(self->oid_, string(field), _value); } break; } - case 'N': //SET_VECFIELD(unsigned int, I) + case 'N': // SET_VECFIELD(unsigned int, I) { - if (!PySequence_Check(value)) - { - PyErr_SetString(PyExc_TypeError, "For setting vector field, specified value must be a sequence." ); - } - else - { + if (!PySequence_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "For setting vector field, " + "specified value must be a sequence."); + } else { Py_ssize_t length = PySequence_Length(value); vector _value; - for ( int ii = 0; ii < length; ++ii) - { - PyObject * vo = PySequence_GetItem(value, ii); + for (int ii = 0; ii < length; ++ii) { + PyObject *vo = PySequence_GetItem(value, ii); unsigned int v = PyInt_AsUnsignedLongMask(vo); Py_XDECREF(vo); _value.push_back(v); } - ret = Field< vector < unsigned int > >::set(self->oid_, string(field), _value); + ret = Field>::set(self->oid_, string(field), _value); } break; } - case 'K': //SET_VECFIELD(unsigned long, k) + case 'K': // SET_VECFIELD(unsigned long, k) { - if (!PySequence_Check(value)) - { - PyErr_SetString(PyExc_TypeError, "For setting vector field, specified value must be a sequence." ); - } - else - { + if (!PySequence_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "For setting vector field, " + "specified value must be a sequence."); + } else { Py_ssize_t length = PySequence_Length(value); vector _value; - for ( int ii = 0; ii < length; ++ii) - { - PyObject * vo = PySequence_GetItem(value, ii); + for (int ii = 0; ii < length; ++ii) { + PyObject *vo = PySequence_GetItem(value, ii); unsigned long v = PyInt_AsUnsignedLongMask(vo); Py_XDECREF(vo); _value.push_back(v); } - ret = Field< vector < unsigned long > >::set(self->oid_, string(field), _value); + ret = Field>::set(self->oid_, string(field), _value); } break; } - case 'F': //SET_VECFIELD(float, f) + case 'F': // SET_VECFIELD(float, f) { - if (!PySequence_Check(value)) - { - PyErr_SetString(PyExc_TypeError, "For setting vector field, specified value must be a sequence." ); - } - else - { + if (!PySequence_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "For setting vector field, specified " + "value must be a sequence."); + } else { Py_ssize_t length = PySequence_Length(value); vector _value; - for ( int ii = 0; ii < length; ++ii) - { - PyObject * vo = PySequence_GetItem(value, ii); + for (int ii = 0; ii < length; ++ii) { + PyObject *vo = PySequence_GetItem(value, ii); float v = PyFloat_AsDouble(vo); Py_XDECREF(vo); _value.push_back(v); } - ret = Field< vector < float > >::set(self->oid_, string(field), _value); + ret = Field>::set(self->oid_, string(field), _value); } break; } - case 'S': - { - if (!PySequence_Check(value)) - { - PyErr_SetString(PyExc_TypeError, "For setting vector field, specified value must be a sequence." ); - } - else - { + case 'S': { + if (!PySequence_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "For setting vector field, specified " + "value must be a sequence."); + } else { Py_ssize_t length = PySequence_Length(value); vector _value; - for ( int ii = 0; ii < length; ++ii) - { - PyObject * vo = PySequence_GetItem(value, ii); - char * v = PyString_AsString(vo); + for (int ii = 0; ii < length; ++ii) { + PyObject *vo = PySequence_GetItem(value, ii); + char *v = PyString_AsString(vo); Py_XDECREF(vo); _value.push_back(string(v)); } - ret = Field< vector < string > >::set(self->oid_, string(field), _value); + ret = Field>::set(self->oid_, string(field), _value); } break; } - case 'T': // vector< vector > + case 'T': // vector< vector > { - vector < vector > * _value = (vector < vector > *)to_cpp(value, ftype); - if (!PyErr_Occurred()) - { - ret = Field < vector < vector > >::set(self->oid_, string(field), *_value); + vector> *_value = + (vector> *)to_cpp(value, ftype); + if (!PyErr_Occurred()) { + ret = Field>>::set(self->oid_, string(field), *_value); } delete _value; break; } - case 'Q': // vector< vector > + case 'Q': // vector< vector > { - vector < vector > * _value = (vector < vector > *)to_cpp(value, ftype); - if (!PyErr_Occurred()) - { - ret = Field < vector < vector > >::set(self->oid_, string(field), *_value); + vector> *_value = (vector> *)to_cpp(value, ftype); + if (!PyErr_Occurred()) { + ret = Field>>::set(self->oid_, string(field), *_value); } delete _value; break; } - case 'R': // vector< vector > + case 'R': // vector< vector > { - vector < vector > * _value = (vector < vector > *)to_cpp(value, ftype); - if (!PyErr_Occurred()) - { - ret = Field < vector < vector > >::set(self->oid_, string(field), *_value); + vector> *_value = (vector> *)to_cpp(value, ftype); + if (!PyErr_Occurred()) { + ret = Field>>::set(self->oid_, string(field), *_value); } delete _value; break; } - case 'X': //SET_VECFIELD(Id, f) + case 'X': // SET_VECFIELD(Id, f) { - if (!PySequence_Check(value)) - { - PyErr_SetString(PyExc_TypeError, "For setting vector field, specified value must be a sequence." ); - } - else - { + if (!PySequence_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "For setting vector field, specified value " + "must be a sequence."); + } else { Py_ssize_t length = PySequence_Length(value); vector _value; - for ( int ii = 0; ii < length; ++ii) - { - PyObject * vo = PySequence_GetItem(value, ii); - Id v = ((_Id*)vo)->id_; + for (int ii = 0; ii < length; ++ii) { + PyObject *vo = PySequence_GetItem(value, ii); + Id v = ((_Id *)vo)->id_; Py_XDECREF(vo); _value.push_back(v); } - ret = Field< vector < Id > >::set(self->oid_, string(field), _value); + ret = Field>::set(self->oid_, string(field), _value); } break; } - case 'Y': //SET_VECFIELD(ObjId, f) + case 'Y': // SET_VECFIELD(ObjId, f) { - if (!PySequence_Check(value)) - { - PyErr_SetString(PyExc_TypeError, "For setting vector field, specified value must be a sequence." ); - } - else - { + if (!PySequence_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "For setting vector field, specified " + "value must be a sequence."); + } else { Py_ssize_t length = PySequence_Length(value); vector _value; - for ( int ii = 0; ii < length; ++ii) - { - PyObject * vo = PySequence_GetItem(value, ii); - ObjId v = ((_ObjId*)vo)->oid_; + for (int ii = 0; ii < length; ++ii) { + PyObject *vo = PySequence_GetItem(value, ii); + ObjId v = ((_ObjId *)vo)->oid_; Py_XDECREF(vo); _value.push_back(v); } - ret = Field< vector < ObjId > >::set(self->oid_, string(field), _value); + ret = Field>::set(self->oid_, string(field), _value); } break; } @@ -1148,34 +994,31 @@ int moose_ObjId_setattro(_ObjId * self, PyObject * attr, PyObject * value) // MOOSE Field::set returns 1 for success 0 for // failure. Python treats return value 0 from stters as // success, anything else failure. - if (ret) - { + if (ret) { return 0; - } - else - { + } else { ostringstream msg; - msg << "Failed to set field '" << field << "'"; - PyErr_SetString(PyExc_AttributeError,msg.str().c_str()); + msg << "Failed to set field '" << field << "'"; + PyErr_SetString(PyExc_AttributeError, msg.str().c_str()); return -1; } } // moose_ObjId_setattro -PyObject * moose_ObjId_getItem(_ObjId * self, Py_ssize_t index) +PyObject *moose_ObjId_getItem(_ObjId *self, Py_ssize_t index) { - if (index < 0) - { + if (index < 0) { index += moose_ObjId_getLength(self); } - if ((index < 0) || (index >= moose_ObjId_getLength(self))) - { + if ((index < 0) || (index >= moose_ObjId_getLength(self))) { PyErr_SetString(PyExc_IndexError, "Index out of bounds."); return NULL; } // Here I am assuming the user can start with any ObjId and // ask for an index - which will be field index. - // Thus if syn[0...9] correspond to chan[0...9], then syn[0] is still a valid ObjId. - // For example, syn has Id X, dataIndex 0...9, and under dataIndex=0, we have 5 field elements f[0...5] + // Thus if syn[0...9] correspond to chan[0...9], then syn[0] is still a + // valid ObjId. + // For example, syn has Id X, dataIndex 0...9, and under dataIndex=0, we + // have 5 field elements f[0...5] // Then syn = Id(X) // syn[0] = ObjId(X, 0, 0) = syn[0][0] // assign s0 <- syn[0] @@ -1186,57 +1029,52 @@ PyObject * moose_ObjId_getItem(_ObjId * self, Py_ssize_t index) // In PyMOOSE, user is allowed to directly put in the numbers // for Id, dataIndex and fieldIndex directly and construct an // ObjId. - _ObjId * ret = PyObject_New(_ObjId, &ObjIdType); + _ObjId *ret = PyObject_New(_ObjId, &ObjIdType); ret->oid_ = ObjId(self->oid_.id, self->oid_.dataIndex, index); - return (PyObject*)ret; + return (PyObject *)ret; } -PyObject * moose_ObjId_getSlice(_ObjId * self, Py_ssize_t start, Py_ssize_t end) +PyObject *moose_ObjId_getSlice(_ObjId *self, Py_ssize_t start, Py_ssize_t end) { Py_ssize_t len = moose_ObjId_getLength(self); - while (start < 0) - { + while (start < 0) { start += len; } - while (end < 0) - { + while (end < 0) { end += len; } - if (start > end) - { - // PyErr_SetString(PyExc_IndexError, "Start index must be less than end."); + if (start > end) { + // PyErr_SetString(PyExc_IndexError, "Start index must be less than + // end."); // python itself returns empty tuple - follow that return PyTuple_New(0); } - PyObject * ret = PyTuple_New((Py_ssize_t)(end - start)); + PyObject *ret = PyTuple_New((Py_ssize_t)(end - start)); // Py_XINCREF(ret); - for ( int ii = start; ii < end; ++ii) - { - _ObjId * value = PyObject_New(_ObjId, &ObjIdType); + for (int ii = start; ii < end; ++ii) { + _ObjId *value = PyObject_New(_ObjId, &ObjIdType); value->oid_ = ObjId(self->oid_.id, self->oid_.dataIndex, ii); - if (PyTuple_SetItem(ret, (Py_ssize_t)(ii-start), (PyObject*)value)) // danger - must we DECREF all prior values? + if (PyTuple_SetItem(ret, (Py_ssize_t)(ii - start), (PyObject *)value)) // danger - must we DECREF all prior values? { Py_XDECREF(ret); // Py_XDECREF(value); - PyErr_SetString(PyExc_RuntimeError, "Failed to assign tuple entry."); + PyErr_SetString(PyExc_RuntimeError, + "Failed to assign tuple entry."); return NULL; } } return ret; } - -Py_ssize_t moose_ObjId_getLength(_ObjId * self) +Py_ssize_t moose_ObjId_getLength(_ObjId *self) { - Element * el = self->oid_.element(); - if (!el->hasFields()) - { + Element *el = self->oid_.element(); + if (!el->hasFields()) { return 0; } - FieldElement * fe = reinterpret_cast< FieldElement* >(el); - if (fe == NULL) - { + FieldElement *fe = reinterpret_cast(el); + if (fe == NULL) { return 0; } return (Py_ssize_t)(fe->numData()); @@ -1246,287 +1084,291 @@ Py_ssize_t moose_ObjId_getLength(_ObjId * self) /// with ObjId target. /// /// args should be a tuple (lookupFieldName, key) -PyObject * getLookupField(ObjId target, char * fieldName, PyObject * key) +PyObject *getLookupField(ObjId target, char *fieldName, PyObject *key) { vector type_vec; - if (parseFinfoType(Field::get(target, "className"), "lookupFinfo", string(fieldName), type_vec) < 0) - { + if (parseFinfoType(Field::get(target, "className"), + "lookupFinfo", + string(fieldName), + type_vec) < 0) { ostringstream error; - error << "Cannot handle key type for LookupField `" << Field::get(target, "className") << "." << fieldName << "`."; + error << "Cannot handle key type for LookupField `" + << Field::get(target, "className") << "." << fieldName << "`."; PyErr_SetString(PyExc_TypeError, error.str().c_str()); return NULL; } - if (type_vec.size() != 2) - { + if (type_vec.size() != 2) { ostringstream error; - error << "LookupField type signature should be , . But for `" - << Field::get(target, "className") << "." << fieldName << "` got " << type_vec.size() << " components." ; + error << "LookupField type signature should be , . " + "But for `" << Field::get(target, "className") << "." + << fieldName << "` got " << type_vec.size() << " components."; PyErr_SetString(PyExc_AssertionError, error.str().c_str()); return NULL; } - PyObject * ret = NULL; + PyObject *ret = NULL; char key_type_code = shortType(type_vec[0]); char value_type_code = shortType(type_vec[1]); - switch(key_type_code) - { - case 'b': - { - ret = lookup_value (target, string(fieldName), value_type_code, key_type_code, key); + switch (key_type_code) { + case 'b': { + ret = lookup_value( + target, string(fieldName), value_type_code, key_type_code, key); break; } - case 'c': - { - ret = lookup_value (target, string(fieldName), value_type_code, key_type_code, key); + case 'c': { + ret = lookup_value( + target, string(fieldName), value_type_code, key_type_code, key); break; } - case 'h': - { - ret = lookup_value (target, string(fieldName), value_type_code, key_type_code, key); + case 'h': { + ret = lookup_value( + target, string(fieldName), value_type_code, key_type_code, key); break; } - case 'H': - { - ret = lookup_value (target, string(fieldName), value_type_code, key_type_code, key); + case 'H': { + ret = lookup_value( + target, string(fieldName), value_type_code, key_type_code, key); break; } - case 'i': - { - ret = lookup_value (target, string(fieldName), value_type_code, key_type_code, key); + case 'i': { + ret = lookup_value( + target, string(fieldName), value_type_code, key_type_code, key); break; } - case 'I': - { - ret = lookup_value (target, string(fieldName), value_type_code, key_type_code, key); + case 'I': { + ret = lookup_value( + target, string(fieldName), value_type_code, key_type_code, key); break; } - case 'l': - { - ret = lookup_value (target, string(fieldName), value_type_code, key_type_code, key); + case 'l': { + ret = lookup_value( + target, string(fieldName), value_type_code, key_type_code, key); break; } - case 'k': - { - ret = lookup_value (target, string(fieldName), value_type_code, key_type_code, key); + case 'k': { + ret = lookup_value( + target, string(fieldName), value_type_code, key_type_code, key); break; } - case 'L': - { - ret = lookup_value (target, string(fieldName), value_type_code, key_type_code, key); + case 'L': { + ret = lookup_value( + target, string(fieldName), value_type_code, key_type_code, key); break; } - case 'K': - { - ret = lookup_value (target, string(fieldName), value_type_code, key_type_code, key); + case 'K': { + ret = lookup_value( + target, string(fieldName), value_type_code, key_type_code, key); break; } - case 'd': - { - ret = lookup_value (target, string(fieldName), value_type_code, key_type_code, key); + case 'd': { + ret = lookup_value( + target, string(fieldName), value_type_code, key_type_code, key); break; } - case 'f': - { - ret = lookup_value (target, string(fieldName), value_type_code, key_type_code, key); + case 'f': { + ret = lookup_value( + target, string(fieldName), value_type_code, key_type_code, key); break; } - case 's': - { - ret = lookup_value (target, string(fieldName), value_type_code, key_type_code, key); + case 's': { + ret = lookup_value( + target, string(fieldName), value_type_code, key_type_code, key); break; } - case 'x': - { - ret = lookup_value (target, string(fieldName), value_type_code, key_type_code, key); + case 'x': { + ret = lookup_value( + target, string(fieldName), value_type_code, key_type_code, key); break; } - case 'y': - { - ret = lookup_value (target, string(fieldName), value_type_code, key_type_code, key); + case 'y': { + ret = lookup_value( + target, string(fieldName), value_type_code, key_type_code, key); break; } - case 'D': - { - ret = lookup_value < vector >(target, string(fieldName), value_type_code, key_type_code, key); + case 'D': { + ret = lookup_value>( + target, string(fieldName), value_type_code, key_type_code, key); break; } - case 'S': - { - ret = lookup_value < vector >(target, string(fieldName), value_type_code, key_type_code, key); + case 'S': { + ret = lookup_value>( + target, string(fieldName), value_type_code, key_type_code, key); break; } - case 'X': - { - ret = lookup_value < vector >(target, string(fieldName), value_type_code, key_type_code, key); + case 'X': { + ret = lookup_value>( + target, string(fieldName), value_type_code, key_type_code, key); break; } - case 'Y': - { - ret = lookup_value < vector >(target, string(fieldName), value_type_code, key_type_code, key); + case 'Y': { + ret = lookup_value>( + target, string(fieldName), value_type_code, key_type_code, key); break; } - case 'v': - { - ret = lookup_value < vector >(target, string(fieldName), value_type_code, key_type_code, key); + case 'v': { + ret = lookup_value>( + target, string(fieldName), value_type_code, key_type_code, key); break; } - case 'N': - { - ret = lookup_value < vector >(target, string(fieldName), value_type_code, key_type_code, key); + case 'N': { + ret = lookup_value>( + target, string(fieldName), value_type_code, key_type_code, key); break; } - case 'P': - { - ret = lookup_value < vector >(target, string(fieldName), value_type_code, key_type_code, key); + case 'P': { + ret = lookup_value>( + target, string(fieldName), value_type_code, key_type_code, key); break; } - case 'F': - { - ret = lookup_value < vector >(target, string(fieldName), value_type_code, key_type_code, key); + case 'F': { + ret = lookup_value>( + target, string(fieldName), value_type_code, key_type_code, key); break; } - case 'w': - { - ret = lookup_value < vector >(target, string(fieldName), value_type_code, key_type_code, key); + case 'w': { + ret = lookup_value>( + target, string(fieldName), value_type_code, key_type_code, key); break; } - case 'C': - { - ret = lookup_value < vector >(target, string(fieldName), value_type_code, key_type_code, key); + case 'C': { + ret = lookup_value>( + target, string(fieldName), value_type_code, key_type_code, key); break; } default: ostringstream error; - error << "Unhandled key type `" << type_vec[0] << "` for " << Field::get(target, "className") << "." << fieldName; + error << "Unhandled key type `" << type_vec[0] << "` for " + << Field::get(target, "className") << "." << fieldName; PyErr_SetString(PyExc_TypeError, error.str().c_str()); } return ret; } -PyDoc_STRVAR(moose_ObjId_getLookupField_documentation, - "getLookupField(fieldname, key) -> value type\n" - "\n" - "Lookup entry for `key` in `fieldName`\n" - "\n" - "Parameters\n" - "----------\n" - "fieldname : string\n" - " Name of the lookupfield.\n" - "\n" - "key : appropriate type for key of the lookupfield (as in the dict " - " getFieldDict).\n" - " Key for the look-up."); - -PyObject * moose_ObjId_getLookupField(_ObjId * self, PyObject * args) +PyDoc_STRVAR( + moose_ObjId_getLookupField_documentation, + "getLookupField(fieldname, key) -> value type\n" + "\n" + "Lookup entry for `key` in `fieldName`\n" + "\n" + "Parameters\n" + "----------\n" + "fieldname : string\n" + " Name of the lookupfield.\n" + "\n" + "key : appropriate type for key of the lookupfield (as in the dict " + " getFieldDict).\n" + " Key for the look-up."); + +PyObject *moose_ObjId_getLookupField(_ObjId *self, PyObject *args) { - if (!Id::isValid(self->oid_.id)) - { + if (!Id::isValid(self->oid_.id)) { RAISE_INVALID_ID(NULL, "moose_ObjId_getLookupField"); } - char * fieldName = NULL; - PyObject * key = NULL; - if (!PyArg_ParseTuple(args, "sO:moose_ObjId_getLookupField", &fieldName, &key)) - { + char *fieldName = NULL; + PyObject *key = NULL; + if (!PyArg_ParseTuple(args, "sO:moose_ObjId_getLookupField", &fieldName, &key)) { return NULL; } return getLookupField(self->oid_, fieldName, key); } // moose_ObjId_getLookupField -int setLookupField(ObjId target, char * fieldName, PyObject * key, PyObject * value) +int setLookupField(ObjId target, char *fieldName, PyObject *key, PyObject *value) { vector type_vec; - if (parseFinfoType(Field::get(target, "className"), "lookupFinfo", string(fieldName), type_vec) < 0) - { + if (parseFinfoType(Field::get(target, "className"), + "lookupFinfo", + string(fieldName), + type_vec) < 0) { ostringstream error; - error << "Cannot handle key type for LookupField `" << Field::get(target, "className") << "." << fieldName << "`."; + error << "Cannot handle key type for LookupField `" + << Field::get(target, "className") << "." << fieldName << "`."; PyErr_SetString(PyExc_TypeError, error.str().c_str()); return -1; } - if (type_vec.size() != 2) - { + if (type_vec.size() != 2) { ostringstream error; - error << "LookupField type signature should be , . But for `" - << Field::get(target, "className") << "." << fieldName << "` got " << type_vec.size() << " components." ; + error << "LookupField type signature should be , . " + "But for `" << Field::get(target, "className") << "." + << fieldName << "` got " << type_vec.size() << " components."; PyErr_SetString(PyExc_AssertionError, error.str().c_str()); return -1; } char key_type_code = shortType(type_vec[0]); char value_type_code = shortType(type_vec[1]); int ret = -1; - switch(key_type_code) - { - case 'I': - { - ret = set_lookup_value (target, string(fieldName), value_type_code, key_type_code, key, value); + switch (key_type_code) { + case 'I': { + ret = set_lookup_value( + target, string(fieldName), value_type_code, key_type_code, key, value); break; } - case 'k': - { - ret = set_lookup_value (target, string(fieldName), value_type_code, key_type_code, key, value); + case 'k': { + ret = set_lookup_value( + target, string(fieldName), value_type_code, key_type_code, key, value); break; } - case 's': - { - ret = set_lookup_value (target, string(fieldName), value_type_code, key_type_code, key, value); + case 's': { + ret = set_lookup_value( + target, string(fieldName), value_type_code, key_type_code, key, value); break; } - case 'i': - { - ret = set_lookup_value (target, string(fieldName), value_type_code, key_type_code, key, value); + case 'i': { + ret = set_lookup_value( + target, string(fieldName), value_type_code, key_type_code, key, value); break; } - case 'l': - { - ret = set_lookup_value (target, string(fieldName), value_type_code, key_type_code, key, value); + case 'l': { + ret = set_lookup_value( + target, string(fieldName), value_type_code, key_type_code, key, value); break; } - case 'L': - { - ret = set_lookup_value (target, string(fieldName), value_type_code, key_type_code, key, value); + case 'L': { + ret = set_lookup_value( + target, string(fieldName), value_type_code, key_type_code, key, value); break; } - case 'K': - { - ret = set_lookup_value (target, string(fieldName), value_type_code, key_type_code, key, value); + case 'K': { + ret = set_lookup_value( + target, string(fieldName), value_type_code, key_type_code, key, value); break; } - case 'b': - { - ret = set_lookup_value (target, string(fieldName), value_type_code, key_type_code, key, value); + case 'b': { + ret = set_lookup_value( + target, string(fieldName), value_type_code, key_type_code, key, value); break; } - case 'c': - { - ret = set_lookup_value (target, string(fieldName), value_type_code, key_type_code, key, value); + case 'c': { + ret = set_lookup_value( + target, string(fieldName), value_type_code, key_type_code, key, value); break; } - case 'h': - { - ret = set_lookup_value (target, string(fieldName), value_type_code, key_type_code, key, value); + case 'h': { + ret = set_lookup_value( + target, string(fieldName), value_type_code, key_type_code, key, value); break; } - case 'H': - { - ret = set_lookup_value (target, string(fieldName), value_type_code, key_type_code, key, value); + case 'H': { + ret = set_lookup_value( + target, string(fieldName), value_type_code, key_type_code, key, value); break; } - case 'd': - { - ret = set_lookup_value (target, string(fieldName), value_type_code, key_type_code, key, value); + case 'd': { + ret = set_lookup_value( + target, string(fieldName), value_type_code, key_type_code, key, value); break; } - case 'f': - { - ret = set_lookup_value (target, string(fieldName), value_type_code, key_type_code, key, value); + case 'f': { + ret = set_lookup_value( + target, string(fieldName), value_type_code, key_type_code, key, value); break; } - case 'x': - { - ret = set_lookup_value (target, string(fieldName), value_type_code, key_type_code, key, value); + case 'x': { + ret = set_lookup_value( + target, string(fieldName), value_type_code, key_type_code, key, value); break; } - case 'y': - { - ret = set_lookup_value (target, string(fieldName), value_type_code, key_type_code, key, value); + case 'y': { + ret = set_lookup_value( + target, string(fieldName), value_type_code, key_type_code, key, value); break; } default: @@ -1535,7 +1377,7 @@ int setLookupField(ObjId target, char * fieldName, PyObject * key, PyObject * va PyErr_SetString(PyExc_TypeError, error.str().c_str()); } return ret; -}// setLookupField +} // setLookupField PyDoc_STRVAR(moose_ObjId_setLookupField_documentation, "setLookupField(fieldname, key, value)\n" @@ -1551,68 +1393,71 @@ PyDoc_STRVAR(moose_ObjId_setLookupField_documentation, "value : value type\n" " value to be set for `key` in the lookup field.\n"); -PyObject * moose_ObjId_setLookupField(_ObjId * self, PyObject * args) +PyObject *moose_ObjId_setLookupField(_ObjId *self, PyObject *args) { - if (!Id::isValid(self->oid_.id)) - { + if (!Id::isValid(self->oid_.id)) { return NULL; } - PyObject * key; - PyObject * value; - char * field; - if (!PyArg_ParseTuple(args, "sOO:moose_ObjId_setLookupField", &field, &key, &value)) - { + PyObject *key; + PyObject *value; + char *field; + if (!PyArg_ParseTuple(args, "sOO:moose_ObjId_setLookupField", &field, &key, &value)) { return NULL; } - if ( setLookupField(self->oid_, field, key, value) == 0) - { + if (setLookupField(self->oid_, field, key, value) == 0) { Py_RETURN_NONE; } return NULL; -}// moose_ObjId_setLookupField - -PyDoc_STRVAR(moose_ObjId_setDestField_documentation, - "setDestField(arg0, arg1, ...)\n" - "\n" - "Set a destination field. This is for advanced uses. destFields can\n" - "(and should) be directly called like functions as\n" - "`element.fieldname(arg0, ...)`\n" - "\n" - "Parameters\n" - "----------\n" - "The number and type of paramateres depend on the destFinfo to be\n" - "set. Use moose.doc('{classname}.{fieldname}') to get builtin\n" - "documentation on the destFinfo `fieldname`\n" - ); - -PyObject * moose_ObjId_setDestField(_ObjId * self, PyObject * args) +} // moose_ObjId_setLookupField + +PyDoc_STRVAR( + moose_ObjId_setDestField_documentation, + "setDestField(arg0, arg1, ...)\n" + "\n" + "Set a destination field. This is for advanced uses. destFields can\n" + "(and should) be directly called like functions as\n" + "`element.fieldname(arg0, ...)`\n" + "\n" + "Parameters\n" + "----------\n" + "The number and type of paramateres depend on the destFinfo to be\n" + "set. Use moose.doc('{classname}.{fieldname}') to get builtin\n" + "documentation on the destFinfo `fieldname`\n"); + +PyObject *moose_ObjId_setDestField(_ObjId *self, PyObject *args) { - if (!Id::isValid(self->oid_.id)) - { + if (!Id::isValid(self->oid_.id)) { RAISE_INVALID_ID(NULL, "moose_ObjId_setDestField"); } - PyObject * arglist[10] = {NULL, NULL, NULL, NULL, NULL, - NULL, NULL, NULL, NULL, NULL - }; + PyObject *arglist[10] = {NULL, NULL, NULL, NULL, NULL, + NULL, NULL, NULL, NULL, NULL}; ostringstream error; - ObjId oid = ((_ObjId*)self)->oid_; + ObjId oid = ((_ObjId *)self)->oid_; error << "moose.setDestField: "; // Unpack the arguments - if (!PyArg_UnpackTuple(args, "setDestField", minArgs, maxArgs, - &arglist[0], &arglist[1], &arglist[2], - &arglist[3], &arglist[4], &arglist[5], - &arglist[6], &arglist[7], &arglist[8], - &arglist[9])) - { - error << "At most " << maxArgs - 1 << " arguments can be handled."; + if (!PyArg_UnpackTuple(args, + "setDestField", + MIN_ARGS, + MAX_ARGS, + &arglist[0], + &arglist[1], + &arglist[2], + &arglist[3], + &arglist[4], + &arglist[5], + &arglist[6], + &arglist[7], + &arglist[8], + &arglist[9])) { + error << "At most " << MAX_ARGS - 1 << " arguments can be handled."; PyErr_SetString(PyExc_ValueError, error.str().c_str()); return NULL; } // Get the destFinfo name - char * fieldName = PyString_AsString(arglist[0]); - if (!fieldName) // not a string, raises TypeError + char *fieldName = PyString_AsString(arglist[0]); + if (!fieldName) // not a string, raises TypeError { error << "first argument must be a string specifying field name."; PyErr_SetString(PyExc_TypeError, error.str().c_str()); @@ -1620,288 +1465,224 @@ PyObject * moose_ObjId_setDestField(_ObjId * self, PyObject * args) } // Try to parse the arguments. - vector< string > argType; - if (parseFinfoType(Field::get(oid, "className"), - "destFinfo", string(fieldName), argType) < 0) - { + vector argType; + if (parseFinfoType( + Field::get(oid, "className"), "destFinfo", string(fieldName), argType) < 0) { error << "Arguments not handled: " << fieldName << "("; - for (unsigned int ii = 0; ii < argType.size(); ++ii) - { + for (unsigned int ii = 0; ii < argType.size(); ++ii) { error << argType[ii] << ","; } error << ")"; PyErr_SetString(PyExc_TypeError, error.str().c_str()); return NULL; } - if (argType.size() == 1) - { - if ( arglist[1] == NULL && argType[0] == "void") - { + if (argType.size() == 1) { + if (arglist[1] == NULL && argType[0] == "void") { bool ret = SetGet0::set(oid, string(fieldName)); - if (ret) - { + if (ret) { Py_RETURN_TRUE; - } - else - { + } else { Py_RETURN_FALSE; } } return setDestFinfo(oid, string(fieldName), arglist[1], argType[0]); - } - else if (argType.size() == 2) - { - return setDestFinfo2(oid, string(fieldName), arglist[1], shortType(argType[0]), arglist[2], shortType(argType[1])); - } - else - { + } else if (argType.size() == 2) { + return setDestFinfo2(oid, + string(fieldName), + arglist[1], + shortType(argType[0]), + arglist[2], + shortType(argType[1])); + } else { error << "Can handle only up to 2 arguments" << endl; return NULL; } } // moose_ObjId_setDestField -PyObject * setDestFinfo(ObjId obj, string fieldName, PyObject *arg, string argType) +PyObject *setDestFinfo(ObjId obj, string fieldName, PyObject *arg, string argType) { char typecode = shortType(argType); bool ret; ostringstream error; error << "moose.setDestFinfo: "; - switch (typecode) - { + switch (typecode) { case 'f': - case 'd': - { + case 'd': { double param = PyFloat_AsDouble(arg); - if (typecode == 'f') - { + if (typecode == 'f') { ret = SetGet1::set(obj, fieldName, (float)param); - } - else - { + } else { ret = SetGet1::set(obj, fieldName, param); } - } - break; - case 's': - { - char * param = PyString_AsString(arg); + } break; + case 's': { + char *param = PyString_AsString(arg); ret = SetGet1::set(obj, fieldName, string(param)); - } - break; + } break; case 'i': - case 'l': - { + case 'l': { long param = PyInt_AsLong(arg); - if (param == -1 && PyErr_Occurred()) - { + if (param == -1 && PyErr_Occurred()) { return NULL; } - if (typecode == 'i') - { + if (typecode == 'i') { ret = SetGet1::set(obj, fieldName, (int)param); - } - else - { + } else { ret = SetGet1::set(obj, fieldName, param); } - } - break; + } break; case 'I': - case 'k': - { - unsigned long param =PyLong_AsUnsignedLong(arg); - if (PyErr_Occurred()) - { + case 'k': { + unsigned long param = PyLong_AsUnsignedLong(arg); + if (PyErr_Occurred()) { return NULL; } - if (typecode == 'I') - { - ret = SetGet1< unsigned int>::set(obj, fieldName, (unsigned int)param); - } - else - { + if (typecode == 'I') { + ret = SetGet1::set(obj, fieldName, (unsigned int)param); + } else { ret = SetGet1::set(obj, fieldName, param); } - } - break; - case 'x': - { + } break; + case 'x': { Id param; - _Id * id = (_Id*)(arg); - if (id == NULL) - { + _Id *id = (_Id *)(arg); + if (id == NULL) { error << "argument should be an vec or an melement"; PyErr_SetString(PyExc_TypeError, error.str().c_str()); return NULL; } param = id->id_; ret = SetGet1::set(obj, fieldName, param); - } - break; - case 'y': - { + } break; + case 'y': { ObjId param; - _ObjId * oid = (_ObjId*)(arg); - if (oid == NULL) - { + _ObjId *oid = (_ObjId *)(arg); + if (oid == NULL) { error << "argument should be vec or an melement"; PyErr_SetString(PyExc_TypeError, error.str().c_str()); return NULL; } param = oid->oid_; ret = SetGet1::set(obj, fieldName, param); - } - break; - case 'c': - { - char * param = PyString_AsString(arg); - if (!param) - { + } break; + case 'c': { + char *param = PyString_AsString(arg); + if (!param) { error << "expected argument of type char/string"; PyErr_SetString(PyExc_TypeError, error.str().c_str()); return NULL; - } - else if (strlen(param) == 0) - { + } else if (strlen(param) == 0) { error << "Empty string not allowed."; PyErr_SetString(PyExc_ValueError, error.str().c_str()); return NULL; } ret = SetGet1::set(obj, fieldName, param[0]); - } - break; + } break; //////////////////////////////////////////////////// // We do NOT handle multiple vectors. Use the argument // list as a single vector argument. //////////////////////////////////////////////////// - case 'v': - { + case 'v': { return _set_vector_destFinfo(obj, string(fieldName), arg, typecode); } - case 'w': - { + case 'w': { return _set_vector_destFinfo(obj, string(fieldName), arg, typecode); } - case 'L': //SET_VECFIELD(long, l) { + case 'L': // SET_VECFIELD(long, l) { { return _set_vector_destFinfo(obj, string(fieldName), arg, typecode); } - case 'N': //SET_VECFIELD(unsigned int, I) + case 'N': // SET_VECFIELD(unsigned int, I) { return _set_vector_destFinfo(obj, string(fieldName), arg, typecode); } - case 'K': //SET_VECFIELD(unsigned long, k) + case 'K': // SET_VECFIELD(unsigned long, k) { return _set_vector_destFinfo(obj, string(fieldName), arg, typecode); } - case 'F': //SET_VECFIELD(float, f) + case 'F': // SET_VECFIELD(float, f) { return _set_vector_destFinfo(obj, string(fieldName), arg, typecode); } - case 'D': //SET_VECFIELD(double, d) + case 'D': // SET_VECFIELD(double, d) { return _set_vector_destFinfo(obj, string(fieldName), arg, typecode); } - case 'S': - { + case 'S': { return _set_vector_destFinfo(obj, string(fieldName), arg, typecode); } - case 'X': - { + case 'X': { return _set_vector_destFinfo(obj, string(fieldName), arg, typecode); } - case 'Y': - { + case 'Y': { return _set_vector_destFinfo(obj, string(fieldName), arg, typecode); } - default: - { + default: { error << "Cannot handle argument type: " << argType; PyErr_SetString(PyExc_TypeError, error.str().c_str()); return NULL; } } // switch (shortType(argType[ii]) - if (ret) - { + if (ret) { Py_RETURN_TRUE; - } - else - { + } else { Py_RETURN_FALSE; } - } /** Set destFinfo for 2 argument destination field functions. */ // template -PyObject* setDestFinfo2(ObjId obj, string fieldName, PyObject * arg1, char type1, PyObject * arg2, char type2) +PyObject *setDestFinfo2(ObjId obj, string fieldName, PyObject *arg1, char type1, PyObject *arg2, char type2) { ostringstream error; error << "moose.setDestFinfo2: "; - switch (type2) - { + switch (type2) { case 'f': - case 'd': - { + case 'd': { double param = PyFloat_AsDouble(arg2); - if (type2 == 'f') - { + if (type2 == 'f') { return setDestFinfo1(obj, fieldName, arg1, type1, (float)param); - } - else - { + } else { return setDestFinfo1(obj, fieldName, arg1, type1, param); } } - case 's': - { - char * param = PyString_AsString(arg2); + case 's': { + char *param = PyString_AsString(arg2); return setDestFinfo1(obj, fieldName, arg1, type1, string(param)); } case 'i': - case 'l': - { + case 'l': { long param = PyInt_AsLong(arg2); - if (param == -1 && PyErr_Occurred()) - { + if (param == -1 && PyErr_Occurred()) { return NULL; } - if (type2 == 'i') - { - return setDestFinfo1< int>(obj, fieldName, arg1, type1, (int)param); - } - else - { - return setDestFinfo1< long>(obj, fieldName, arg1, type1, param); + if (type2 == 'i') { + return setDestFinfo1(obj, fieldName, arg1, type1, (int)param); + } else { + return setDestFinfo1(obj, fieldName, arg1, type1, param); } } case 'I': - case 'k': - { - unsigned long param =PyLong_AsUnsignedLong(arg2); - if (PyErr_Occurred()) - { + case 'k': { + unsigned long param = PyLong_AsUnsignedLong(arg2); + if (PyErr_Occurred()) { return NULL; } - if (type2 == 'I') - { - return setDestFinfo1< unsigned int>(obj, fieldName, arg1, type1, (unsigned int)param); - } - else - { - return setDestFinfo1< unsigned long>(obj, fieldName, arg1, type1, param); + if (type2 == 'I') { + return setDestFinfo1( + obj, fieldName, arg1, type1, (unsigned int)param); + } else { + return setDestFinfo1(obj, fieldName, arg1, type1, param); } } - case 'x': - { + case 'x': { Id param; // if (Id_SubtypeCheck(arg)){ - _Id * id = (_Id*)(arg2); - if (id == NULL) - { + _Id *id = (_Id *)(arg2); + if (id == NULL) { error << "argument should be an vec or an melement"; PyErr_SetString(PyExc_TypeError, error.str().c_str()); return NULL; @@ -1916,10 +1697,9 @@ PyObject* setDestFinfo2(ObjId obj, string fieldName, PyObject * arg1, char type1 // } // param = oid->oid_.id; // } - return setDestFinfo1< Id>(obj, fieldName, arg1, type1, param); + return setDestFinfo1(obj, fieldName, arg1, type1, param); } - case 'y': - { + case 'y': { ObjId param; // if (Id_SubtypeCheck(arg)){ // _Id * id = (_Id*)(arg); @@ -1930,36 +1710,30 @@ PyObject* setDestFinfo2(ObjId obj, string fieldName, PyObject * arg1, char type1 // } // param = ObjId(id->id_); // } else if (ObjId_SubtypeCheck(arg)){ - _ObjId * oid = (_ObjId*)(arg2); - if (oid == NULL) - { + _ObjId *oid = (_ObjId *)(arg2); + if (oid == NULL) { error << "argument should be an vec or an melement"; PyErr_SetString(PyExc_TypeError, error.str().c_str()); return NULL; } param = oid->oid_; // } - return setDestFinfo1< ObjId>(obj, fieldName, arg1, type1, param); + return setDestFinfo1(obj, fieldName, arg1, type1, param); } - case 'c': - { - char * param = PyString_AsString(arg2); - if (!param) - { + case 'c': { + char *param = PyString_AsString(arg2); + if (!param) { error << "expected argument of type char/string"; PyErr_SetString(PyExc_TypeError, error.str().c_str()); return NULL; - } - else if (strlen(param) == 0) - { + } else if (strlen(param) == 0) { error << "Empty string not allowed."; PyErr_SetString(PyExc_ValueError, error.str().c_str()); return NULL; } - return setDestFinfo1< char>(obj, fieldName, arg1, type1, param[0]); + return setDestFinfo1(obj, fieldName, arg1, type1, param[0]); } - default: - { + default: { error << "Unhandled argument 2 type (shortType=" << type2 << ")"; PyErr_SetString(PyExc_TypeError, error.str().c_str()); return NULL; @@ -1967,77 +1741,71 @@ PyObject* setDestFinfo2(ObjId obj, string fieldName, PyObject * arg1, char type1 } } - -PyDoc_STRVAR(moose_ObjId_getFieldNames_documenation, - "getFieldNames(fieldType='') -> tuple of str\n" - "\n" - "Returns the names of fields of this element of fieldType kind.\n" - "\n" - "Parameters\n" - "----------\n" - "fieldType : str\n" - " Type of the fields you wish to retrieve. Can be\n" - " - `valueFinfo` - attributes of the object\n" - " - `srcFinfo` - fields of the object which can be used as source of information for connect\n" - " - `destFinfo` - fields of the object which can be used as destination of information for connect\n" - " - `lookupFinfo`- fields which can be looked at through this object" - ", etc. If an empty string is specified, names of all avaialable fields are returned.\n" - "\n" - "Returns\n" - "-------\n" - "names : tuple of strings.\n" - " names of the fields of the specified type.\n" - "\n" - "Examples\n" - "--------\n" - "List names of all the source fields in PulseGen class:\n" - "\n" - " >>> comp.getFieldNames('lookupFinfo') \n" - " ('neighbors', 'msgDests', 'msgDestFunctions', 'isA')\n" - " >>> moose.getFieldNames('PulseGen', 'srcFinfo')\n" - " ('childMsg', 'output')\n" - "\n"); +PyDoc_STRVAR( + moose_ObjId_getFieldNames_documenation, + "getFieldNames(fieldType='') -> tuple of str\n" + "\n" + "Returns the names of fields of this element of fieldType kind.\n" + "\n" + "Parameters\n" + "----------\n" + "fieldType : str\n" + " Type of the fields you wish to retrieve. Can be\n" + " - `valueFinfo` - attributes of the object\n" + " - `srcFinfo` - fields of the object which can be used as source of " + "information for connect\n" + " - `destFinfo` - fields of the object which can be used as " + "destination of information for connect\n" + " - `lookupFinfo`- fields which can be looked at through this object" + ", etc. If an empty string is specified, names of all avaialable fields " + "are returned.\n" + "\n" + "Returns\n" + "-------\n" + "names : tuple of strings.\n" + " names of the fields of the specified type.\n" + "\n" + "Examples\n" + "--------\n" + "List names of all the source fields in PulseGen class:\n" + "\n" + " >>> comp.getFieldNames('lookupFinfo') \n" + " ('neighbors', 'msgDests', 'msgDestFunctions', 'isA')\n" + " >>> moose.getFieldNames('PulseGen', 'srcFinfo')\n" + " ('childMsg', 'output')\n" + "\n"); // 2011-03-23 15:28:26 (+0530) -PyObject * moose_ObjId_getFieldNames(_ObjId * self, PyObject *args) +PyObject *moose_ObjId_getFieldNames(_ObjId *self, PyObject *args) { - if (!Id::isValid(self->oid_.id)) - { + if (!Id::isValid(self->oid_.id)) { RAISE_INVALID_ID(NULL, "moose_ObjId_getFieldNames"); } - char * ftype = NULL; - if (!PyArg_ParseTuple(args, "|s:moose_ObjId_getFieldNames", &ftype)) - { + char *ftype = NULL; + if (!PyArg_ParseTuple(args, "|s:moose_ObjId_getFieldNames", &ftype)) { return NULL; } - string ftype_str = (ftype != NULL)? string(ftype): ""; + string ftype_str = (ftype != NULL) ? string(ftype) : ""; vector ret; string className = Field::get(self->oid_, "className"); - if (ftype_str == "") - { - for (const char **a = getFinfoTypes(); *a; ++a) - { + if (ftype_str == "") { + for (const char **a = getFinfoTypes(); *a; ++a) { vector fields = getFieldNames(className, string(*a)); ret.insert(ret.end(), fields.begin(), fields.end()); } - } - else - { + } else { ret = getFieldNames(className, ftype_str); } - PyObject * pyret = PyTuple_New((Py_ssize_t)ret.size()); + PyObject *pyret = PyTuple_New((Py_ssize_t)ret.size()); - for (unsigned int ii = 0; ii < ret.size(); ++ ii ) - { - PyObject * fname = Py_BuildValue("s", ret[ii].c_str()); - if (!fname) - { + for (unsigned int ii = 0; ii < ret.size(); ++ii) { + PyObject *fname = Py_BuildValue("s", ret[ii].c_str()); + if (!fname) { Py_XDECREF(pyret); pyret = NULL; break; } - if (PyTuple_SetItem(pyret, (Py_ssize_t)ii, fname)) - { + if (PyTuple_SetItem(pyret, (Py_ssize_t)ii, fname)) { Py_XDECREF(pyret); // Py_DECREF(fname); pyret = NULL; @@ -2047,42 +1815,40 @@ PyObject * moose_ObjId_getFieldNames(_ObjId * self, PyObject *args) return pyret; } -PyDoc_STRVAR(moose_ObjId_getNeighbors_documentation, - "getNeighbors(fieldName) -> tuple of vecs\n" - "\n" - "Get the objects connected to this element on specified field.\n" - "\n" - "Parameters\n" - "----------\n" - "fieldName : str\n" - " name of the connection field (a destFinfo/srcFinfo/sharedFinfo)\n" - "\n" - "Returns\n" - "-------\n" - "neighbors: tuple of vecs.\n" - " tuple containing the ids of the neighbour vecs.\n" - "\n"); - -PyObject * moose_ObjId_getNeighbors(_ObjId * self, PyObject * args) +PyDoc_STRVAR( + moose_ObjId_getNeighbors_documentation, + "getNeighbors(fieldName) -> tuple of vecs\n" + "\n" + "Get the objects connected to this element on specified field.\n" + "\n" + "Parameters\n" + "----------\n" + "fieldName : str\n" + " name of the connection field (a destFinfo/srcFinfo/sharedFinfo)\n" + "\n" + "Returns\n" + "-------\n" + "neighbors: tuple of vecs.\n" + " tuple containing the ids of the neighbour vecs.\n" + "\n"); + +PyObject *moose_ObjId_getNeighbors(_ObjId *self, PyObject *args) { - if (!Id::isValid(self->oid_.id)) - { + if (!Id::isValid(self->oid_.id)) { RAISE_INVALID_ID(NULL, "moose_ObjId_getNeighbors"); } - char * field = NULL; - if (!PyArg_ParseTuple(args, "s:moose_ObjId_getNeighbors", &field)) - { + char *field = NULL; + if (!PyArg_ParseTuple(args, "s:moose_ObjId_getNeighbors", &field)) { return NULL; } - vector< Id > val = LookupField< string, vector< Id > >::get(self->oid_, "neighbors", string(field)); + vector val = + LookupField>::get(self->oid_, "neighbors", string(field)); - PyObject * ret = PyTuple_New((Py_ssize_t)val.size()); + PyObject *ret = PyTuple_New((Py_ssize_t)val.size()); - for (unsigned int ii = 0; ii < val.size(); ++ ii ) - { - _Id * entry = PyObject_New(_Id, &IdType); - if (!entry || PyTuple_SetItem(ret, (Py_ssize_t)ii, (PyObject*)entry)) - { + for (unsigned int ii = 0; ii < val.size(); ++ii) { + _Id *entry = PyObject_New(_Id, &IdType); + if (!entry || PyTuple_SetItem(ret, (Py_ssize_t)ii, (PyObject *)entry)) { Py_DECREF(ret); // Py_DECREF((PyObject*)entry); ret = NULL; @@ -2101,9 +1867,12 @@ PyObject * moose_ObjId_getNeighbors(_ObjId * self, PyObject * args) PyDoc_STRVAR(moose_ObjId_connect_documentation, "connect(src, srcfield, destobj, destfield[,msgtype]) -> bool\n" "\n" - "Create a message between `src_field` on `src` object to `dest_field` on `dest` object.\n" - "This function is used mainly, to say, connect two entities, and to denote what kind of give-and-take relationship they share." - "It enables the 'destfield' (of the 'destobj') to acquire the data, from 'srcfield'(of the 'src')." + "Create a message between `src_field` on `src` object to " + "`dest_field` on `dest` object.\n" + "This function is used mainly, to say, connect two entities, and " + "to denote what kind of give-and-take relationship they share." + "It enables the 'destfield' (of the 'destobj') to acquire the " + "data, from 'srcfield'(of the 'src')." "\n" "Parameters\n" "----------\n" @@ -2144,113 +1913,86 @@ PyDoc_STRVAR(moose_ObjId_connect_documentation, "See also\n" "--------\n" "moose.connect\n" - "\n" - ); -PyObject * moose_ObjId_connect(_ObjId * self, PyObject * args) + "\n"); +PyObject *moose_ObjId_connect(_ObjId *self, PyObject *args) { - if (!Id::isValid(self->oid_.id)) - { + if (!Id::isValid(self->oid_.id)) { RAISE_INVALID_ID(NULL, "moose_ObjId_connect"); } extern PyTypeObject ObjIdType; - PyObject * destPtr = NULL; - char * srcField = NULL, * destField = NULL, * msgType = NULL; + PyObject *destPtr = NULL; + char *srcField = NULL, *destField = NULL, *msgType = NULL; static char default_msg_type[] = "Single"; - if(!PyArg_ParseTuple(args, - "sOs|s:moose_ObjId_connect", - &srcField, - &destPtr, - &destField, - &msgType)) - { + if (!PyArg_ParseTuple( + args, "sOs|s:moose_ObjId_connect", &srcField, &destPtr, &destField, &msgType)) { return NULL; } - if (msgType == NULL) - { + if (msgType == NULL) { msgType = default_msg_type; } - _ObjId * dest = reinterpret_cast<_ObjId*>(destPtr); - ObjId mid = SHELLPTR->doAddMsg(msgType, - self->oid_, - string(srcField), - dest->oid_, - string(destField)); - if (mid.bad()) - { - PyErr_SetString(PyExc_NameError, - "connect failed: check field names and type compatibility."); + _ObjId *dest = reinterpret_cast<_ObjId *>(destPtr); + ObjId mid = SHELLPTR->doAddMsg( + msgType, self->oid_, string(srcField), dest->oid_, string(destField)); + if (mid.bad()) { + PyErr_SetString( + PyExc_NameError, + "connect failed: check field names and type compatibility."); return NULL; } - _ObjId* msgMgrId = (_ObjId*)PyObject_New(_ObjId, &ObjIdType); + _ObjId *msgMgrId = (_ObjId *)PyObject_New(_ObjId, &ObjIdType); msgMgrId->oid_ = mid; - return (PyObject*)msgMgrId; + return (PyObject *)msgMgrId; } -PyDoc_STRVAR(moose_ObjId_richcompare_documentation, - "Compare two element instances. This just does a string comparison of\n" - "the paths of the element instances. This function exists only to\n" - "facilitate certain operations requiring sorting/comparison, like\n" - "using elements for dict keys. Conceptually only equality comparison is\n" - "meaningful for elements.\n"); -PyObject* moose_ObjId_richcompare(_ObjId * self, PyObject * other, int op) +PyDoc_STRVAR( + moose_ObjId_richcompare_documentation, + "Compare two element instances. This just does a string comparison of\n" + "the paths of the element instances. This function exists only to\n" + "facilitate certain operations requiring sorting/comparison, like\n" + "using elements for dict keys. Conceptually only equality comparison is\n" + "meaningful for elements.\n"); +PyObject *moose_ObjId_richcompare(_ObjId *self, PyObject *other, int op) { - if (!Id::isValid(self->oid_.id)) - { + if (!Id::isValid(self->oid_.id)) { RAISE_INVALID_ID(NULL, "moose_ObjId_richcompare"); } extern PyTypeObject ObjIdType; - if ((self != NULL && other == NULL) || (self == NULL && other != NULL)) - { - if (op == Py_EQ) - { + if ((self != NULL && other == NULL) || (self == NULL && other != NULL)) { + if (op == Py_EQ) { Py_RETURN_FALSE; - } - else if (op == Py_NE) - { + } else if (op == Py_NE) { Py_RETURN_TRUE; - } - else - { - PyErr_SetString(PyExc_TypeError, "Cannot compare NULL with non-NULL"); + } else { + PyErr_SetString(PyExc_TypeError, + "Cannot compare NULL with non-NULL"); return NULL; } } - if (!PyObject_IsInstance(other, (PyObject*)&ObjIdType)) - { + if (!PyObject_IsInstance(other, (PyObject *)&ObjIdType)) { ostringstream error; - error << "Cannot compare ObjId with " - << Py_TYPE(other)->tp_name; + error << "Cannot compare ObjId with " << Py_TYPE(other)->tp_name; PyErr_SetString(PyExc_TypeError, error.str().c_str()); return NULL; } - if (!Id::isValid(((_ObjId*)other)->oid_.id)) - { + if (!Id::isValid(((_ObjId *)other)->oid_.id)) { RAISE_INVALID_ID(NULL, "moose_ObjId_richcompare"); } string l_path = self->oid_.path(); - string r_path = ((_ObjId*)other)->oid_.path(); + string r_path = ((_ObjId *)other)->oid_.path(); int result = l_path.compare(r_path); - if (result == 0) - { - if (op == Py_EQ || op == Py_LE || op == Py_GE) - { + if (result == 0) { + if (op == Py_EQ || op == Py_LE || op == Py_GE) { Py_RETURN_TRUE; } Py_RETURN_FALSE; - } - else if (result < 0) - { - if (op == Py_LT || op == Py_LE || op == Py_NE) - { + } else if (result < 0) { + if (op == Py_LT || op == Py_LE || op == Py_NE) { Py_RETURN_TRUE; } Py_RETURN_FALSE; - } - else - { - if (op == Py_GT || op == Py_GE || op == Py_NE) - { + } else { + if (op == Py_GT || op == Py_GE || op == Py_NE) { Py_RETURN_TRUE; } Py_RETURN_FALSE; @@ -2266,28 +2008,25 @@ PyDoc_STRVAR(moose_ObjId_getDataIndex_documentation, " >>> comp = moose.Compartment('/comp')\n" " >>> comp.getDataIndex()\n" " >>> 0\n" - "" - ); -PyObject * moose_ObjId_getDataIndex(_ObjId * self) + ""); +PyObject *moose_ObjId_getDataIndex(_ObjId *self) { - if (!Id::isValid(self->oid_.id)) - { + if (!Id::isValid(self->oid_.id)) { RAISE_INVALID_ID(NULL, "moose_ObjId_getDataIndex"); } - PyObject * ret = Py_BuildValue("I", self->oid_.dataIndex); + PyObject *ret = Py_BuildValue("I", self->oid_.dataIndex); return ret; } // WARNING: fieldIndex has been deprecated in dh_branch. This // needs to be updated accordingly. The current code is just // place-holer to avoid compilation errors. -PyObject * moose_ObjId_getFieldIndex(_ObjId * self) +PyObject *moose_ObjId_getFieldIndex(_ObjId *self) { - if (!Id::isValid(self->oid_.id)) - { + if (!Id::isValid(self->oid_.id)) { RAISE_INVALID_ID(NULL, "moose_ObjId_getFieldIndex"); } - PyObject * ret = Py_BuildValue("I", self->oid_.dataIndex); + PyObject *ret = Py_BuildValue("I", self->oid_.dataIndex); return ret; } @@ -2295,169 +2034,140 @@ PyObject * moose_ObjId_getFieldIndex(_ObjId * self) // Python method lists for PyObject of ObjId /////////////////////////////////////////////// -static PyMethodDef ObjIdMethods[] = -{ - { - "getFieldType", (PyCFunction)moose_ObjId_getFieldType, METH_VARARGS, - moose_ObjId_getFieldType_documentation - }, - { - "getField", (PyCFunction)moose_ObjId_getField, METH_VARARGS, - moose_ObjId_getField_documentation - }, - { - "setField", (PyCFunction)moose_ObjId_setField, METH_VARARGS, - moose_ObjId_setField_documentation - }, - { - "getLookupField", (PyCFunction)moose_ObjId_getLookupField, METH_VARARGS, - moose_ObjId_getLookupField_documentation - }, - { - "setLookupField", (PyCFunction)moose_ObjId_setLookupField, METH_VARARGS, - moose_ObjId_setLookupField_documentation - }, - { - "getId", (PyCFunction)moose_ObjId_getId, METH_NOARGS, - moose_ObjId_getId_documentation - }, - { - "vec", (PyCFunction)moose_ObjId_getId, METH_NOARGS, - "Return the vec this element belongs to. This is overridden by the" - " attribute of the same name for quick access." - }, - { - "getFieldNames", (PyCFunction)moose_ObjId_getFieldNames, METH_VARARGS, - moose_ObjId_getFieldNames_documenation - }, - { - "getNeighbors", (PyCFunction)moose_ObjId_getNeighbors, METH_VARARGS, - moose_ObjId_getNeighbors_documentation - }, - { - "connect", (PyCFunction)moose_ObjId_connect, METH_VARARGS, - moose_ObjId_connect_documentation - }, - { - "getDataIndex", (PyCFunction)moose_ObjId_getDataIndex, METH_NOARGS, - moose_ObjId_getDataIndex_documentation - }, - { - "getFieldIndex", (PyCFunction)moose_ObjId_getFieldIndex, METH_NOARGS, - "Get the index of this object as a field." - }, - { - "setDestField", (PyCFunction)moose_ObjId_setDestField, METH_VARARGS, - moose_ObjId_setDestField_documentation - }, - {NULL, NULL, 0, NULL}, /* Sentinel */ +static PyMethodDef ObjIdMethods[] = { + {"getFieldType", (PyCFunction)moose_ObjId_getFieldType, + METH_VARARGS, moose_ObjId_getFieldType_documentation}, + {"getField", (PyCFunction)moose_ObjId_getField, + METH_VARARGS, moose_ObjId_getField_documentation}, + {"setField", (PyCFunction)moose_ObjId_setField, + METH_VARARGS, moose_ObjId_setField_documentation}, + {"getLookupField", (PyCFunction)moose_ObjId_getLookupField, + METH_VARARGS, moose_ObjId_getLookupField_documentation}, + {"setLookupField", (PyCFunction)moose_ObjId_setLookupField, + METH_VARARGS, moose_ObjId_setLookupField_documentation}, + {"getId", (PyCFunction)moose_ObjId_getId, + METH_NOARGS, moose_ObjId_getId_documentation}, + {"vec", (PyCFunction)moose_ObjId_getId, METH_NOARGS, + "Return the vec this element belongs to. This is overridden by the" + " attribute of the same name for quick access."}, + {"getFieldNames", (PyCFunction)moose_ObjId_getFieldNames, + METH_VARARGS, moose_ObjId_getFieldNames_documenation}, + {"getNeighbors", (PyCFunction)moose_ObjId_getNeighbors, + METH_VARARGS, moose_ObjId_getNeighbors_documentation}, + {"connect", (PyCFunction)moose_ObjId_connect, + METH_VARARGS, moose_ObjId_connect_documentation}, + {"getDataIndex", (PyCFunction)moose_ObjId_getDataIndex, + METH_NOARGS, moose_ObjId_getDataIndex_documentation}, + {"getFieldIndex", (PyCFunction)moose_ObjId_getFieldIndex, + METH_NOARGS, "Get the index of this object as a field."}, + {"setDestField", (PyCFunction)moose_ObjId_setDestField, + METH_VARARGS, moose_ObjId_setDestField_documentation}, + {NULL, NULL, 0, NULL}, /* Sentinel */ }; - /////////////////////////////////////////////// // Type defs for PyObject of ObjId /////////////////////////////////////////////// -PyDoc_STRVAR(moose_ObjId_documentation, - "Individual moose element contained in an array-type object" - " (vec).\n" - "\n" - "Each element has a unique path, possibly with its index in" - " the vec. These are identified by three components: vec, dndex and" - " findex. vec is the containing vec, which is identified by a unique" - " number (field `value`). `dindex` is the index of the current" - " item in the containing vec. `dindex` is 0 for single elements." - " findex is field index, specifying the index of elements which exist" - " as fields of another moose element.\n" - "\n" - "Notes\n" - "-----\n" - "Users need not create melement directly. Instead use the named moose" - " class for creating new elements. To get a reference to an existing" - " element, use the :ref:`moose.element` function.\n" - "\n" - "Parameters\n" - "----------\n" - "path : str\n" - " path of the element to be created.\n" - "\n" - "n : positive int, optional\n" - " defaults to 1. If greater, then a vec of that size is created and\n" - " this element is a reference to the first entry of the vec.\n" - "\n" - "g : int, optional\n" - " if 1, this is a global element, else if 0 (default), the element\n" - " is local to the current node.\n" - "\n" - "dtype : str\n" - " name of the class of the element. If creating any concrete\n" - " subclass, this is automatically taken from the class name and\n" - " should not be specified explicitly.\n" - "\n" - "Attributes\n" - "----------\n" - "vec : moose.vec\n" - " The vec containing this element. `vec` wraps the Id of the object in MOOSE C++ API.\n" - "\n" - "dindex : int\n" - " index of this element in the container vec\n" - "\n" - "findex: int\n" - " if this is a tertiary object, i.e. acts as a field in another\n" - " element (like synapse[0] in IntFire[1]), then the index of\n" - " this field in the containing element.\n" - "\n" - "Examples\n" - "--------\n" - "\n" - ">>> a = Neutral('alpha') # Creates element named `alpha` under current working element\n" - ">>> b = Neutral('alpha/beta') # Creates the element named `beta` under `alpha`\n" - ">>> c = moose.melement(b)" - ); - -PyTypeObject ObjIdType = -{ - PyVarObject_HEAD_INIT(NULL, 0) /* tp_head */ - "moose.melement", /* tp_name */ +PyDoc_STRVAR( + moose_ObjId_documentation, + "Individual moose element contained in an array-type object" + " (vec).\n" + "\n" + "Each element has a unique path, possibly with its index in" + " the vec. These are identified by three components: vec, dndex and" + " findex. vec is the containing vec, which is identified by a unique" + " number (field `value`). `dindex` is the index of the current" + " item in the containing vec. `dindex` is 0 for single elements." + " findex is field index, specifying the index of elements which exist" + " as fields of another moose element.\n" + "\n" + "Notes\n" + "-----\n" + "Users need not create melement directly. Instead use the named moose" + " class for creating new elements. To get a reference to an existing" + " element, use the :ref:`moose.element` function.\n" + "\n" + "Parameters\n" + "----------\n" + "path : str\n" + " path of the element to be created.\n" + "\n" + "n : positive int, optional\n" + " defaults to 1. If greater, then a vec of that size is created and\n" + " this element is a reference to the first entry of the vec.\n" + "\n" + "g : int, optional\n" + " if 1, this is a global element, else if 0 (default), the element\n" + " is local to the current node.\n" + "\n" + "dtype : str\n" + " name of the class of the element. If creating any concrete\n" + " subclass, this is automatically taken from the class name and\n" + " should not be specified explicitly.\n" + "\n" + "Attributes\n" + "----------\n" + "vec : moose.vec\n" + " The vec containing this element. `vec` wraps the Id of the object in " + "MOOSE C++ API.\n" + "\n" + "dindex : int\n" + " index of this element in the container vec\n" + "\n" + "findex: int\n" + " if this is a tertiary object, i.e. acts as a field in another\n" + " element (like synapse[0] in IntFire[1]), then the index of\n" + " this field in the containing element.\n" + "\n" + "Examples\n" + "--------\n" + "\n" + ">>> a = Neutral('alpha') # Creates element named `alpha` under current " + "working element\n" + ">>> b = Neutral('alpha/beta') # Creates the element named `beta` under " + "`alpha`\n" + ">>> c = moose.melement(b)"); + +PyTypeObject ObjIdType = { + PyVarObject_HEAD_INIT(NULL, 0) /* tp_head */ + "moose.melement", /* tp_name */ sizeof(_ObjId), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ - 0, /* tp_compare */ + 0, /* tp_compare */ (reprfunc)moose_ObjId_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ (hashfunc)moose_ObjId_hash, /* tp_hash */ 0, /* tp_call */ - (reprfunc)moose_ObjId_str, /* tp_str */ + (reprfunc)moose_ObjId_str, /* tp_str */ (getattrofunc)moose_ObjId_getattro, /* tp_getattro */ (setattrofunc)moose_ObjId_setattro, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - moose_ObjId_documentation, - 0, /* tp_traverse */ - 0, /* tp_clear */ + moose_ObjId_documentation, 0, /* tp_traverse */ + 0, /* tp_clear */ (richcmpfunc)moose_ObjId_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - ObjIdMethods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc) moose_ObjId_init, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + ObjIdMethods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)moose_ObjId_init, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ }; - - // // melement.cpp ends here diff --git a/pymoose/moosemodule.cpp b/pymoose/moosemodule.cpp index 67c2a4d083..662911c0d2 100644 --- a/pymoose/moosemodule.cpp +++ b/pymoose/moosemodule.cpp @@ -41,8 +41,7 @@ using namespace std; - -extern Id init( int argc, char ** argv, bool& doUnitTests); +extern Id init(int argc, char **argv, bool &doUnitTests); extern void initMsgManagers(); /*----------------------------------------------------------------------------- @@ -53,27 +52,27 @@ extern void initMsgManagers(); * themselves. If seed is not set by user, it uses std::random_device to * initialize itself. *-----------------------------------------------------------------------------*/ -void pymoose_mtseed_( long int seed ) +void pymoose_mtseed_(long int seed) { - moose::mtseed( seed ); + moose::mtseed(seed); } -double pymoose_mtrand_( void ) +double pymoose_mtrand_(void) { - return moose::mtrand( ); + return moose::mtrand(); } -bool setupSocketStreamer(const string addr ) +bool setupSocketStreamer(const string addr) { - LOG(moose::debug, "Setting streamer with addr " << addr ); + LOG(moose::debug, "Setting streamer with addr " << addr); // Find all tables. - vector< ObjId > tables; - wildcardFind( "/##[TYPE=Table2]", tables ); - wildcardFind( "/##[TYPE=Table]", tables, false ); + vector tables; + wildcardFind("/##[TYPE=Table2]", tables); + wildcardFind("/##[TYPE=Table]", tables, false); - if( tables.size() < 1 ) - { - LOG( moose::warning, "No table found. MOOSE will not create a streamer." ); + if (tables.size() < 1) { + LOG(moose::warning, + "No table found. MOOSE will not create a streamer."); return false; } @@ -83,51 +82,47 @@ bool setupSocketStreamer(const string addr ) Field::set(st, "address", addr); LOG(moose::debug, "Found " << tables.size() << " tables."); - for( auto &t : tables ) - SetGet1::set(st, "addTable", t ); + for (auto &t : tables) + SetGet1::set(st, "addTable", t); return true; } /** - Utility function to get all the individual elements when ALLDATA is dataIndex. + Utility function to get all the individual elements when ALLDATA is + dataIndex. */ vector all_elements(Id id) { vector ret; - unsigned int ii = 0; // storage for dataIndex - unsigned int jj = 0; // storage for fieldIndex - unsigned int * iptr = ⅈ // this will point to the fastest changing index + unsigned int ii = 0; // storage for dataIndex + unsigned int jj = 0; // storage for fieldIndex + unsigned int *iptr = ⅈ // this will point to the fastest changing index unsigned int length; - if (id.element()->hasFields()) - { + if (id.element()->hasFields()) { iptr = &jj; - length = Field< unsigned int>::get(id, "numField"); - } - else - { + length = Field::get(id, "numField"); + } else { length = id.element()->numData(); } - for (*iptr = 0; *iptr < length; ++(*iptr)) - { + for (*iptr = 0; *iptr < length; ++(*iptr)) { ret.push_back(ObjId(id, ii, jj)); } return ret; } - /** * @brief Handle signal raised by user during simulation. * * @param signum */ -void handle_keyboard_interrupts( int signum ) +void handle_keyboard_interrupts(int signum) { - LOG( moose::info, "Interrupt signal (" << signum << ") received."); + LOG(moose::info, "Interrupt signal (" << signum << ") received."); // Get the shell and cleanup. - Shell* shell = reinterpret_cast(getShell(0, NULL).eref().data()); + Shell *shell = reinterpret_cast(getShell(0, NULL).eref().data()); shell->cleanSimulation(); - exit( signum ); + exit(signum); } // IdType and ObjIdType are defined in vec.cpp and @@ -142,47 +137,38 @@ extern PyTypeObject moose_ElementField; int verbosity = 0; static int isInfinite = 0; static unsigned int numNodes = 1; -static int doUnitTests = 0; static int quitFlag = 0; /** Utility function to convert an Python integer or a sequence object into a vector of dimensions */ -vector pysequence_to_dimvec(PyObject * dims) +vector pysequence_to_dimvec(PyObject *dims) { - vector vec_dims; + vector vec_dims; Py_ssize_t num_dims = 1; long dim_value = 1; - if (dims) - { + if (dims) { // First try to use it as a tuple of dimensions - if (PyTuple_Check(dims)) - { + if (PyTuple_Check(dims)) { num_dims = PyTuple_Size(dims); - for (Py_ssize_t ii = 0; ii < num_dims; ++ ii) - { - PyObject* dim = PyTuple_GetItem(dims, ii); + for (Py_ssize_t ii = 0; ii < num_dims; ++ii) { + PyObject *dim = PyTuple_GetItem(dims, ii); dim_value = PyInt_AsLong(dim); - if ((dim_value == -1) && PyErr_Occurred()) - { + if ((dim_value == -1) && PyErr_Occurred()) { return vec_dims; } vec_dims.push_back((unsigned int)dim_value); } - } - else if (PyInt_Check(dims)) // 1D array + } else if (PyInt_Check(dims)) // 1D array { dim_value = PyInt_AsLong(dims); - if (dim_value <= 0) - { + if (dim_value <= 0) { dim_value = 1; } vec_dims.push_back(dim_value); } - } - else - { + } else { vec_dims.push_back(dim_value); } return vec_dims; @@ -193,241 +179,214 @@ vector pysequence_to_dimvec(PyObject * dims) structure is allocated here and it is the responsibility of the caller to free that memory. */ -void * to_cpp(PyObject * object, char typecode) +void *to_cpp(PyObject *object, char typecode) { - switch(typecode) - { - case 'i': - { - int * ret = new int(); - * ret = PyInt_AsLong(object); - return (void*)ret; + switch (typecode) { + case 'i': { + int *ret = new int(); + *ret = PyInt_AsLong(object); + return (void *)ret; } - case 'l': - { + case 'l': { long v = PyInt_AsLong(object); - long * ret = new long(); + long *ret = new long(); *ret = v; - return (void*)ret; + return (void *)ret; } - case 'h': - { + case 'h': { short v = PyInt_AsLong(object); - short * ret = new short(); + short *ret = new short(); *ret = v; - return (void*)ret; + return (void *)ret; } - case 'f': - { + case 'f': { float v = (float)PyFloat_AsDouble(object); - if ( v == -1.0 && PyErr_Occurred()) - { - PyErr_SetString(PyExc_TypeError, "Expected a sequence of floating point numbers."); - } - else - { - float * ret = new float(); + if (v == -1.0 && PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "Expected a sequence of floating point numbers."); + } else { + float *ret = new float(); *ret = v; - return (void*)ret; + return (void *)ret; } } - case 'd': - { + case 'd': { double v = PyFloat_AsDouble(object); - if ( v == -1.0 && PyErr_Occurred()) - { - PyErr_SetString(PyExc_TypeError, "Expected a sequence of floating point numbers."); - } - else - { - double * ret = new double(); + if (v == -1.0 && PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "Expected a sequence of floating point numbers."); + } else { + double *ret = new double(); *ret = v; - return (void*)ret; + return (void *)ret; } } - case 's': - { + case 's': { assert(object); - char* tmp = PyString_AsString(object); - if (tmp == NULL) - { + char *tmp = PyString_AsString(object); + if (tmp == NULL) { return NULL; } - string * ret = new string(tmp); - return (void*)ret; + string *ret = new string(tmp); + return (void *)ret; } - case 'I': - { + case 'I': { unsigned int v = PyInt_AsUnsignedLongMask(object); - unsigned int * ret = new unsigned int(); + unsigned int *ret = new unsigned int(); *ret = v; - return (void*)ret; + return (void *)ret; } - case 'k': - { + case 'k': { unsigned long v = PyInt_AsUnsignedLongMask(object); - unsigned long * ret = new unsigned long(); + unsigned long *ret = new unsigned long(); *ret = v; - return (void*)ret; - } - case 'x': - { - _Id * value = (_Id*)object; - if (value != NULL) - { - Id * ret = new Id(); - * ret = value->id_; - return (void*)ret; + return (void *)ret; + } + case 'x': { + _Id *value = (_Id *)object; + if (value != NULL) { + Id *ret = new Id(); + *ret = value->id_; + return (void *)ret; } } - case 'y': - { - _ObjId * value = (_ObjId*)object; - if (value != NULL) - { - ObjId * ret = new ObjId(); - * ret = value->oid_; - return (void*)ret; + case 'y': { + _ObjId *value = (_ObjId *)object; + if (value != NULL) { + ObjId *ret = new ObjId(); + *ret = value->oid_; + return (void *)ret; } } case 'v': - return PySequenceToVector< int >(object, 'i'); + return PySequenceToVector(object, 'i'); case 'N': - return PySequenceToVector < unsigned int > (object, 'I'); + return PySequenceToVector(object, 'I'); case 'w': - return PySequenceToVector < short > (object, 'h'); + return PySequenceToVector(object, 'h'); case 'M': - return PySequenceToVector < long > (object, 'l'); + return PySequenceToVector(object, 'l'); case 'P': - return PySequenceToVector < unsigned long > (object, 'k'); + return PySequenceToVector(object, 'k'); case 'F': - return PySequenceToVector < float > (object, 'f'); + return PySequenceToVector(object, 'f'); case 'D': - return PySequenceToVector < double > (object, 'd'); + return PySequenceToVector(object, 'd'); case 'S': - return PySequenceToVector < string > (object, 's'); + return PySequenceToVector(object, 's'); case 'Y': - return PySequenceToVector < ObjId > (object, 'y'); + return PySequenceToVector(object, 'y'); case 'X': - return PySequenceToVector < Id > (object, 'x'); + return PySequenceToVector(object, 'x'); case 'R': - return PySequenceToVectorOfVectors< double >(object, 'd'); + return PySequenceToVectorOfVectors(object, 'd'); case 'Q': - return PySequenceToVectorOfVectors< int >(object, 'i'); + return PySequenceToVectorOfVectors(object, 'i'); case 'T': - return PySequenceToVectorOfVectors< unsigned int > (object, 'I'); + return PySequenceToVectorOfVectors(object, 'I'); } return NULL; } - /** Utility function to convert C++ object into Python object. */ -PyObject * to_py(void * obj, char typecode) +PyObject *to_py(void *obj, char typecode) { - switch(typecode) - { - case 'd': - { - double * ptr = static_cast(obj); + switch (typecode) { + case 'd': { + double *ptr = static_cast(obj); assert(ptr != NULL); return PyFloat_FromDouble(*ptr); } - case 's': // handle only C++ string and NOT C char array because static cast cannot differentiate the two - { - string * ptr = static_cast< string * >(obj); - assert (ptr != NULL); - return PyString_FromString(ptr->c_str()); - } - case 'x': - { - Id * ptr = static_cast< Id * >(obj); + case 's': // handle only C++ string and NOT C char array because static cast + // cannot differentiate the two + { + string *ptr = static_cast(obj); + assert(ptr != NULL); + return PyString_FromString(ptr->c_str()); + } + case 'x': { + Id *ptr = static_cast(obj); assert(ptr != NULL); - _Id * id = PyObject_New(_Id, &IdType); + _Id *id = PyObject_New(_Id, &IdType); id->id_ = *ptr; return (PyObject *)(id); } - case 'y': - { - ObjId * ptr = static_cast< ObjId * >(obj); + case 'y': { + ObjId *ptr = static_cast(obj); assert(ptr != NULL); - _ObjId * oid = PyObject_New(_ObjId, &ObjIdType); + _ObjId *oid = PyObject_New(_ObjId, &ObjIdType); oid->oid_ = *ptr; - return (PyObject*)oid; + return (PyObject *)oid; } - case 'l': - { - long * ptr = static_cast< long * >(obj); + case 'l': { + long *ptr = static_cast(obj); assert(ptr != NULL); return PyLong_FromLong(*ptr); } - case 'k': - { - unsigned long * ptr = static_cast< unsigned long * >(obj); + case 'k': { + unsigned long *ptr = static_cast(obj); assert(ptr != NULL); return PyLong_FromUnsignedLong(*ptr); } - case 'i': // integer + case 'i': // integer { - int * ptr = static_cast< int * >(obj); + int *ptr = static_cast(obj); assert(ptr != NULL); return PyInt_FromLong(*ptr); } - case 'I': // unsigned int + case 'I': // unsigned int { - unsigned int * ptr = static_cast< unsigned int * >(obj); + unsigned int *ptr = static_cast(obj); assert(ptr != NULL); return PyLong_FromUnsignedLong(*ptr); } - case 'b': //bool + case 'b': // bool { - bool * ptr = static_cast< bool * >(obj); + bool *ptr = static_cast(obj); assert(ptr != NULL); - if (*ptr) - { + if (*ptr) { Py_RETURN_TRUE; - } - else - { + } else { Py_RETURN_FALSE; } } #ifdef HAVE_LONG_LONG - case 'L': //long long + case 'L': // long long { - long long * ptr = static_cast< long long * > (obj); + long long *ptr = static_cast(obj); assert(ptr != NULL); return PyLong_FromLongLong(*ptr); } - case 'K': // unsigned long long + case 'K': // unsigned long long { - unsigned long long * ptr = static_cast< unsigned long long * >(obj); + unsigned long long *ptr = static_cast(obj); assert(ptr != NULL); return PyLong_FromUnsignedLongLong(*ptr); } -#endif // HAVE_LONG_LONG - case 'f': // float +#endif // HAVE_LONG_LONG + case 'f': // float { - float * ptr = static_cast< float* >(obj); + float *ptr = static_cast(obj); assert(ptr != NULL); return PyFloat_FromDouble(*ptr); } - case 'c': // char + case 'c': // char { - char * ptr = static_cast< char * >(obj); + char *ptr = static_cast(obj); assert(ptr != NULL); return Py_BuildValue("c", *ptr); } - case 'h': //short + case 'h': // short { - short * ptr = static_cast< short* >(obj); + short *ptr = static_cast(obj); assert(ptr != NULL); return Py_BuildValue("h", *ptr); } - case 'H': // unsigned short + case 'H': // unsigned short { - unsigned short * ptr = static_cast< unsigned short * >(obj); + unsigned short *ptr = static_cast(obj); assert(ptr != NULL); return Py_BuildValue("H", *ptr); } @@ -444,12 +403,10 @@ PyObject * to_py(void * obj, char typecode) case 'S': case 'T': case 'Q': - case 'R': - { + case 'R': { return to_pytuple(obj, innerType(typecode)); } - default: - { + default: { PyErr_SetString(PyExc_TypeError, "unhandled data type"); return NULL; } @@ -463,21 +420,20 @@ PyObject * to_py(void * obj, char typecode) decrements the refcount of the tuple and returns NULL. Returns the tuple on success. */ -PyObject * convert_and_set_tuple_entry(PyObject * tuple, unsigned int index, void * vptr, char typecode) +PyObject *convert_and_set_tuple_entry(PyObject *tuple, unsigned int index, void *vptr, char typecode) { - PyObject * item = to_py(vptr, typecode); - if (item == NULL) - { + PyObject *item = to_py(vptr, typecode); + if (item == NULL) { return NULL; // the error message would have been populated by to_cpp } - if (PyTuple_SetItem(tuple, (Py_ssize_t)index, item) != 0) - { - PyErr_SetString(PyExc_RuntimeError, "convert_and_set_tuple_entry: could not set tuple entry."); + if (PyTuple_SetItem(tuple, (Py_ssize_t)index, item) != 0) { + PyErr_SetString( + PyExc_RuntimeError, + "convert_and_set_tuple_entry: could not set tuple entry."); return NULL; } #ifndef NDEBUG - if (verbosity > 2) - { + if (verbosity > 2) { cout << "Set tuple " << tuple << " entry " << index << " with " << item << endl; } #endif @@ -487,216 +443,200 @@ PyObject * convert_and_set_tuple_entry(PyObject * tuple, unsigned int index, voi /** Convert a C++ vector to Python tuple */ -PyObject * to_pytuple(void * obj, char typecode) +PyObject *to_pytuple(void *obj, char typecode) { - PyObject * ret; - switch (typecode) - { - case 'd': // vector + PyObject *ret; + switch (typecode) { + case 'd': // vector { - vector< double > * vec = static_cast< vector < double >* >(obj); + vector *vec = static_cast *>(obj); assert(vec != NULL); npy_intp size = (npy_intp)(vec->size()); ret = PyArray_SimpleNew(1, &size, NPY_DOUBLE); assert(ret != NULL); - char * ptr = PyArray_BYTES((PyArrayObject*)ret); + char *ptr = PyArray_BYTES((PyArrayObject *)ret); memcpy(ptr, &(*vec)[0], vec->size() * sizeof(double)); return ret; } - case 'i': // vector + case 'i': // vector { - vector< int > * vec = static_cast< vector < int >* >(obj); + vector *vec = static_cast *>(obj); assert(vec != NULL); npy_intp size = (npy_intp)(vec->size()); ret = PyArray_SimpleNew(1, &size, NPY_INT); assert(ret != NULL); - char * ptr = PyArray_BYTES((PyArrayObject*)ret); + char *ptr = PyArray_BYTES((PyArrayObject *)ret); memcpy(ptr, &(*vec)[0], size * sizeof(int)); return ret; } - case 'I': // vector + case 'I': // vector { - vector< int > * vec = static_cast< vector < int >* >(obj); + vector *vec = static_cast *>(obj); assert(vec != NULL); npy_intp size = (npy_intp)(vec->size()); ret = PyArray_SimpleNew(1, &size, NPY_UINT); assert(ret != NULL); - char * ptr = PyArray_BYTES((PyArrayObject*)ret); + char *ptr = PyArray_BYTES((PyArrayObject *)ret); memcpy(ptr, &(*vec)[0], size * sizeof(unsigned int)); return ret; } - case 'l': // vector + case 'l': // vector { - vector< long > * vec = static_cast< vector < long >* >(obj); + vector *vec = static_cast *>(obj); assert(vec != NULL); npy_intp size = (npy_intp)(vec->size()); ret = PyArray_SimpleNew(1, &size, NPY_INT); assert(ret != NULL); - char * ptr = PyArray_BYTES((PyArrayObject*)ret); + char *ptr = PyArray_BYTES((PyArrayObject *)ret); memcpy(ptr, &(*vec)[0], size * sizeof(long)); return ret; } - case 'x': // vector + case 'x': // vector { - vector< Id > * vec = static_cast< vector < Id >* >(obj); + vector *vec = static_cast *>(obj); assert(vec != NULL); ret = PyTuple_New((Py_ssize_t)vec->size()); assert(ret != NULL); - for (unsigned int ii = 0; ii < vec->size(); ++ii) - { - if (convert_and_set_tuple_entry(ret, ii, (void*)&vec->at(ii), typecode) == NULL) - { + for (unsigned int ii = 0; ii < vec->size(); ++ii) { + if (convert_and_set_tuple_entry(ret, ii, (void *)&vec->at(ii), typecode) == NULL) { return NULL; } } break; } - case 'y': // vector + case 'y': // vector { - vector< ObjId > * vec = static_cast< vector < ObjId >* >(obj); + vector *vec = static_cast *>(obj); assert(vec != NULL); ret = PyTuple_New((Py_ssize_t)vec->size()); assert(ret != NULL); - for (unsigned int ii = 0; ii < vec->size(); ++ii) - { - if (convert_and_set_tuple_entry(ret, ii, (void*)&vec->at(ii), typecode) == NULL) - { + for (unsigned int ii = 0; ii < vec->size(); ++ii) { + if (convert_and_set_tuple_entry(ret, ii, (void *)&vec->at(ii), typecode) == NULL) { return NULL; } } break; } - case 'c': // vector + case 'c': // vector { - vector< char > * vec = static_cast< vector < char >* >(obj); + vector *vec = static_cast *>(obj); assert(vec != NULL); ret = PyTuple_New((Py_ssize_t)vec->size()); assert(ret != NULL); - for (unsigned int ii = 0; ii < vec->size(); ++ii) - { - if (convert_and_set_tuple_entry(ret, ii, (void*)&vec->at(ii), typecode) == NULL) - { + for (unsigned int ii = 0; ii < vec->size(); ++ii) { + if (convert_and_set_tuple_entry(ret, ii, (void *)&vec->at(ii), typecode) == NULL) { return NULL; } } break; } - case 'h': // vector + case 'h': // vector { - vector< short > * vec = static_cast< vector < short >* >(obj); + vector *vec = static_cast *>(obj); assert(vec != NULL); ret = PyTuple_New((Py_ssize_t)vec->size()); assert(ret != NULL); - for (unsigned int ii = 0; ii < vec->size(); ++ii) - { - if (convert_and_set_tuple_entry(ret, ii, (void*)&vec->at(ii), typecode) == NULL) - { + for (unsigned int ii = 0; ii < vec->size(); ++ii) { + if (convert_and_set_tuple_entry(ret, ii, (void *)&vec->at(ii), typecode) == NULL) { return NULL; } } break; } - case 'k': // vector + case 'k': // vector { - vector< unsigned int > * vec = static_cast< vector < unsigned int >* >(obj); + vector *vec = static_cast *>(obj); assert(vec != NULL); npy_intp size = (npy_intp)(vec->size()); ret = PyArray_SimpleNew(1, &size, NPY_UINT); assert(ret != NULL); - char * ptr = PyArray_BYTES((PyArrayObject*)ret); + char *ptr = PyArray_BYTES((PyArrayObject *)ret); memcpy(ptr, &(*vec)[0], size * sizeof(unsigned int)); return ret; } - case 'L': // vector - this is not used at present + case 'L': // vector - this is not used at present { - vector< long long> * vec = static_cast< vector < long long>* >(obj); + vector *vec = static_cast *>(obj); assert(vec != NULL); ret = PyTuple_New((Py_ssize_t)vec->size()); npy_intp size = (npy_intp)(vec->size()); ret = PyArray_SimpleNew(1, &size, NPY_LONGLONG); assert(ret != NULL); - char * ptr = PyArray_BYTES((PyArrayObject*)ret); + char *ptr = PyArray_BYTES((PyArrayObject *)ret); memcpy(ptr, &(*vec)[0], size * sizeof(long long)); return ret; } - case 'K': // vector - this is not used at present + case 'K': // vector - this is not used at present { - vector< unsigned long long> * vec = static_cast< vector < unsigned long long>* >(obj); + vector *vec = static_cast *>(obj); assert(vec != NULL); npy_intp size = (npy_intp)(vec->size()); ret = PyArray_SimpleNew(1, &size, NPY_ULONGLONG); assert(ret != NULL); - char * ptr = PyArray_BYTES((PyArrayObject*)ret); + char *ptr = PyArray_BYTES((PyArrayObject *)ret); memcpy(ptr, &(*vec)[0], size * sizeof(unsigned long long)); return ret; } - case 'F': // vector + case 'F': // vector { - vector< float > * vec = static_cast< vector < float >* >(obj); + vector *vec = static_cast *>(obj); assert(vec != NULL); npy_intp size = (npy_intp)(vec->size()); ret = PyArray_SimpleNew(1, &size, NPY_FLOAT); assert(ret != NULL); - char * ptr = PyArray_BYTES((PyArrayObject*)ret); + char *ptr = PyArray_BYTES((PyArrayObject *)ret); memcpy(ptr, &(*vec)[0], size * sizeof(float)); return ret; } - case 's': // vector + case 's': // vector { - vector< string > * vec = static_cast< vector < string >* >(obj); + vector *vec = static_cast *>(obj); assert(vec != NULL); ret = PyTuple_New((Py_ssize_t)vec->size()); assert(ret != NULL); - for (unsigned int ii = 0; ii < vec->size(); ++ii) - { + for (unsigned int ii = 0; ii < vec->size(); ++ii) { string v = vec->at(ii); - if (convert_and_set_tuple_entry(ret, ii, (void*)&v, typecode) == NULL) - { + if (convert_and_set_tuple_entry(ret, ii, (void *)&v, typecode) == NULL) { return NULL; } } break; } - case 'N': // vector< vector > + case 'N': // vector< vector > { - vector< vector< unsigned int > > * vec = static_cast< vector < vector< unsigned int > >* >(obj); + vector> *vec = + static_cast> *>(obj); assert(vec != NULL); ret = PyTuple_New((Py_ssize_t)vec->size()); assert(ret != NULL); - for (unsigned int ii = 0; ii < vec->size(); ++ii) - { - if (convert_and_set_tuple_entry(ret, ii, (void*)&vec->at(ii), typecode) == NULL) - { + for (unsigned int ii = 0; ii < vec->size(); ++ii) { + if (convert_and_set_tuple_entry(ret, ii, (void *)&vec->at(ii), typecode) == NULL) { return NULL; } } break; } - case 'v': // vector< vector < int > > + case 'v': // vector< vector < int > > { - vector< vector< int > > * vec = static_cast< vector < vector< int > >* >(obj); + vector> *vec = static_cast> *>(obj); assert(vec != NULL); ret = PyTuple_New((Py_ssize_t)vec->size()); assert(ret != NULL); - for (unsigned int ii = 0; ii < vec->size(); ++ii) - { - if (convert_and_set_tuple_entry(ret, ii, (void*)&vec->at(ii), typecode) == NULL) - { + for (unsigned int ii = 0; ii < vec->size(); ++ii) { + if (convert_and_set_tuple_entry(ret, ii, (void *)&vec->at(ii), typecode) == NULL) { return NULL; } } break; } - case 'D': // vector< vector > + case 'D': // vector< vector > { - vector< vector< double > > * vec = static_cast< vector < vector< double > >* >(obj); + vector> *vec = static_cast> *>(obj); assert(vec != NULL); ret = PyTuple_New((Py_ssize_t)vec->size()); assert(ret != NULL); - for (unsigned int ii = 0; ii < vec->size(); ++ii) - { - if (convert_and_set_tuple_entry(ret, ii, (void*)&vec->at(ii), typecode) == NULL) - { + for (unsigned int ii = 0; ii < vec->size(); ++ii) { + if (convert_and_set_tuple_entry(ret, ii, (void *)&vec->at(ii), typecode) == NULL) { return NULL; } } @@ -710,16 +650,16 @@ PyObject * to_pytuple(void * obj, char typecode) } // Global store of defined MOOSE classes. -map& get_moose_classes() +map &get_moose_classes() { static map defined_classes; return defined_classes; } // Global storage for PyGetSetDef structs for LookupFields. -map >& get_getsetdefs() +map> &get_getsetdefs() { - static map > getset_defs; + static map> getset_defs; return getset_defs; } @@ -727,117 +667,43 @@ map >& get_getsetdefs() map of fields which are aliased in Python to avoid collision with Python keywords. */ -const map& get_field_alias() +const map &get_field_alias() { static map alias; - if (alias.empty()) - { + if (alias.empty()) { // alias["class_"] = "class"; alias["lambda_"] = "lambda"; } return alias; } - -// Minimum number of arguments for setting destFinfo - 1-st -// the finfo name. -// Py_ssize_t minArgs = 1; - -// // Arbitrarily setting maximum on variable argument list. Read: -// // http://www.swig.org/Doc1.3/Varargs.html to understand why -// Py_ssize_t maxArgs = 10; - - -/////////////////////////////////////////////////////////////////////////// -// Helper routines -/////////////////////////////////////////////////////////////////////////// - - -/** - Get the environment variables and set runtime environment based - on them. -*/ -vector setup_runtime_env() -{ - const map& argmap = moose::getArgMap(); - vector args; - args.push_back("moose"); - map::const_iterator it; - - it = argmap.find("INFINITE"); - if (it != argmap.end()) - { - istringstream(it->second) >> isInfinite; - if (isInfinite) - { - args.push_back("-i"); - } - } - - it = argmap.find("QUIT"); - if (it != argmap.end()) - { - istringstream(it->second) >> quitFlag; - if (quitFlag) - { - args.push_back("-q"); - } - } - it = argmap.find("VERBOSITY"); - if (it != argmap.end()) - { - istringstream(it->second) >> verbosity; - } - it = argmap.find("DOUNITTESTS"); - if (it != argmap.end()) - { - istringstream(it->second) >> doUnitTests; - } - - if (verbosity > 0) - { - cout << "ENVIRONMENT: " << endl - << "----------------------------------------" << endl - // << " SINGLETHREADED = " << isSingleThreaded << endl - << " INFINITE = " << isInfinite << endl - << " NUMNODES = " << numNodes << endl - // << " NUMPTHREADS = " << numProcessThreads << endl - << " VERBOSITY = " << verbosity << endl - << " DOUNITTESTS = " << doUnitTests << endl - << "========================================" << endl; - } - return args; -} //! setup_runtime_env() - /** Create the shell instance unless already created. This calls basecode/main.cpp:init(argc, argv) to do the initialization. Return the Id of the Shell object. */ -Id getShell(int argc, char ** argv) +Id getShell(int argc, char **argv) { static int inited = 0; if (inited) return Id(0); bool dounit = false; - Id shellId = init(argc, argv, dounit); + Id shellId = init(argc, argv, dounit); inited = 1; - Shell * shellPtr = reinterpret_cast(shellId.eref().data()); - if ( shellPtr->myNode() == 0 ) - { - if ( Shell::numNodes() > 1 ) - { + Shell *shellPtr = reinterpret_cast(shellId.eref().data()); + if (shellPtr->myNode() == 0) { + if (Shell::numNodes() > 1) { // Use the last clock for the postmaster, so that it is called // after everything else has been processed and all messages // are ready to send out. - shellPtr->doUseClock( "/postmaster", "process", 9 ); - shellPtr->doSetClock( 9, 1.0 ); // Use a sensible default. + shellPtr->doUseClock("/postmaster", "process", 9); + shellPtr->doSetClock(9, 1.0); // Use a sensible default. } } return shellId; -} +} /** Clean up after yourself. @@ -846,33 +712,18 @@ void finalize() { static bool finalized = false; if (finalized) - { return; - } + finalized = true; Id shellId = getShell(0, NULL); + // Clear the memory for PyGetSetDefs. The key // (name) was dynamically allocated using calloc. So was the // docstring. - for (map >::iterator it = - get_getsetdefs().begin(); - it != get_getsetdefs().end(); - ++it) - { - vector &getsets = it->second; - // for (unsigned int ii = 0; ii < getsets.size()-1; ++ii){ // the -1 is for the empty sentinel entry - // free(getsets[ii].name); - // Py_XDECREF(getsets[ii].closure); - // } - } + for (auto it = get_getsetdefs().begin(); it != get_getsetdefs().end(); ++it) + vector &getsets = it->second; + get_getsetdefs().clear(); - // deallocate the class names calloc-ed at initialization. - // for(map< string, PyTypeObject* >::iterator it = get_moose_classes().begin(); - // it != get_moose_classes().end(); ++it){ - // PyTypeObject * classObject = it->second; - // free(classObject->tp_name); // skipping this as not sure whether this is useful - all gets deallocated at exit anyways. - // } - // get_moose_classes().clear(); SHELLPTR->doQuit(); Msg::clearAllMsgs(); @@ -884,21 +735,15 @@ void finalize() } //! finalize() - /** Return list of available Finfo types. Place holder for static const to avoid static initialization issues. */ -const char ** getFinfoTypes() +const char **getFinfoTypes() { - static const char * finfoTypes[] = {"valueFinfo", - "srcFinfo", - "destFinfo", - "lookupFinfo", - "sharedFinfo", - "fieldElementFinfo", - 0 - }; + static const char *finfoTypes[] = { + "valueFinfo", "srcFinfo", "destFinfo", "lookupFinfo", + "sharedFinfo", "fieldElementFinfo", 0}; return finfoTypes; } @@ -918,20 +763,16 @@ const char ** getFinfoTypes() string getFieldType(string className, string fieldName) { string fieldType = ""; - const Cinfo * cinfo = Cinfo::find(className); - if (cinfo == NULL) - { - if (verbosity > 0) - { + const Cinfo *cinfo = Cinfo::find(className); + if (cinfo == NULL) { + if (verbosity > 0) { cerr << "Unknown class " << className << endl; } return fieldType; } - const Finfo * finfo = cinfo->findFinfo(fieldName); - if (finfo == NULL) - { - if (verbosity > 0) - { + const Finfo *finfo = cinfo->findFinfo(fieldName); + if (finfo == NULL) { + if (verbosity > 0) { cerr << "Unknown field " << fieldName << endl; } return fieldType; @@ -947,23 +788,19 @@ string getFieldType(string className, string fieldName) arguments. We populate `typeVec` with the individual type strings. */ -int parseFinfoType(string className, string finfoType, string fieldName, vector & typeVec) +int parseFinfoType(string className, string finfoType, string fieldName, vector &typeVec) { string typestring = getFieldType(className, fieldName); - if (typestring.empty()) - { + if (typestring.empty()) { return -1; } moose::tokenize(typestring, ",", typeVec); - if ((int)typeVec.size() > maxArgs) - { + if ((int)typeVec.size() > MAX_ARGS) { return -1; } - for (unsigned int ii = 0; ii < typeVec.size() ; ++ii) - { + for (unsigned int ii = 0; ii < typeVec.size(); ++ii) { char type_code = shortType(typeVec[ii]); - if (type_code == 0) - { + if (type_code == 0) { return -1; } } @@ -975,59 +812,42 @@ int parseFinfoType(string className, string finfoType, string fieldName, vector< */ vector getFieldNames(string className, string finfoType) { - vector ret; - const Cinfo * cinfo = Cinfo::find(className); - if (cinfo == NULL) - { + vector ret; + const Cinfo *cinfo = Cinfo::find(className); + if (cinfo == NULL) { cerr << "Invalid class name." << endl; return ret; } - // Finfo * (Cinfo:: * getFinfo)(unsigned int); // causes : warning: ISO C++ forbids taking the address of a bound member function to form a pointer to member function. - if (finfoType == "valueFinfo" || finfoType == "value") - { - for (unsigned int ii = 0; ii < cinfo->getNumValueFinfo(); ++ii) - { - Finfo * finfo = cinfo->getValueFinfo(ii); + + if (finfoType == "valueFinfo" || finfoType == "value") { + for (unsigned int ii = 0; ii < cinfo->getNumValueFinfo(); ++ii) { + Finfo *finfo = cinfo->getValueFinfo(ii); ret.push_back(finfo->name()); } - } - else if (finfoType == "srcFinfo" || finfoType == "src") - { - for (unsigned int ii = 0; ii < cinfo->getNumSrcFinfo(); ++ii) - { - Finfo * finfo = cinfo->getSrcFinfo(ii); + } else if (finfoType == "srcFinfo" || finfoType == "src") { + for (unsigned int ii = 0; ii < cinfo->getNumSrcFinfo(); ++ii) { + Finfo *finfo = cinfo->getSrcFinfo(ii); ret.push_back(finfo->name()); } - } - else if (finfoType == "destFinfo" || finfoType == "dest") - { - for (unsigned int ii = 0; ii < cinfo->getNumDestFinfo(); ++ii) - { - Finfo * finfo = cinfo->getDestFinfo(ii); + } else if (finfoType == "destFinfo" || finfoType == "dest") { + for (unsigned int ii = 0; ii < cinfo->getNumDestFinfo(); ++ii) { + Finfo *finfo = cinfo->getDestFinfo(ii); ret.push_back(finfo->name()); } - } - else if (finfoType == "lookupFinfo" || finfoType == "lookup") - { - for (unsigned int ii = 0; ii < cinfo->getNumLookupFinfo(); ++ii) - { - Finfo * finfo = cinfo->getLookupFinfo(ii); + } else if (finfoType == "lookupFinfo" || finfoType == "lookup") { + for (unsigned int ii = 0; ii < cinfo->getNumLookupFinfo(); ++ii) { + Finfo *finfo = cinfo->getLookupFinfo(ii); ret.push_back(finfo->name()); } - } - else if (finfoType == "sharedFinfo" || finfoType == "shared") - { - for (unsigned int ii = 0; ii < cinfo->getNumSrcFinfo(); ++ii) - { - Finfo * finfo = cinfo->getSrcFinfo(ii); + } else if (finfoType == "sharedFinfo" || finfoType == "shared") { + for (unsigned int ii = 0; ii < cinfo->getNumSrcFinfo(); ++ii) { + Finfo *finfo = cinfo->getSrcFinfo(ii); ret.push_back(finfo->name()); } - } - else if (finfoType == "fieldElementFinfo" || finfoType == "fieldElement") - { - for (unsigned int ii = 0; ii < cinfo->getNumFieldElementFinfo(); ++ii) - { - Finfo * finfo = cinfo->getFieldElementFinfo(ii); + } else if (finfoType == "fieldElementFinfo" || + finfoType == "fieldElement") { + for (unsigned int ii = 0; ii < cinfo->getNumFieldElementFinfo(); ++ii) { + Finfo *finfo = cinfo->getFieldElementFinfo(ii); ret.push_back(finfo->name()); } } @@ -1041,65 +861,47 @@ vector getFieldNames(string className, string finfoType) Populate the `fieldTypes` vector with corresponding C++ data type string (Finfo.type). */ -int getFieldDict(string className, string finfoType, - vector& fieldNames, vector&fieldTypes) +int getFieldDict(string className, string finfoType, vector &fieldNames, vector &fieldTypes) { - const Cinfo * cinfo = Cinfo::find(className); - if (cinfo == NULL) - { + const Cinfo *cinfo = Cinfo::find(className); + if (cinfo == NULL) { cerr << "Invalid class." << endl; return 0; } - if (finfoType == "valueFinfo" || finfoType == "value") - { - for (unsigned int ii = 0; ii < cinfo->getNumValueFinfo(); ++ii) - { - Finfo * finfo = cinfo->getValueFinfo(ii); + if (finfoType == "valueFinfo" || finfoType == "value") { + for (unsigned int ii = 0; ii < cinfo->getNumValueFinfo(); ++ii) { + Finfo *finfo = cinfo->getValueFinfo(ii); fieldNames.push_back(finfo->name()); fieldTypes.push_back(finfo->rttiType()); } - } - else if (finfoType == "srcFinfo" || finfoType == "src") - { - for (unsigned int ii = 0; ii < cinfo->getNumSrcFinfo(); ++ii) - { - Finfo * finfo = cinfo->getSrcFinfo(ii); + } else if (finfoType == "srcFinfo" || finfoType == "src") { + for (unsigned int ii = 0; ii < cinfo->getNumSrcFinfo(); ++ii) { + Finfo *finfo = cinfo->getSrcFinfo(ii); fieldNames.push_back(finfo->name()); fieldTypes.push_back(finfo->rttiType()); } - } - else if (finfoType == "destFinfo" || finfoType == "dest") - { - for (unsigned int ii = 0; ii < cinfo->getNumDestFinfo(); ++ii) - { - Finfo * finfo = cinfo->getDestFinfo(ii); + } else if (finfoType == "destFinfo" || finfoType == "dest") { + for (unsigned int ii = 0; ii < cinfo->getNumDestFinfo(); ++ii) { + Finfo *finfo = cinfo->getDestFinfo(ii); fieldNames.push_back(finfo->name()); fieldTypes.push_back(finfo->rttiType()); } - } - else if (finfoType == "lookupFinfo" || finfoType == "lookup") - { - for (unsigned int ii = 0; ii < cinfo->getNumLookupFinfo(); ++ii) - { - Finfo * finfo = cinfo->getLookupFinfo(ii); + } else if (finfoType == "lookupFinfo" || finfoType == "lookup") { + for (unsigned int ii = 0; ii < cinfo->getNumLookupFinfo(); ++ii) { + Finfo *finfo = cinfo->getLookupFinfo(ii); fieldNames.push_back(finfo->name()); fieldTypes.push_back(finfo->rttiType()); } - } - else if (finfoType == "sharedFinfo" || finfoType == "shared") - { - for (unsigned int ii = 0; ii < cinfo->getNumSrcFinfo(); ++ii) - { - Finfo * finfo = cinfo->getSrcFinfo(ii); + } else if (finfoType == "sharedFinfo" || finfoType == "shared") { + for (unsigned int ii = 0; ii < cinfo->getNumSrcFinfo(); ++ii) { + Finfo *finfo = cinfo->getSrcFinfo(ii); fieldNames.push_back(finfo->name()); fieldTypes.push_back(finfo->rttiType()); } - } - else if (finfoType == "fieldElementFinfo" || finfoType == "field" || finfoType == "fieldElement") - { - for (unsigned int ii = 0; ii < cinfo->getNumFieldElementFinfo(); ++ii) - { - Finfo * finfo = cinfo->getFieldElementFinfo(ii); + } else if (finfoType == "fieldElementFinfo" || finfoType == "field" || + finfoType == "fieldElement") { + for (unsigned int ii = 0; ii < cinfo->getNumFieldElementFinfo(); ++ii) { + Finfo *finfo = cinfo->getFieldElementFinfo(ii); fieldNames.push_back(finfo->name()); fieldTypes.push_back(finfo->rttiType()); } @@ -1107,32 +909,23 @@ int getFieldDict(string className, string finfoType, return 1; } -////////////////////////// -// Field Type definition -////////////////////////// -///////////////////////////////////////////////////// // ObjId functions. -///////////////////////////////////////////////////// - /** - Utility function to traverse python class hierarchy to reach closest base class. + Utility function to traverse python class hierarchy to reach closest base + class. Ideally we should go via mro */ -PyTypeObject * getBaseClass(PyObject * self) +PyTypeObject *getBaseClass(PyObject *self) { extern PyTypeObject ObjIdType; string basetype_str = ""; - PyTypeObject * base = NULL; - for (base = Py_TYPE(self); - base != &ObjIdType; base = base->tp_base) - { + PyTypeObject *base = NULL; + for (base = Py_TYPE(self); base != &ObjIdType; base = base->tp_base) { basetype_str = base->tp_name; size_t dot = basetype_str.find('.'); - basetype_str = basetype_str.substr(dot+1); - if (get_moose_classes().find(basetype_str) != - get_moose_classes().end()) - { + basetype_str = basetype_str.substr(dot + 1); + if (get_moose_classes().find(basetype_str) != get_moose_classes().end()) { return base; } } @@ -1142,46 +935,43 @@ PyTypeObject * getBaseClass(PyObject * self) //////////////////////////////////////////// // Module functions //////////////////////////////////////////// -PyDoc_STRVAR(moose_getFieldNames_documentation, - "getFieldNames(className, finfoType='valueFinfo') -> tuple\n" - "\n" - "Get a tuple containing the name of all the fields of `finfoType`\n" - "kind.\n" - "\n" - "Parameters\n" - "----------\n" - "className : string\n" - " Name of the class to look up.\n" - "finfoType : string\n" - " The kind of field " - " `valueFinfo` - " - " `srcFinfo` - " - " `destFinfo` - " - " `lookupFinfo`- " - " `fieldElementFinfo` - \n" - "\n" - "Returns\n" - "-------\n" - "tuple\n" - " Names of the fields of type `finfoType` in class `className`.\n" - ); - -PyObject * moose_getFieldNames(PyObject * dummy, PyObject * args) +PyDoc_STRVAR( + moose_getFieldNames_documentation, + "getFieldNames(className, finfoType='valueFinfo') -> tuple\n" + "\n" + "Get a tuple containing the name of all the fields of `finfoType`\n" + "kind.\n" + "\n" + "Parameters\n" + "----------\n" + "className : string\n" + " Name of the class to look up.\n" + "finfoType : string\n" + " The kind of field " + " `valueFinfo` - " + " `srcFinfo` - " + " `destFinfo` - " + " `lookupFinfo`- " + " `fieldElementFinfo` - \n" + "\n" + "Returns\n" + "-------\n" + "tuple\n" + " Names of the fields of type `finfoType` in class `className`.\n"); + +PyObject *moose_getFieldNames(PyObject *dummy, PyObject *args) { - char * className = NULL; + char *className = NULL; char _finfoType[] = "valueFinfo"; - char * finfoType = _finfoType; - if (!PyArg_ParseTuple(args, "s|s", &className, &finfoType)) - { + char *finfoType = _finfoType; + if (!PyArg_ParseTuple(args, "s|s", &className, &finfoType)) { return NULL; } - vector fieldNames = getFieldNames(className, finfoType); - PyObject * ret = PyTuple_New(fieldNames.size()); + vector fieldNames = getFieldNames(className, finfoType); + PyObject *ret = PyTuple_New(fieldNames.size()); - for (unsigned int ii = 0; ii < fieldNames.size(); ++ii) - { - if (PyTuple_SetItem(ret, ii, PyString_FromString(fieldNames[ii].c_str())) == -1) - { + for (unsigned int ii = 0; ii < fieldNames.size(); ++ii) { + if (PyTuple_SetItem(ret, ii, PyString_FromString(fieldNames[ii].c_str())) == -1) { Py_XDECREF(ret); return NULL; } @@ -1189,288 +979,261 @@ PyObject * moose_getFieldNames(PyObject * dummy, PyObject * args) return ret; } -PyDoc_STRVAR(moose_copy_documentation, - "copy(src, dest, name, n, toGlobal, copyExtMsg) -> bool\n" - "\n" - "Make copies of a moose object.\n" - "\n" - "Parameters\n" - "----------\n" - "src : vec, element or str\n" - " source object.\n" - "dest : vec, element or str\n" - " Destination object to copy into.\n" - "name : str\n" - " Name of the new object. If omitted, name of the original will be used.\n" - "n : int\n" - " Number of copies to make.\n" - "toGlobal : int\n" - " Relevant for parallel environments only. If false, the copies will\n" - " reside on local node, otherwise all nodes get the copies.\n" - "copyExtMsg : int\n" - " If true, messages to/from external objects are also copied.\n" - "\n" - "Returns\n" - "-------\n" - "vec\n" - " newly copied vec\n" - ); - -PyObject * moose_copy(PyObject * dummy, PyObject * args, PyObject * kwargs) +PyDoc_STRVAR( + moose_copy_documentation, + "copy(src, dest, name, n, toGlobal, copyExtMsg) -> bool\n" + "\n" + "Make copies of a moose object.\n" + "\n" + "Parameters\n" + "----------\n" + "src : vec, element or str\n" + " source object.\n" + "dest : vec, element or str\n" + " Destination object to copy into.\n" + "name : str\n" + " Name of the new object. If omitted, name of the original will be " + "used.\n" + "n : int\n" + " Number of copies to make.\n" + "toGlobal : int\n" + " Relevant for parallel environments only. If false, the copies will\n" + " reside on local node, otherwise all nodes get the copies.\n" + "copyExtMsg : int\n" + " If true, messages to/from external objects are also copied.\n" + "\n" + "Returns\n" + "-------\n" + "vec\n" + " newly copied vec\n"); + +PyObject *moose_copy(PyObject *dummy, PyObject *args, PyObject *kwargs) { - PyObject * src = NULL, * dest = NULL; - char * newName = NULL; - static const char * kwlist[] = {"src", "dest", "name", "n", "toGlobal", "copyExtMsg", NULL}; - unsigned int num=1, toGlobal=0, copyExtMsgs=0; - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|sIII", const_cast(kwlist), &src, &dest, &newName, &num, &toGlobal, ©ExtMsgs)) - { + PyObject *src = NULL, *dest = NULL; + char *newName = NULL; + static const char *kwlist[] = {"src", "dest", "name", "n", + "toGlobal", "copyExtMsg", NULL}; + unsigned int num = 1, toGlobal = 0, copyExtMsgs = 0; + if (!PyArg_ParseTupleAndKeywords( + args, kwargs, "OO|sIII", const_cast(kwlist), &src, &dest, &newName, &num, &toGlobal, ©ExtMsgs)) { return NULL; } Id _src; ObjId _dest; - if (PyObject_IsInstance(src, (PyObject*)&IdType)) - { - _src = ((_Id*)src)->id_; - } - else if (PyObject_IsInstance(src, (PyObject*)&ObjIdType)) - { - _src = ((_ObjId*)src)->oid_.id; - } - else if (PyString_Check(src)) - { + if (PyObject_IsInstance(src, (PyObject *)&IdType)) { + _src = ((_Id *)src)->id_; + } else if (PyObject_IsInstance(src, (PyObject *)&ObjIdType)) { + _src = ((_ObjId *)src)->oid_.id; + } else if (PyString_Check(src)) { _src = Id(PyString_AsString(src)); - } - else - { - PyErr_SetString(PyExc_TypeError, "Source must be instance of vec, element or string."); + } else { + PyErr_SetString(PyExc_TypeError, + "Source must be instance of vec, element or string."); return NULL; } - if (_src == Id()) - { + if (_src == Id()) { PyErr_SetString(PyExc_ValueError, "Cannot make copy of moose shell."); return NULL; } - if (PyObject_IsInstance(dest, (PyObject*)&IdType)) - { - _dest = ObjId(((_Id*)dest)->id_); - } - else if (PyObject_IsInstance(dest, (PyObject*)&ObjIdType)) - { - _dest = ((_ObjId*)dest)->oid_; - } - else if (PyString_Check(dest)) - { + if (PyObject_IsInstance(dest, (PyObject *)&IdType)) { + _dest = ObjId(((_Id *)dest)->id_); + } else if (PyObject_IsInstance(dest, (PyObject *)&ObjIdType)) { + _dest = ((_ObjId *)dest)->oid_; + } else if (PyString_Check(dest)) { _dest = ObjId(PyString_AsString(dest)); - } - else - { - PyErr_SetString(PyExc_TypeError, "destination must be instance of vec, element or string."); + } else { + PyErr_SetString( + PyExc_TypeError, + "destination must be instance of vec, element or string."); return NULL; } - if (!Id::isValid(_src)) - { + if (!Id::isValid(_src)) { RAISE_INVALID_ID(NULL, "moose_copy: invalid source Id."); - } - else if (_dest.bad()) - { + } else if (_dest.bad()) { RAISE_INVALID_ID(NULL, "moose_copy: invalid destination."); } string name; - if (newName == NULL) - { + if (newName == NULL) { // Use the original name if name is not specified. name = Field::get(ObjId(_src, 0), "name"); - } - else - { + } else { name = string(newName); } - _Id * tgt = PyObject_New(_Id, &IdType); + _Id *tgt = PyObject_New(_Id, &IdType); tgt->id_ = SHELLPTR->doCopy(_src, _dest, name, num, toGlobal, copyExtMsgs); - PyObject * ret = (PyObject*)tgt; + PyObject *ret = (PyObject *)tgt; return ret; } // Not sure what this function should return... ideally the Id of the // moved object - does it change though? -PyObject * moose_move(PyObject * dummy, PyObject * args) +PyObject *moose_move(PyObject *dummy, PyObject *args) { - PyObject * src, * dest; - if (!PyArg_ParseTuple(args, "OO:moose_move", &src, &dest)) - { + PyObject *src, *dest; + if (!PyArg_ParseTuple(args, "OO:moose_move", &src, &dest)) { return NULL; } Id _src; ObjId _dest; - if (PyObject_IsInstance(src, (PyObject*)&IdType)) - { - _src = ((_Id*)src)->id_; - } - else if (PyObject_IsInstance(src, (PyObject*)&ObjIdType)) - { - _src = ((_ObjId*)src)->oid_.id; - } - else if (PyString_Check(src)) - { + if (PyObject_IsInstance(src, (PyObject *)&IdType)) { + _src = ((_Id *)src)->id_; + } else if (PyObject_IsInstance(src, (PyObject *)&ObjIdType)) { + _src = ((_ObjId *)src)->oid_.id; + } else if (PyString_Check(src)) { _src = Id(PyString_AsString(src)); - } - else - { - PyErr_SetString(PyExc_TypeError, "Source must be instance of vec, element or string."); + } else { + PyErr_SetString(PyExc_TypeError, + "Source must be instance of vec, element or string."); return NULL; } - if (_src == Id()) - { + if (_src == Id()) { PyErr_SetString(PyExc_ValueError, "Cannot make move moose shell."); return NULL; } - if (PyObject_IsInstance(dest, (PyObject*)&IdType)) - { - _dest = ObjId(((_Id*)dest)->id_); - } - else if (PyObject_IsInstance(dest, (PyObject*)&ObjIdType)) - { - _dest = ((_ObjId*)dest)->oid_; - } - else if (PyString_Check(dest)) - { + if (PyObject_IsInstance(dest, (PyObject *)&IdType)) { + _dest = ObjId(((_Id *)dest)->id_); + } else if (PyObject_IsInstance(dest, (PyObject *)&ObjIdType)) { + _dest = ((_ObjId *)dest)->oid_; + } else if (PyString_Check(dest)) { _dest = ObjId(PyString_AsString(dest)); - } - else - { - PyErr_SetString(PyExc_TypeError, "destination must be instance of vec, element or string."); + } else { + PyErr_SetString( + PyExc_TypeError, + "destination must be instance of vec, element or string."); return NULL; } - if (!Id::isValid(_src)) - { + if (!Id::isValid(_src)) { RAISE_INVALID_ID(NULL, "moose_copy: invalid source Id."); - } - else if (_dest.bad()) - { + } else if (_dest.bad()) { RAISE_INVALID_ID(NULL, "moose_copy: invalid destination."); } SHELLPTR->doMove(_src, _dest); Py_RETURN_NONE; } -PyDoc_STRVAR(moose_delete_documentation, - "delete(obj)->None\n" - "\n" - "Delete the underlying moose object(s). This does not delete any of the\n" - "Python objects referring to this vec but does invalidate them. Any\n" - "attempt to access them will raise a ValueError.\n" - "\n" - "Parameters\n" - "----------\n" - "id : vec\n" - " vec of the object to be deleted.\n" - "\n" - "Returns\n" - "-------\n" - "None\n" - ); -PyObject * moose_delete(PyObject * dummy, PyObject * args) +PyDoc_STRVAR( + moose_delete_documentation, + "delete(obj)->None\n" + "\n" + "Delete the underlying moose object(s). This does not delete any of the\n" + "Python objects referring to this vec but does invalidate them. Any\n" + "attempt to access them will raise a ValueError.\n" + "\n" + "Parameters\n" + "----------\n" + "id : vec\n" + " vec of the object to be deleted.\n" + "\n" + "Returns\n" + "-------\n" + "None\n"); +PyObject *moose_delete(PyObject *dummy, PyObject *args) { - PyObject * obj; + PyObject *obj; bool isId_ = false; bool isObjId_ = false; - if (!PyArg_ParseTuple(args, "O:moose.delete", &obj)) - { + if (!PyArg_ParseTuple(args, "O:moose.delete", &obj)) { return NULL; } ObjId oid_; - if (PyObject_IsInstance(obj, (PyObject*)&IdType)) - { - oid_ = ((_Id*)obj)->id_; + if (PyObject_IsInstance(obj, (PyObject *)&IdType)) { + oid_ = ((_Id *)obj)->id_; isId_ = true; - } - else if (PyObject_IsInstance(obj, (PyObject*)&ObjIdType)) - { - oid_ = ((_ObjId*)obj)->oid_; + } else if (PyObject_IsInstance(obj, (PyObject *)&ObjIdType)) { + oid_ = ((_ObjId *)obj)->oid_; isObjId_ = true; - } - else if (PyString_Check(obj)) - { + } else if (PyString_Check(obj)) { oid_ = ObjId(PyString_AsString(obj)); - } - else - { + } else { PyErr_WarnEx(PyExc_RuntimeWarning, "Cannot delete moose shell.", 1); - Py_RETURN_NONE;; + Py_RETURN_NONE; + ; } - if (oid_ == ObjId()) - { + if (oid_ == ObjId()) { PyErr_WarnEx(PyExc_RuntimeWarning, "Cannot delete moose shell.", 1); Py_RETURN_NONE; } - if ( oid_.bad() ) - { + if (oid_.bad()) { RAISE_INVALID_ID(NULL, "moose_delete"); } deleteObjId(oid_); - if (isId_) - { - ((_Id*)obj)->id_ = Id(); + if (isId_) { + ((_Id *)obj)->id_ = Id(); } - if (isObjId_) - { - ((_ObjId*)obj)->oid_ = ObjId(0, BADINDEX, BADINDEX); + if (isObjId_) { + ((_ObjId *)obj)->oid_ = ObjId(0, BADINDEX, BADINDEX); } // SHELLPTR->doDelete(((_Id*)obj)->id_); Py_RETURN_NONE; } -PyDoc_STRVAR(moose_useClock_documentation, - "useClock(tick, path, fn)\n\n" - "schedule `fn` function of every object that matches `path` on tick no. `tick`.\n\n " - "Most commonly the function is 'process'. NOTE: unlike earlier versions, now autoschedule is not available. You have to call useClock for every element that should be updated during the simulation.\n\n " - "The sequence of clockticks with the same dt is according to their number. This is utilized for controlling the order of updates in various objects where it matters. The following convention should be observed when assigning clockticks to various components of a model:\n\n " - "Clock ticks 0-3 are for electrical (biophysical) components, 4 and 5 are for chemical kinetics, 6 and 7 are for lookup tables and stimulus, 8 and 9 are for recording tables.\n\n " - "Generally, `process` is the method to be assigned a clock tick. Notable exception is `init` method of Compartment class which is assigned tick 0.\n\n" - " - 0 : Compartment: `init`\n" - " - 1 : Compartment: `process`\n" - " - 2 : HHChannel and other channels: `process`\n" - " - 3 : CaConc : `process`\n" - " - 4,5 : Elements for chemical kinetics : `process`\n" - " - 6,7 : Lookup (tables), stimulus : `process`\n" - " - 8,9 : Tables for plotting : `process`\n" - " \n" - "Parameters\n" - "----------\n" - "tick : int\n" - " tick number on which the targets should be scheduled.\n" - "path : str\n" - " path of the target element(s). This can be a wildcard also.\n" - "fn : str\n" - " name of the function to be called on each tick. Commonly `process`.\n" - "\n" - "Examples\n" - "--------\n" - "In multi-compartmental neuron model a compartment's membrane potential (Vm) is dependent on its neighbours' membrane potential. Thus it must get the neighbour's present Vm before computing its own Vm in next time step. This ordering is achieved by scheduling the `init` function, which communicates membrane potential, on tick 0 and `process` function on tick 1.\n\n" - " >>> moose.useClock(0, '/model/compartment_1', 'init')\n" - " >>> moose.useClock(1, '/model/compartment_1', 'process')\n"); - -PyObject * moose_useClock(PyObject * dummy, PyObject * args) +PyDoc_STRVAR( + moose_useClock_documentation, + "useClock(tick, path, fn)\n\n" + "schedule `fn` function of every object that matches `path` on tick no. " + "`tick`.\n\n " + "Most commonly the function is 'process'. NOTE: unlike earlier versions, " + "now autoschedule is not available. You have to call useClock for every " + "element that should be updated during the simulation.\n\n " + "The sequence of clockticks with the same dt is according to their number. " + "This is utilized for controlling the order of updates in various objects " + "where it matters. The following convention should be observed when " + "assigning clockticks to various components of a model:\n\n " + "Clock ticks 0-3 are for electrical (biophysical) components, 4 and 5 are " + "for chemical kinetics, 6 and 7 are for lookup tables and stimulus, 8 and " + "9 are for recording tables.\n\n " + "Generally, `process` is the method to be assigned a clock tick. Notable " + "exception is `init` method of Compartment class which is assigned tick " + "0.\n\n" + " - 0 : Compartment: `init`\n" + " - 1 : Compartment: `process`\n" + " - 2 : HHChannel and other channels: `process`\n" + " - 3 : CaConc : `process`\n" + " - 4,5 : Elements for chemical kinetics : `process`\n" + " - 6,7 : Lookup (tables), stimulus : `process`\n" + " - 8,9 : Tables for plotting : `process`\n" + " \n" + "Parameters\n" + "----------\n" + "tick : int\n" + " tick number on which the targets should be scheduled.\n" + "path : str\n" + " path of the target element(s). This can be a wildcard also.\n" + "fn : str\n" + " name of the function to be called on each tick. Commonly " + "`process`.\n" + "\n" + "Examples\n" + "--------\n" + "In multi-compartmental neuron model a compartment's membrane potential " + "(Vm) is dependent on its neighbours' membrane potential. Thus it must get " + "the neighbour's present Vm before computing its own Vm in next time step. " + "This ordering is achieved by scheduling the `init` function, which " + "communicates membrane potential, on tick 0 and `process` function on tick " + "1.\n\n" + " >>> moose.useClock(0, '/model/compartment_1', 'init')\n" + " >>> moose.useClock(1, '/model/compartment_1', 'process')\n"); + +PyObject *moose_useClock(PyObject *dummy, PyObject *args) { - char * path, * field; + char *path, *field; unsigned int tick; - if(!PyArg_ParseTuple(args, "Iss:moose_useClock", &tick, &path, &field)) - { + if (!PyArg_ParseTuple(args, "Iss:moose_useClock", &tick, &path, &field)) { return NULL; } SHELLPTR->doUseClock(string(path), string(field), tick); Py_RETURN_NONE; } - PyDoc_STRVAR(moose_setClock_documentation, "setClock(tick, dt)\n" "\n" "set the ticking interval of `tick` to `dt`.\n" "\n" - "A tick with interval `dt` will call the functions scheduled on that tick every `dt` timestep.\n" + "A tick with interval `dt` will call the functions scheduled on " + "that tick every `dt` timestep.\n" "\n" "Parameters\n" "----------\n" @@ -1479,16 +1242,14 @@ PyDoc_STRVAR(moose_setClock_documentation, " dt : double\n" " ticking interval\n"); -PyObject * moose_setClock(PyObject * dummy, PyObject * args) +PyObject *moose_setClock(PyObject *dummy, PyObject *args) { unsigned int tick; double dt; - if(!PyArg_ParseTuple(args, "Id:moose_setClock", &tick, &dt)) - { + if (!PyArg_ParseTuple(args, "Id:moose_setClock", &tick, &dt)) { return NULL; } - if (dt < 0) - { + if (dt < 0) { PyErr_SetString(PyExc_ValueError, "dt must be positive."); return NULL; } @@ -1496,154 +1257,153 @@ PyObject * moose_setClock(PyObject * dummy, PyObject * args) Py_RETURN_NONE; } -PyDoc_STRVAR(moose_start_documentation, - "start(time, notify = False) -> None\n" - "\n" - "Run simulation for `t` time. Advances the simulator clock by `t`\n" - "time. If 'notify = True', a message is written to terminal whenever \n" - "10\% of simulation time is over. \n" - "\n" - "After setting up a simulation, YOU MUST CALL MOOSE.REINIT() before\n" - "CALLING MOOSE.START() TO EXECUTE THE SIMULATION. Otherwise, the\n" - "simulator behaviour will be undefined. Once moose.reinit() has been\n" - "called, you can call moose.start(t) as many time as you like. This\n" - "will continue the simulation from the last state for `t` time.\n" - "\n" - "Parameters\n" - "----------\n" - "t : float\n" - " duration of simulation.\n" - "notify: bool\n" - " default False. If True, notify user whenever 10\% of simultion \n" - " is over.\n" - "\n" - "Returns\n" - "--------\n" - " None\n" - "\n" - "See also\n" - "--------\n" - "moose.reinit : (Re)initialize simulation\n" - "\n" - ); -PyObject * moose_start(PyObject * dummy, PyObject * args ) +PyDoc_STRVAR( + moose_start_documentation, + "start(time, notify = False) -> None\n" + "\n" + "Run simulation for `t` time. Advances the simulator clock by `t`\n" + "time. If 'notify = True', a message is written to terminal whenever \n" + "10\% of simulation time is over. \n" + "\n" + "After setting up a simulation, YOU MUST CALL MOOSE.REINIT() before\n" + "CALLING MOOSE.START() TO EXECUTE THE SIMULATION. Otherwise, the\n" + "simulator behaviour will be undefined. Once moose.reinit() has been\n" + "called, you can call moose.start(t) as many time as you like. This\n" + "will continue the simulation from the last state for `t` time.\n" + "\n" + "Parameters\n" + "----------\n" + "t : float\n" + " duration of simulation.\n" + "notify: bool\n" + " default False. If True, notify user whenever 10\% of simultion \n" + " is over.\n" + "\n" + "Returns\n" + "--------\n" + " None\n" + "\n" + "See also\n" + "--------\n" + "moose.reinit : (Re)initialize simulation\n" + "\n"); +PyObject *moose_start(PyObject *dummy, PyObject *args) { double runtime = 0.0; bool notify = false; PyArg_ParseTuple(args, "d|I:moose_start", &runtime, ¬ify); - if (runtime <= 0.0) - { - PyErr_SetString(PyExc_ValueError, "simulation runtime must be positive."); + if (runtime <= 0.0) { + PyErr_SetString(PyExc_ValueError, + "simulation runtime must be positive."); return NULL; } - // This is from http://stackoverflow.com/questions/1641182/how-can-i-catch-a-ctrl-c-event-c + // This is from + // http://stackoverflow.com/questions/1641182/how-can-i-catch-a-ctrl-c-event-c struct sigaction sigHandler; sigHandler.sa_handler = handle_keyboard_interrupts; sigemptyset(&sigHandler.sa_mask); sigHandler.sa_flags = 0; sigaction(SIGINT, &sigHandler, NULL); - SHELLPTR->doStart( runtime, notify ); + SHELLPTR->doStart(runtime, notify); Py_RETURN_NONE; } -PyDoc_STRVAR(moose_reinit_documentation, - "reinit() -> None\n" - "\n" - "Reinitialize simulation.\n" - "\n" - "This function (re)initializes moose simulation. It must be called\n" - "before you start the simulation (see moose.start). If you want to\n" - "continue simulation after you have called moose.reinit() and\n" - "moose.start(), you must NOT call moose.reinit() again. Calling\n" - "moose.reinit() again will take the system back to initial setting\n" - "(like clear out all data recording tables, set state variables to\n" - "their initial values, etc.\n" - "\n"); -PyObject * moose_reinit(PyObject * dummy, PyObject * args) +PyDoc_STRVAR( + moose_reinit_documentation, + "reinit() -> None\n" + "\n" + "Reinitialize simulation.\n" + "\n" + "This function (re)initializes moose simulation. It must be called\n" + "before you start the simulation (see moose.start). If you want to\n" + "continue simulation after you have called moose.reinit() and\n" + "moose.start(), you must NOT call moose.reinit() again. Calling\n" + "moose.reinit() again will take the system back to initial setting\n" + "(like clear out all data recording tables, set state variables to\n" + "their initial values, etc.\n" + "\n"); +PyObject *moose_reinit(PyObject *dummy, PyObject *args) { // If environment variable MOOSE_TCP_STREAMER_ADDRESS is set then setup the // streamer. - string envSocketServer = moose::getEnv( "MOOSE_STREAMER_ADDRESS" ); - if(! envSocketServer.empty()) - { - LOG( moose::debug, "Environment variable MOOSE_STREAMER_ADDRESS: " << envSocketServer ); - if( envSocketServer.size() > 0 ) + string envSocketServer = moose::getEnv("MOOSE_STREAMER_ADDRESS"); + if (!envSocketServer.empty()) { + LOG(moose::debug, "Environment variable MOOSE_STREAMER_ADDRESS: " << envSocketServer); + if (envSocketServer.size() > 0) setupSocketStreamer(envSocketServer); } SHELLPTR->doReinit(); Py_RETURN_NONE; } -PyObject * moose_stop(PyObject * dummy, PyObject * args) +PyObject *moose_stop(PyObject *dummy, PyObject *args) { SHELLPTR->doStop(); Py_RETURN_NONE; } -PyObject * moose_isRunning(PyObject * dummy, PyObject * args) +PyObject *moose_isRunning(PyObject *dummy, PyObject *args) { return Py_BuildValue("i", SHELLPTR->isRunning()); } -PyObject * moose_exists(PyObject * dummy, PyObject * args) +PyObject *moose_exists(PyObject *dummy, PyObject *args) { - char * path; - if (!PyArg_ParseTuple(args, "s", &path)) - { + char *path; + if (!PyArg_ParseTuple(args, "s", &path)) { return NULL; } - return Py_BuildValue("i", Id(path) != Id() || string(path) == "/" || string(path) == "/root"); + return Py_BuildValue( + "i", + Id(path) != Id() || string(path) == "/" || string(path) == "/root"); } -PyDoc_STRVAR(moose_loadModelInternal_documentation, - "loadModelInternal(filename, modelpath, solverclass) -> vec\n" - "\n" - "Load model from a file to a specified path.\n" - "Note: This function should not be used by users. It is meants for developers. \n" - "Please see `moose.loadModel` function.\n" - "\n" - "Parameters\n" - "----------\n" - "filename : str\n" - " model description file.\n" - "modelpath : str\n" - " moose path for the top level element of the model to be created.\n" - "solverclass : str, optional\n" - " solver type to be used for simulating the model.\n" - "\n" - "Returns\n" - "-------\n" - "vec\n" - " loaded model container vec.\n" - ); - -PyObject * moose_loadModelInternal(PyObject * dummy, PyObject * args) +PyDoc_STRVAR( + moose_loadModelInternal_documentation, + "loadModelInternal(filename, modelpath, solverclass) -> vec\n" + "\n" + "Load model from a file to a specified path.\n" + "Note: This function should not be used by users. It is meants for " + "developers. \n" + "Please see `moose.loadModel` function.\n" + "\n" + "Parameters\n" + "----------\n" + "filename : str\n" + " model description file.\n" + "modelpath : str\n" + " moose path for the top level element of the model to be created.\n" + "solverclass : str, optional\n" + " solver type to be used for simulating the model.\n" + "\n" + "Returns\n" + "-------\n" + "vec\n" + " loaded model container vec.\n"); + +PyObject *moose_loadModelInternal(PyObject *dummy, PyObject *args) { - char * fname = NULL, * modelpath = NULL, * solverclass = NULL; + char *fname = NULL, *modelpath = NULL, *solverclass = NULL; - if(!PyArg_ParseTuple(args, "ss|s:moose_loadModelInternal", &fname, &modelpath, &solverclass)) - { + if (!PyArg_ParseTuple(args, "ss|s:moose_loadModelInternal", &fname, &modelpath, &solverclass)) { cout << "here in moose load"; return NULL; } - _Id * model = (_Id*)PyObject_New(_Id, &IdType); - if (!solverclass) - { + _Id *model = (_Id *)PyObject_New(_Id, &IdType); + if (!solverclass) { model->id_ = SHELLPTR->doLoadModel(string(fname), string(modelpath)); + } else { + model->id_ = SHELLPTR->doLoadModel( + string(fname), string(modelpath), string(solverclass)); } - else - { - model->id_ = SHELLPTR->doLoadModel(string(fname), string(modelpath), string(solverclass)); - } - if (model->id_ == Id()) - { + if (model->id_ == Id()) { Py_XDECREF(model); PyErr_SetString(PyExc_IOError, "could not load model"); return NULL; } - PyObject * ret = reinterpret_cast(model); + PyObject *ret = reinterpret_cast(model); return ret; } @@ -1706,52 +1466,39 @@ PyObject * moose_saveModel(PyObject * dummy, PyObject * args) } #endif -PyObject * moose_setCwe(PyObject * dummy, PyObject * args) +PyObject *moose_setCwe(PyObject *dummy, PyObject *args) { - PyObject * element = NULL; - char * path = NULL; + PyObject *element = NULL; + char *path = NULL; ObjId oid; - if (PyTuple_Size(args) == 0) - { + if (PyTuple_Size(args) == 0) { oid = Id("/"); - } - else if(PyArg_ParseTuple(args, "s:moose_setCwe", &path)) - { + } else if (PyArg_ParseTuple(args, "s:moose_setCwe", &path)) { oid = ObjId(string(path)); - } - else if (PyArg_ParseTuple(args, "O:moose_setCwe", &element)) - { + } else if (PyArg_ParseTuple(args, "O:moose_setCwe", &element)) { PyErr_Clear(); - if (PyObject_IsInstance(element, (PyObject*)&IdType)) - { - oid = (reinterpret_cast<_Id*>(element))->id_; - } - else if (PyObject_IsInstance(element, (PyObject*)&ObjIdType)) - { - oid = (reinterpret_cast<_ObjId*>(element))->oid_; - } - else - { - PyErr_SetString(PyExc_NameError, "setCwe: Argument must be an vec or element"); + if (PyObject_IsInstance(element, (PyObject *)&IdType)) { + oid = (reinterpret_cast<_Id *>(element))->id_; + } else if (PyObject_IsInstance(element, (PyObject *)&ObjIdType)) { + oid = (reinterpret_cast<_ObjId *>(element))->oid_; + } else { + PyErr_SetString(PyExc_NameError, + "setCwe: Argument must be an vec or element"); return NULL; } - } - else - { + } else { return NULL; } - if (oid.bad()) - { + if (oid.bad()) { RAISE_INVALID_ID(NULL, "moose_setCwe"); } SHELLPTR->setCwe(oid); Py_RETURN_NONE; } -PyObject * moose_getCwe(PyObject * dummy, PyObject * args) +PyObject *moose_getCwe(PyObject *dummy, PyObject *args) { - if (!PyArg_ParseTuple(args, ":moose_getCwe")) - { + if (!PyArg_ParseTuple(args, ":moose_getCwe")) { return NULL; } // _Id * cwe = (_Id*)PyObject_New(_Id, &IdType); @@ -1764,9 +1511,12 @@ PyObject * moose_getCwe(PyObject * dummy, PyObject * args) PyDoc_STRVAR(moose_connect_documentation, "connect(src, srcfield, destobj, destfield[,msgtype]) -> bool\n" "\n" - "Create a message between `src_field` on `src` object to `dest_field` on `dest` object.\n" - "This function is used mainly, to say, connect two entities, and to denote what kind of give-and-take relationship they share." - "It enables the 'destfield' (of the 'destobj') to acquire the data, from 'srcfield'(of the 'src')." + "Create a message between `src_field` on `src` object to " + "`dest_field` on `dest` object.\n" + "This function is used mainly, to say, connect two entities, and " + "to denote what kind of give-and-take relationship they share." + "It enables the 'destfield' (of the 'destobj') to acquire the " + "data, from 'srcfield'(of the 'src')." "\n" "Parameters\n" "----------\n" @@ -1806,146 +1556,123 @@ PyDoc_STRVAR(moose_connect_documentation, "\n" "See also\n" "--------\n" - "moose.connect\n" - ); + "moose.connect\n"); -PyObject * moose_connect(PyObject * dummy, PyObject * args) +PyObject *moose_connect(PyObject *dummy, PyObject *args) { - PyObject * srcPtr = NULL, * destPtr = NULL; - char * srcField = NULL, * destField = NULL, * msgType = NULL; + PyObject *srcPtr = NULL, *destPtr = NULL; + char *srcField = NULL, *destField = NULL, *msgType = NULL; static char default_msg_type[] = "Single"; - if(!PyArg_ParseTuple(args, "OsOs|s:moose_connect", &srcPtr, &srcField, &destPtr, &destField, &msgType)) - { + if (!PyArg_ParseTuple( + args, "OsOs|s:moose_connect", &srcPtr, &srcField, &destPtr, &destField, &msgType)) { return NULL; } - if (msgType == NULL) - { + if (msgType == NULL) { msgType = default_msg_type; } ObjId dest, src; - if (ObjId_SubtypeCheck(srcPtr)) - { - _ObjId * _src = reinterpret_cast<_ObjId*>(srcPtr); + if (ObjId_SubtypeCheck(srcPtr)) { + _ObjId *_src = reinterpret_cast<_ObjId *>(srcPtr); src = _src->oid_; - } - else if (Id_SubtypeCheck(srcPtr)) - { - _Id * _src = reinterpret_cast<_Id*>(srcPtr); + } else if (Id_SubtypeCheck(srcPtr)) { + _Id *_src = reinterpret_cast<_Id *>(srcPtr); src = ObjId(_src->id_); - } - else if (PyString_Check(srcPtr)) - { - char * _src = PyString_AsString(srcPtr); + } else if (PyString_Check(srcPtr)) { + char *_src = PyString_AsString(srcPtr); src = ObjId(string(_src)); - } - else - { - PyErr_SetString(PyExc_TypeError, "source does not resolve to an element."); + } else { + PyErr_SetString(PyExc_TypeError, + "source does not resolve to an element."); return NULL; } - if (ObjId_SubtypeCheck(destPtr)) - { - _ObjId * _dest = reinterpret_cast<_ObjId*>(destPtr); + if (ObjId_SubtypeCheck(destPtr)) { + _ObjId *_dest = reinterpret_cast<_ObjId *>(destPtr); dest = _dest->oid_; - } - else if (Id_SubtypeCheck(destPtr)) - { - _Id * _dest = reinterpret_cast<_Id*>(destPtr); + } else if (Id_SubtypeCheck(destPtr)) { + _Id *_dest = reinterpret_cast<_Id *>(destPtr); dest = ObjId(_dest->id_); - } - else if (PyString_Check(destPtr)) - { - char * _dest = PyString_AsString(destPtr); + } else if (PyString_Check(destPtr)) { + char *_dest = PyString_AsString(destPtr); dest = ObjId(string(_dest)); - } - else - { - PyErr_SetString(PyExc_TypeError, "target does not resolve to an element."); + } else { + PyErr_SetString(PyExc_TypeError, + "target does not resolve to an element."); return NULL; } - if (!Id::isValid(dest.id) || !Id::isValid(src.id)) - { + if (!Id::isValid(dest.id) || !Id::isValid(src.id)) { RAISE_INVALID_ID(NULL, "moose_connect"); } ObjId mid = SHELLPTR->doAddMsg(msgType, src, string(srcField), dest, string(destField)); - if ( mid.bad() ) - { - PyErr_SetString(PyExc_NameError, "check field names and type compatibility."); + if (mid.bad()) { + PyErr_SetString(PyExc_NameError, + "check field names and type compatibility."); return NULL; } return oid_to_element(mid); } - -PyDoc_STRVAR(moose_getFieldDict_documentation, - "getFieldDict(className, finfoType) -> dict\n" - "\n" - "Get dictionary of field names and types for specified class.\n" - "\n" - "Parameters\n" - "----------\n" - "className : str\n" - " MOOSE class to find the fields of.\n" - "finfoType : str (optional)\n" - " Finfo type of the fields to find. If empty or not specified, all\n" - " fields will be retrieved.\n" - "\n" - "Returns\n" - "-------\n" - "dict\n" - " field names and their types.\n" - "\n" - "Notes\n" - "-----\n" - " This behaviour is different from `getFieldNames` where only\n" - " `valueFinfo`s are returned when `finfoType` remains unspecified.\n" - "\n" - "Examples\n" - "--------\n" - "List all the source fields on class Neutral::\n" - "\n" - ">>> moose.getFieldDict('Neutral', 'srcFinfo')\n" - " {'childMsg': 'int'}\n" - "\n" - "\n"); -PyObject * moose_getFieldDict(PyObject * dummy, PyObject * args) +PyDoc_STRVAR( + moose_getFieldDict_documentation, + "getFieldDict(className, finfoType) -> dict\n" + "\n" + "Get dictionary of field names and types for specified class.\n" + "\n" + "Parameters\n" + "----------\n" + "className : str\n" + " MOOSE class to find the fields of.\n" + "finfoType : str (optional)\n" + " Finfo type of the fields to find. If empty or not specified, all\n" + " fields will be retrieved.\n" + "\n" + "Returns\n" + "-------\n" + "dict\n" + " field names and their types.\n" + "\n" + "Notes\n" + "-----\n" + " This behaviour is different from `getFieldNames` where only\n" + " `valueFinfo`s are returned when `finfoType` remains unspecified.\n" + "\n" + "Examples\n" + "--------\n" + "List all the source fields on class Neutral::\n" + "\n" + ">>> moose.getFieldDict('Neutral', 'srcFinfo')\n" + " {'childMsg': 'int'}\n" + "\n" + "\n"); +PyObject *moose_getFieldDict(PyObject *dummy, PyObject *args) { - char * className = NULL; - char * fieldType = NULL; - if (!PyArg_ParseTuple(args, "s|s:moose_getFieldDict", &className, &fieldType)) - { + char *className = NULL; + char *fieldType = NULL; + if (!PyArg_ParseTuple(args, "s|s:moose_getFieldDict", &className, &fieldType)) { return NULL; } - if (!className || (strlen(className) <= 0)) - { + if (!className || (strlen(className) <= 0)) { PyErr_SetString(PyExc_ValueError, "Expected non-empty class name."); return NULL; } Id classId = Id("/classes/" + string(className)); - if (classId == Id()) - { + if (classId == Id()) { string msg = string(className); msg += " not a valid MOOSE class."; PyErr_SetString(PyExc_NameError, msg.c_str()); return NULL; } - static const char * finfoTypes [] = {"valueFinfo", "lookupFinfo", "srcFinfo", "destFinfo", "sharedFinfo", NULL}; - vector fields, types; - if (fieldType && strlen(fieldType) > 0) - { - if (getFieldDict(className, string(fieldType), fields, types) == 0) - { + static const char *finfoTypes[] = {"valueFinfo", "lookupFinfo", "srcFinfo", + "destFinfo", "sharedFinfo", NULL}; + vector fields, types; + if (fieldType && strlen(fieldType) > 0) { + if (getFieldDict(className, string(fieldType), fields, types) == 0) { PyErr_SetString(PyExc_ValueError, "Invalid finfo type."); return NULL; } - } - else - { - for (const char ** ptr = finfoTypes; *ptr != NULL; ++ptr) - { - if (getFieldDict(className, string(*ptr), fields, types) == 0) - { + } else { + for (const char **ptr = finfoTypes; *ptr != NULL; ++ptr) { + if (getFieldDict(className, string(*ptr), fields, types) == 0) { string message = "No such finfo type: "; message += string(*ptr); PyErr_SetString(PyExc_ValueError, message.c_str()); @@ -1953,17 +1680,15 @@ PyObject * moose_getFieldDict(PyObject * dummy, PyObject * args) } } } - PyObject * ret = PyDict_New(); - if (!ret) - { - PyErr_SetString(PyExc_SystemError, "Could not allocate dictionary object."); + PyObject *ret = PyDict_New(); + if (!ret) { + PyErr_SetString(PyExc_SystemError, + "Could not allocate dictionary object."); return NULL; } - for (unsigned int ii = 0; ii < fields.size(); ++ ii) - { - PyObject * value = Py_BuildValue("s", types[ii].c_str()); - if (value == NULL || PyDict_SetItemString(ret, fields[ii].c_str(), value) == -1) - { + for (unsigned int ii = 0; ii < fields.size(); ++ii) { + PyObject *value = Py_BuildValue("s", types[ii].c_str()); + if (value == NULL || PyDict_SetItemString(ret, fields[ii].c_str(), value) == -1) { Py_XDECREF(ret); Py_XDECREF(value); return NULL; @@ -1972,164 +1697,126 @@ PyObject * moose_getFieldDict(PyObject * dummy, PyObject * args) return ret; } -PyObject * moose_getField(PyObject * dummy, PyObject * args) +PyObject *moose_getField(PyObject *dummy, PyObject *args) { - PyObject * pyobj; - const char * field; - const char * type; - if (!PyArg_ParseTuple(args, "Oss:moose_getfield", &pyobj, &field, &type)) - { + PyObject *pyobj; + const char *field; + const char *type; + if (!PyArg_ParseTuple(args, "Oss:moose_getfield", &pyobj, &field, &type)) { return NULL; } - if (!PyObject_IsInstance(pyobj, (PyObject*)&ObjIdType)) - { - PyErr_SetString(PyExc_TypeError, "moose.getField(element, fieldname, fieldtype): First argument must be an instance of element or its subclass"); + if (!PyObject_IsInstance(pyobj, (PyObject *)&ObjIdType)) { + PyErr_SetString(PyExc_TypeError, + "moose.getField(element, fieldname, fieldtype): First " + "argument must be an instance of element or its " + "subclass"); return NULL; } string fname(field), ftype(type); - ObjId oid = ((_ObjId*)pyobj)->oid_; - if (!Id::isValid(oid.id)) - { + ObjId oid = ((_ObjId *)pyobj)->oid_; + if (!Id::isValid(oid.id)) { RAISE_INVALID_ID(NULL, "moose_getField"); } // Let us do this version using brute force. Might be simpler than getattro. - if (ftype == "char") - { - char value =Field::get(oid, fname); + if (ftype == "char") { + char value = Field::get(oid, fname); return PyInt_FromLong(value); - } - else if (ftype == "double") - { + } else if (ftype == "double") { double value = Field::get(oid, fname); return PyFloat_FromDouble(value); - } - else if (ftype == "float") - { + } else if (ftype == "float") { float value = Field::get(oid, fname); return PyFloat_FromDouble(value); - } - else if (ftype == "int") - { + } else if (ftype == "int") { int value = Field::get(oid, fname); return PyInt_FromLong(value); - } - else if (ftype == "string") - { + } else if (ftype == "string") { string value = Field::get(oid, fname); return PyString_FromString(value.c_str()); - } - else if (ftype == "unsigned int" || ftype == "unsigned" || ftype == "uint") - { + } else if (ftype == "unsigned int" || ftype == "unsigned" || + ftype == "uint") { unsigned int value = Field::get(oid, fname); return PyInt_FromLong(value); - } - else if (ftype == "Id") - { - _Id * value = (_Id*)PyObject_New(_Id, &IdType); + } else if (ftype == "Id") { + _Id *value = (_Id *)PyObject_New(_Id, &IdType); value->id_ = Field::get(oid, fname); - return (PyObject*) value; - } - else if (ftype == "ObjId") - { - _ObjId * value = (_ObjId*)PyObject_New(_ObjId, &ObjIdType); + return (PyObject *)value; + } else if (ftype == "ObjId") { + _ObjId *value = (_ObjId *)PyObject_New(_ObjId, &ObjIdType); value->oid_ = Field::get(oid, fname); - return (PyObject*)value; - } - else if (ftype == "vector") - { - vector value = Field< vector < int > >::get(oid, fname); - PyObject * ret = PyTuple_New((Py_ssize_t)value.size()); - - for (unsigned int ii = 0; ii < value.size(); ++ ii ) - { - PyObject * entry = Py_BuildValue("i", value[ii]); - if (!entry || PyTuple_SetItem(ret, (Py_ssize_t)ii, entry)) - { + return (PyObject *)value; + } else if (ftype == "vector") { + vector value = Field>::get(oid, fname); + PyObject *ret = PyTuple_New((Py_ssize_t)value.size()); + + for (unsigned int ii = 0; ii < value.size(); ++ii) { + PyObject *entry = Py_BuildValue("i", value[ii]); + if (!entry || PyTuple_SetItem(ret, (Py_ssize_t)ii, entry)) { Py_XDECREF(ret); ret = NULL; break; } } return ret; - } - else if (ftype == "vector") - { - vector value = Field< vector < double > >::get(oid, fname); - PyObject * ret = PyTuple_New((Py_ssize_t)value.size()); + } else if (ftype == "vector") { + vector value = Field>::get(oid, fname); + PyObject *ret = PyTuple_New((Py_ssize_t)value.size()); - for (unsigned int ii = 0; ii < value.size(); ++ ii ) - { - PyObject * entry = Py_BuildValue("f", value[ii]); - if (!entry || PyTuple_SetItem(ret, (Py_ssize_t)ii, entry)) - { + for (unsigned int ii = 0; ii < value.size(); ++ii) { + PyObject *entry = Py_BuildValue("f", value[ii]); + if (!entry || PyTuple_SetItem(ret, (Py_ssize_t)ii, entry)) { Py_XDECREF(ret); ret = NULL; break; } } return ret; - } - else if (ftype == "vector") - { - vector value = Field< vector < float > >::get(oid, fname); - PyObject * ret = PyTuple_New((Py_ssize_t)value.size()); + } else if (ftype == "vector") { + vector value = Field>::get(oid, fname); + PyObject *ret = PyTuple_New((Py_ssize_t)value.size()); - for (unsigned int ii = 0; ii < value.size(); ++ ii ) - { - PyObject * entry = Py_BuildValue("f", value[ii]); - if (!entry || PyTuple_SetItem(ret, (Py_ssize_t)ii, entry)) - { + for (unsigned int ii = 0; ii < value.size(); ++ii) { + PyObject *entry = Py_BuildValue("f", value[ii]); + if (!entry || PyTuple_SetItem(ret, (Py_ssize_t)ii, entry)) { Py_XDECREF(ret); ret = NULL; break; } } return ret; - } - else if (ftype == "vector") - { - vector value = Field< vector < string > >::get(oid, fname); - PyObject * ret = PyTuple_New((Py_ssize_t)value.size()); + } else if (ftype == "vector") { + vector value = Field>::get(oid, fname); + PyObject *ret = PyTuple_New((Py_ssize_t)value.size()); - for (unsigned int ii = 0; ii < value.size(); ++ ii ) - { - PyObject * entry = Py_BuildValue("s", value[ii].c_str()); - if (!entry || PyTuple_SetItem(ret, (Py_ssize_t)ii, entry)) - { + for (unsigned int ii = 0; ii < value.size(); ++ii) { + PyObject *entry = Py_BuildValue("s", value[ii].c_str()); + if (!entry || PyTuple_SetItem(ret, (Py_ssize_t)ii, entry)) { Py_XDECREF(ret); return NULL; } } return ret; - } - else if (ftype == "vector") - { - vector value = Field< vector < Id > >::get(oid, fname); - PyObject * ret = PyTuple_New((Py_ssize_t)value.size()); + } else if (ftype == "vector") { + vector value = Field>::get(oid, fname); + PyObject *ret = PyTuple_New((Py_ssize_t)value.size()); - for (unsigned int ii = 0; ii < value.size(); ++ ii ) - { - _Id * entry = PyObject_New(_Id, &IdType); + for (unsigned int ii = 0; ii < value.size(); ++ii) { + _Id *entry = PyObject_New(_Id, &IdType); entry->id_ = value[ii]; - if (PyTuple_SetItem(ret, (Py_ssize_t)ii, (PyObject*)entry)) - { + if (PyTuple_SetItem(ret, (Py_ssize_t)ii, (PyObject *)entry)) { Py_XDECREF(ret); return NULL; } } return ret; - } - else if (ftype == "vector") - { - vector value = Field< vector < ObjId > >::get(oid, fname); - PyObject * ret = PyTuple_New((Py_ssize_t)value.size()); + } else if (ftype == "vector") { + vector value = Field>::get(oid, fname); + PyObject *ret = PyTuple_New((Py_ssize_t)value.size()); - for (unsigned int ii = 0; ii < value.size(); ++ ii ) - { - _ObjId * entry = PyObject_New(_ObjId, &ObjIdType); + for (unsigned int ii = 0; ii < value.size(); ++ii) { + _ObjId *entry = PyObject_New(_ObjId, &ObjIdType); entry->oid_ = value[ii]; - if (PyTuple_SetItem(ret, (Py_ssize_t)ii, (PyObject*)entry)) - { + if (PyTuple_SetItem(ret, (Py_ssize_t)ii, (PyObject *)entry)) { Py_XDECREF(ret); return NULL; } @@ -2140,132 +1827,133 @@ PyObject * moose_getField(PyObject * dummy, PyObject * args) return NULL; } -PyDoc_STRVAR(moose_seed_documentation, - "moose.seed(seedvalue) -> seed \n" - "\n" - "Reseed MOOSE random number generator.\n" - "\n" - "Parameters\n" - "----------\n" - "seed : int\n" - " Value to use for seeding. \n" - " All RNGs in moose except rand functions in moose.Function \n" - " expression use this seed.\n" - " By default (when this function is not called) seed is initializecd \n" - " to some random value using system random device (if available). \n" - " \n" - "\n" - " default: random number generated using system random device\n" - "\n" - "Returns\n" - "-------\n" - "None\n" - "\n" - "See also\n" - "--------\n" - "moose.rand() : get a pseudorandom number in the [0,1) interval.\n" - ); - -PyObject * moose_seed(PyObject * dummy, PyObject * args) +PyDoc_STRVAR( + moose_seed_documentation, + "moose.seed(seedvalue) -> seed \n" + "\n" + "Reseed MOOSE random number generator.\n" + "\n" + "Parameters\n" + "----------\n" + "seed : int\n" + " Value to use for seeding. \n" + " All RNGs in moose except rand functions in moose.Function \n" + " expression use this seed.\n" + " By default (when this function is not called) seed is initializecd \n" + " to some random value using system random device (if available). \n" + " \n" + "\n" + " default: random number generated using system random device\n" + "\n" + "Returns\n" + "-------\n" + "None\n" + "\n" + "See also\n" + "--------\n" + "moose.rand() : get a pseudorandom number in the [0,1) interval.\n"); + +PyObject *moose_seed(PyObject *dummy, PyObject *args) { long int seed = 0; - if (!PyArg_ParseTuple(args, "|l", &seed)) - { + if (!PyArg_ParseTuple(args, "|l", &seed)) { return NULL; } pymoose_mtseed_(seed); Py_RETURN_NONE; } -PyDoc_STRVAR(moose_rand_documentation, - "moose.rand() -> [0,1)\n" - "\n" - "Returns\n" - "-------\n" - "float in [0, 1) real interval generated by MT19937.\n" - "\n" - "See also\n" - "--------\n" - "moose.seed() : reseed the random number generator.\n" - "\n" - "Notes\n" - "-----\n" - "MOOSE does not automatically seed the random number generator. You\n" - "must explicitly call moose.seed() to create a new sequence of random\n" - "numbers each time.\n" - "\n"); - -PyObject * moose_rand(PyObject * dummy) +PyDoc_STRVAR( + moose_rand_documentation, + "moose.rand() -> [0,1)\n" + "\n" + "Returns\n" + "-------\n" + "float in [0, 1) real interval generated by MT19937.\n" + "\n" + "See also\n" + "--------\n" + "moose.seed() : reseed the random number generator.\n" + "\n" + "Notes\n" + "-----\n" + "MOOSE does not automatically seed the random number generator. You\n" + "must explicitly call moose.seed() to create a new sequence of random\n" + "numbers each time.\n" + "\n"); + +PyObject *moose_rand(PyObject *dummy) { return PyFloat_FromDouble(pymoose_mtrand_()); } -PyDoc_STRVAR(moose_wildcardFind_documentation, - "moose.wildcardFind(expression) -> tuple of melements.\n" - "\n" - "Find an object by wildcard.\n" - "\n" - "Parameters\n" - "----------\n" - "expression : str\n" - " MOOSE allows wildcard expressions of the form::\n" - "\n" - " {PATH}/{WILDCARD}[{CONDITION}]\n" - "\n" - " where {PATH} is valid path in the element tree.\n" - " `{WILDCARD}` can be `#` or `##`.\n" - "\n" - " `#` causes the search to be restricted to the children of the\n" - " element specified by {PATH}.\n" - "\n" - " `##` makes the search to recursively go through all the descendants\n" - " of the {PATH} element.\n" - " {CONDITION} can be::\n" - "\n" - " TYPE={CLASSNAME} : an element satisfies this condition if it is of\n" - " class {CLASSNAME}.\n" - " ISA={CLASSNAME} : alias for TYPE={CLASSNAME}\n" - " CLASS={CLASSNAME} : alias for TYPE={CLASSNAME}\n" - " FIELD({FIELDNAME}){OPERATOR}{VALUE} : compare field {FIELDNAME} with\n" - " {VALUE} by {OPERATOR} where {OPERATOR} is a comparison operator (=,\n" - " !=, >, <, >=, <=).\n" - "\n" - " For example, /mymodel/##[FIELD(Vm)>=-65] will return a list of all\n" - " the objects under /mymodel whose Vm field is >= -65.\n" - "\n" - "Returns\n" - "-------\n" - "tuple\n" - " all elements that match the wildcard.\n" - "\n"); - -PyObject * moose_wildcardFind(PyObject * dummy, PyObject * args) +PyDoc_STRVAR( + moose_wildcardFind_documentation, + "moose.wildcardFind(expression) -> tuple of melements.\n" + "\n" + "Find an object by wildcard.\n" + "\n" + "Parameters\n" + "----------\n" + "expression : str\n" + " MOOSE allows wildcard expressions of the form::\n" + "\n" + " {PATH}/{WILDCARD}[{CONDITION}]\n" + "\n" + " where {PATH} is valid path in the element tree.\n" + " `{WILDCARD}` can be `#` or `##`.\n" + "\n" + " `#` causes the search to be restricted to the children of the\n" + " element specified by {PATH}.\n" + "\n" + " `##` makes the search to recursively go through all the descendants\n" + " of the {PATH} element.\n" + " {CONDITION} can be::\n" + "\n" + " TYPE={CLASSNAME} : an element satisfies this condition if it is " + "of\n" + " class {CLASSNAME}.\n" + " ISA={CLASSNAME} : alias for TYPE={CLASSNAME}\n" + " CLASS={CLASSNAME} : alias for TYPE={CLASSNAME}\n" + " FIELD({FIELDNAME}){OPERATOR}{VALUE} : compare field {FIELDNAME} " + "with\n" + " {VALUE} by {OPERATOR} where {OPERATOR} is a comparison operator " + "(=,\n" + " !=, >, <, >=, <=).\n" + "\n" + " For example, /mymodel/##[FIELD(Vm)>=-65] will return a list of all\n" + " the objects under /mymodel whose Vm field is >= -65.\n" + "\n" + "Returns\n" + "-------\n" + "tuple\n" + " all elements that match the wildcard.\n" + "\n"); + +PyObject *moose_wildcardFind(PyObject *dummy, PyObject *args) { - vector objects; - char * wildcard_path = NULL; - if (!PyArg_ParseTuple(args, "s:moose.wildcardFind", &wildcard_path)) - { + vector objects; + char *wildcard_path = NULL; + if (!PyArg_ParseTuple(args, "s:moose.wildcardFind", &wildcard_path)) { return NULL; } wildcardFind(string(wildcard_path), objects); - PyObject * ret = PyTuple_New(objects.size()); - if (ret == NULL) - { - PyErr_SetString(PyExc_RuntimeError, "moose.wildcardFind: failed to allocate new tuple."); + PyObject *ret = PyTuple_New(objects.size()); + if (ret == NULL) { + PyErr_SetString(PyExc_RuntimeError, + "moose.wildcardFind: failed to allocate new tuple."); return NULL; } - for (unsigned int ii = 0; ii < objects.size(); ++ii) - { - PyObject * entry = oid_to_element(objects[ii]); - if (!entry) - { + for (unsigned int ii = 0; ii < objects.size(); ++ii) { + PyObject *entry = oid_to_element(objects[ii]); + if (!entry) { Py_XDECREF(ret); - PyErr_SetString(PyExc_RuntimeError, "moose.wildcardFind: failed to allocate new vec."); + PyErr_SetString(PyExc_RuntimeError, + "moose.wildcardFind: failed to allocate new vec."); return NULL; } - if (PyTuple_SetItem(ret, (Py_ssize_t)ii, entry)) - { + if (PyTuple_SetItem(ret, (Py_ssize_t)ii, entry)) { Py_XDECREF(entry); Py_XDECREF(ret); return NULL; @@ -2277,7 +1965,7 @@ PyObject * moose_wildcardFind(PyObject * dummy, PyObject * args) This should not be required or accessible to the user. Put here for debugging threading issue. */ -PyObject * moose_quit(PyObject * dummy) +PyObject *moose_quit(PyObject *dummy) { finalize(); cout << "Quitting MOOSE." << endl; @@ -2288,25 +1976,21 @@ PyObject * moose_quit(PyObject * dummy) Go through all elements under /classes and ask for defining a Python class for it. */ -int defineAllClasses(PyObject * module_dict) +int defineAllClasses(PyObject *module_dict) { - static vector classes(Field< vector >::get(ObjId("/classes"), - "children")); - for (unsigned ii = 0; ii < classes.size(); ++ii) - { - const string& className = classes[ii].element()->getName(); - if (verbosity > 0) - { + static vector classes( + Field>::get(ObjId("/classes"), "children")); + for (unsigned ii = 0; ii < classes.size(); ++ii) { + const string &className = classes[ii].element()->getName(); + if (verbosity > 0) { cout << "\nCreating " << className << endl; } - const Cinfo * cinfo = Cinfo::find(className); - if (!cinfo) - { + const Cinfo *cinfo = Cinfo::find(className); + if (!cinfo) { cerr << "Error: no cinfo found with name " << className << endl; return 0; } - if (!defineClass(module_dict, cinfo)) - { + if (!defineClass(module_dict, cinfo)) { return 0; } } @@ -2320,44 +2004,44 @@ int defineAllClasses(PyObject * module_dict) string. */ -PyDoc_STRVAR(moose_Class_documentation, - "*-----------------------------------------------------------------*\n" - "* This is Python generated documentation. *\n" - "* Use moose.doc('classname') to display builtin documentation for *\n" - "* class `classname`. *\n" - "* Use moose.doc('classname.fieldname') to display builtin *\n" - "* documentation for `field` in class `classname`. *\n" - "*-----------------------------------------------------------------*\n" - ); - -int defineLookupFinfos(const Cinfo * cinfo) +PyDoc_STRVAR( + moose_Class_documentation, + "*-----------------------------------------------------------------*\n" + "* This is Python generated documentation. *\n" + "* Use moose.doc('classname') to display builtin documentation for *\n" + "* class `classname`. *\n" + "* Use moose.doc('classname.fieldname') to display builtin *\n" + "* documentation for `field` in class `classname`. *\n" + "*-----------------------------------------------------------------*\n"); + +int defineLookupFinfos(const Cinfo *cinfo) { - const string & className = cinfo->name(); + const string &className = cinfo->name(); #ifndef NDEBUG - if (verbosity > 1) - { + if (verbosity > 1) { cout << "\tDefining lookupFields for " << className << endl; } #endif unsigned int num = cinfo->getNumLookupFinfo(); unsigned int currIndex = get_getsetdefs()[className].size(); - for (unsigned int ii = 0; ii < num; ++ii) - { - const string& name = const_cast(cinfo)->getLookupFinfo(ii)->name(); + for (unsigned int ii = 0; ii < num; ++ii) { + const string &name = const_cast(cinfo)->getLookupFinfo(ii)->name(); PyGetSetDef getset; get_getsetdefs()[className].push_back(getset); - get_getsetdefs()[className][currIndex].name = (char*)calloc(name.size() + 1, sizeof(char)); - strncpy(const_cast(get_getsetdefs()[className][currIndex].name) - , const_cast(name.c_str()), name.size()); - get_getsetdefs()[className][currIndex].doc = (char*) "Lookup field"; + get_getsetdefs()[className][currIndex].name = + (char *)calloc(name.size() + 1, sizeof(char)); + strncpy(const_cast(get_getsetdefs()[className][currIndex].name), + const_cast(name.c_str()), + name.size()); + get_getsetdefs()[className][currIndex].doc = (char *)"Lookup field"; get_getsetdefs()[className][currIndex].get = (getter)moose_ObjId_get_lookupField_attr; - PyObject * args = PyTuple_New(1); + PyObject *args = PyTuple_New(1); PyTuple_SetItem(args, 0, PyString_FromString(name.c_str())); - get_getsetdefs()[className][currIndex].closure = (void*)args; + get_getsetdefs()[className][currIndex].closure = (void *)args; #ifndef NDEBUG - if (verbosity > 1) - { - cout << "\tDefined lookupField " << get_getsetdefs()[className][currIndex].name << endl; + if (verbosity > 1) { + cout << "\tDefined lookupField " + << get_getsetdefs()[className][currIndex].name << endl; } #endif @@ -2366,37 +2050,33 @@ int defineLookupFinfos(const Cinfo * cinfo) return 1; } -int defineClass(PyObject * module_dict, const Cinfo * cinfo) +int defineClass(PyObject *module_dict, const Cinfo *cinfo) { - const string& className = cinfo->name(); - map ::iterator existing = - get_moose_classes().find(className); - if (existing != get_moose_classes().end()) - { + const string &className = cinfo->name(); + map::iterator existing = get_moose_classes().find(className); + if (existing != get_moose_classes().end()) { return 1; } - const Cinfo* base = cinfo->baseCinfo(); + const Cinfo *base = cinfo->baseCinfo(); #ifndef NDEBUG - if (verbosity > 1) - { - cout << "Defining class " << className << endl; //" with base=" << base->name() << endl; + if (verbosity > 1) { + cout << "Defining class " << className + << endl; //" with base=" << base->name() << endl; } #endif - if (base && !defineClass(module_dict, base)) - { + if (base && !defineClass(module_dict, base)) { return 0; } string str = "moose." + className; - PyTypeObject * new_class = - (PyTypeObject*)PyType_Type.tp_alloc(&PyType_Type, 0); + PyTypeObject *new_class = (PyTypeObject *)PyType_Type.tp_alloc(&PyType_Type, 0); // Python3 does not like it without heaptype: aborts on import // Fatal Python error: // type_traverse() called for non-heap type 'moose.Neutral' #ifdef PY3K new_class->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE; - PyHeapTypeObject* et = (PyHeapTypeObject*)new_class; + PyHeapTypeObject *et = (PyHeapTypeObject *)new_class; et->ht_name = PyUnicode_FromString(className.c_str()); #if PY_MINOR_VERSION >= 3 et->ht_qualname = PyUnicode_FromString(str.c_str()); @@ -2420,7 +2100,8 @@ int defineClass(PyObject * module_dict, const Cinfo * cinfo) (even when I unset Py_TPFLAGS_HAVE_GC) and fails the assertion in debug build of Python: - python: Objects/typeobject.c:2683: type_traverse: Assertion `type->tp_flags & Py_TPFLAGS_HEAPTYPE' failed. + python: Objects/typeobject.c:2683: type_traverse: Assertion `type->tp_flags + & Py_TPFLAGS_HEAPTYPE' failed. In released versions of Python there is a crash at Py_Finalize(). @@ -2434,37 +2115,33 @@ int defineClass(PyObject * module_dict, const Cinfo * cinfo) new_class->tp_name = strdup(str.c_str()); new_class->tp_doc = moose_Class_documentation; - //strncpy(new_class->tp_doc, moose_Class_documentation, strlen(moose_Class_documentation)); + // strncpy(new_class->tp_doc, moose_Class_documentation, + // strlen(moose_Class_documentation)); map::iterator base_iter = get_moose_classes().find(cinfo->getBaseClass()); - if (base_iter == get_moose_classes().end()) - { + if (base_iter == get_moose_classes().end()) { new_class->tp_base = &ObjIdType; - } - else - { + } else { new_class->tp_base = base_iter->second; } Py_INCREF(new_class->tp_base); // Define all the lookupFields - if (!defineLookupFinfos(cinfo)) - { + if (!defineLookupFinfos(cinfo)) { return 0; } // Define the destFields - if (!defineDestFinfos(cinfo)) - { + if (!defineDestFinfos(cinfo)) { return 0; } // Define the element fields - if (!defineElementFinfos(cinfo)) - { + if (!defineElementFinfos(cinfo)) { return 0; } // #ifndef NDEBUG // cout << "Get set defs:" << className << endl; - // for (unsigned int ii = 0; ii < get_getsetdefs()[className].size(); ++ii){ + // for (unsigned int ii = 0; ii < + // get_getsetdefs()[className].size(); ++ii){ // cout << ii; // if (get_getsetdefs()[className][ii].name != NULL){ // cout << ": " << get_getsetdefs()[className][ii].name; @@ -2485,81 +2162,78 @@ int defineClass(PyObject * module_dict, const Cinfo * cinfo) Cannot do this for HEAPTYPE ?? but pygobject.c does this in pygobject_register_class */ - if (PyType_Ready(new_class) < 0) - { - cerr << "Fatal error: Could not initialize class '" << className - << "'" << endl; + if (PyType_Ready(new_class) < 0) { + cerr << "Fatal error: Could not initialize class '" << className << "'" << endl; return 0; } - get_moose_classes().insert(pair (className, new_class)); + get_moose_classes().insert(pair(className, new_class)); Py_INCREF(new_class); #ifdef PY3K - PyDict_SetItemString(new_class->tp_dict, "__module__", PyUnicode_InternFromString("moose")); + PyDict_SetItemString( + new_class->tp_dict, "__module__", PyUnicode_InternFromString("moose")); #endif // string doc = const_cast(cinfo)->getDocs(); - // PyDict_SetItemString(new_class->tp_dict, "__doc__", PyString_FromString(" \0")); - // PyDict_SetItemString(module_dict, className.c_str(), (PyObject *)new_class); + // PyDict_SetItemString(new_class->tp_dict, "__doc__", PyString_FromString(" + // \0")); + // PyDict_SetItemString(module_dict, className.c_str(), (PyObject + // *)new_class); return 1; } -PyObject * moose_ObjId_get_destField_attr(PyObject * self, void * closure) +PyObject *moose_ObjId_get_destField_attr(PyObject *self, void *closure) { - if (!PyObject_IsInstance(self, (PyObject*)&ObjIdType)) - { - PyErr_SetString(PyExc_TypeError, "First argument must be an instance of element"); + if (!PyObject_IsInstance(self, (PyObject *)&ObjIdType)) { + PyErr_SetString(PyExc_TypeError, + "First argument must be an instance of element"); return NULL; } - _ObjId * obj = (_ObjId*)self; - if (!Id::isValid(obj->oid_.id)) - { + _ObjId *obj = (_ObjId *)self; + if (!Id::isValid(obj->oid_.id)) { RAISE_INVALID_ID(NULL, "moose_ObjId_get_destField_attr"); } - char * name = NULL; + char *name = NULL; if (!PyArg_ParseTuple((PyObject *)closure, "s:_get_destField: " "expected a string in getter closure.", - &name)) - { + &name)) { return NULL; } - PyObject * args = PyTuple_New(2); + PyObject *args = PyTuple_New(2); PyTuple_SetItem(args, 0, self); Py_INCREF(self); // compensate for reference stolen by PyTuple_SetItem PyTuple_SetItem(args, 1, PyString_FromString(name)); - _Field * ret = PyObject_New(_Field, &moose_DestField); - if (moose_DestField.tp_init((PyObject*)ret, args, NULL) != 0) - { - Py_XDECREF((PyObject*)ret); + _Field *ret = PyObject_New(_Field, &moose_DestField); + if (moose_DestField.tp_init((PyObject *)ret, args, NULL) != 0) { + Py_XDECREF((PyObject *)ret); ret = NULL; - PyErr_SetString(PyExc_RuntimeError, "moose_ObjId_get_destField_attr: failed to init DestField object"); + PyErr_SetString( + PyExc_RuntimeError, + "moose_ObjId_get_destField_attr: failed to init DestField object"); } Py_DECREF(args); - return (PyObject*)ret; + return (PyObject *)ret; } - -int defineDestFinfos(const Cinfo * cinfo) +int defineDestFinfos(const Cinfo *cinfo) { - const string& className = cinfo->name(); + const string &className = cinfo->name(); #ifndef NDEBUG - if (verbosity > 1) - { + if (verbosity > 1) { cout << "\tCreating destField attributes for " << className << endl; } #endif - vector & vec = get_getsetdefs()[className]; + vector &vec = get_getsetdefs()[className]; /* We do not know the final number of user-accessible destFinfos as we have to ignore the destFinfos starting with get/set. So use a vector instead of C array. */ size_t currIndex = vec.size(); - for (unsigned int ii = 0; ii < cinfo->getNumDestFinfo(); ++ii) - { - Finfo * destFinfo = const_cast(cinfo)->getDestFinfo(ii); - const string& name = destFinfo->name(); + for (unsigned int ii = 0; ii < cinfo->getNumDestFinfo(); ++ii) { + Finfo *destFinfo = const_cast(cinfo)->getDestFinfo(ii); + const string &name = destFinfo->name(); /* get_{xyz} and set_{xyz} are internal destFinfos for accessing valueFinfos. Ignore them. @@ -2568,39 +2242,39 @@ int defineDestFinfos(const Cinfo * cinfo) fields, we cannot separate them out. - Subha Fri Jan 31 16:43:51 IST 2014 - The policy changed in the past and hence the following were commented out. + The policy changed in the past and hence the following were commented + out. - Subha Tue May 26 00:25:28 EDT 2015 */ // if (name.find("get") == 0 || name.find("set") == 0){ // continue; // } - PyGetSetDef destFieldGetSet = {.name = (char*) name.c_str() - , .get=nullptr, .set=nullptr - , .doc= (char*) "Destination field" - , .closure=nullptr - }; + PyGetSetDef destFieldGetSet = {.name = (char *)name.c_str(), + .get = nullptr, + .set = nullptr, + .doc = (char *)"Destination field", + .closure = nullptr}; vec.push_back(destFieldGetSet); // Dilawar: // strncpy can not write to const char* especially with clang++. // Ref: https://docs.python.org/3/c-api/structures.html#c.PyGetSetDef - //vec[currIndex].name = (char*)calloc(name.size() + 1, sizeof(char)); - //strncpy(vec[currIndex].name, + // vec[currIndex].name = (char*)calloc(name.size() + 1, sizeof(char)); + // strncpy(vec[currIndex].name, // const_cast(name.c_str()), // name.size()); // vec[currIndex].doc = (char*) "Destination field"; vec[currIndex].get = (getter)moose_ObjId_get_destField_attr; PyObject *args = PyTuple_New(1); - if (!args || !vec[currIndex].name) - { + if (!args || !vec[currIndex].name) { cerr << "moosemodule.cpp: defineDestFinfos: allocation failed\n"; return 0; } PyTuple_SetItem(args, 0, PyString_FromString(name.c_str())); - vec[currIndex].closure = (void*)args; + vec[currIndex].closure = (void *)args; - //LOG( debug, "\tCreated destField " << vec[currIndex].name ); + // LOG( debug, "\tCreated destField " << vec[currIndex].name ); ++currIndex; } // ! for @@ -2619,116 +2293,113 @@ int defineDestFinfos(const Cinfo * cinfo) it in a map before returning. */ -PyObject * moose_ObjId_get_lookupField_attr(PyObject * self, - void * closure) +PyObject *moose_ObjId_get_lookupField_attr(PyObject *self, void *closure) { - if (!PyObject_IsInstance(self, (PyObject*)&ObjIdType)) - { + if (!PyObject_IsInstance(self, (PyObject *)&ObjIdType)) { PyErr_SetString(PyExc_TypeError, "First argument must be an instance of element"); return NULL; } - _ObjId * obj = (_ObjId*)self; - if (!Id::isValid(obj->oid_.id)) - { + _ObjId *obj = (_ObjId *)self; + if (!Id::isValid(obj->oid_.id)) { RAISE_INVALID_ID(NULL, "moose_ObjId_get_lookupField_attr"); } - char * name = NULL; + char *name = NULL; if (!PyArg_ParseTuple((PyObject *)closure, - "s:moose_ObjId_get_lookupField_attr: expected a string in getter closure.", - &name)) - { + "s:moose_ObjId_get_lookupField_attr: expected a " + "string in getter closure.", + &name)) { return NULL; } assert(name); /* Create a new instance of LookupField `name` and set it as * an attribute of the object self. Create the argument for * init method of LookupField. This will be (fieldname, self) */ - PyObject * args = PyTuple_New(2); + PyObject *args = PyTuple_New(2); PyTuple_SetItem(args, 0, self); Py_INCREF(self); // compensate for stolen ref PyTuple_SetItem(args, 1, PyString_FromString(name)); - _Field * ret = PyObject_New(_Field, &moose_LookupField); - if (moose_LookupField.tp_init((PyObject*)ret, args, NULL) != 0) - { - Py_XDECREF((PyObject*)ret); + _Field *ret = PyObject_New(_Field, &moose_LookupField); + if (moose_LookupField.tp_init((PyObject *)ret, args, NULL) != 0) { + Py_XDECREF((PyObject *)ret); ret = NULL; PyErr_SetString(PyExc_RuntimeError, - "moose_ObjId_get_lookupField_attr: failed to init LookupField object"); + "moose_ObjId_get_lookupField_attr: failed to init " + "LookupField object"); } Py_DECREF(args); - return (PyObject*)ret; + return (PyObject *)ret; } -PyObject * moose_ObjId_get_elementField_attr(PyObject * self, - void * closure) +PyObject *moose_ObjId_get_elementField_attr(PyObject *self, void *closure) { // if (!PyObject_IsInstance(self, (PyObject*)&ObjIdType)){ // PyErr_SetString(PyExc_TypeError, // "First argument must be an instance of element"); // return NULL; // } - _ObjId * obj = (_ObjId*)self; - if (!Id::isValid(obj->oid_.id)) - { + _ObjId *obj = (_ObjId *)self; + if (!Id::isValid(obj->oid_.id)) { RAISE_INVALID_ID(NULL, "moose_ObjId_get_elementField_attr"); } - char * name = NULL; + char *name = NULL; if (!PyArg_ParseTuple((PyObject *)closure, - "s:moose_ObjId_get_elementField_attr: expected a string in getter closure.", - &name)) - { + "s:moose_ObjId_get_elementField_attr: expected a " + "string in getter closure.", + &name)) { return NULL; } // Create a new instance of ElementField `name` and set it as // an attribute of the object `self`. // 1. Create the argument for init method of ElementField. This // will be (fieldname, self) - PyObject * args = PyTuple_New(2); + PyObject *args = PyTuple_New(2); PyTuple_SetItem(args, 0, self); Py_INCREF(self); // compensate for stolen ref PyTuple_SetItem(args, 1, PyString_FromString(name)); - _Field * ret = PyObject_New(_Field, &moose_ElementField); + _Field *ret = PyObject_New(_Field, &moose_ElementField); // 2. Now use this arg to actually create the element field. - if (moose_ElementField.tp_init((PyObject*)ret, args, NULL) != 0) - { - Py_DECREF((PyObject*)ret); + if (moose_ElementField.tp_init((PyObject *)ret, args, NULL) != 0) { + Py_DECREF((PyObject *)ret); ret = NULL; - PyErr_SetString(PyExc_RuntimeError, "moose_ObjId_get_elementField_attr: failed to init ElementField object"); + PyErr_SetString(PyExc_RuntimeError, + "moose_ObjId_get_elementField_attr: failed to init " + "ElementField object"); } Py_DECREF(args); - return (PyObject*)ret; + return (PyObject *)ret; } -int defineElementFinfos(const Cinfo * cinfo) +int defineElementFinfos(const Cinfo *cinfo) { - const string & className = cinfo->name(); + const string &className = cinfo->name(); #ifndef NDEBUG - if (verbosity > 1) - { + if (verbosity > 1) { cout << "\tDefining elementFields for " << className << endl; } #endif unsigned int num = cinfo->getNumFieldElementFinfo(); unsigned int currIndex = get_getsetdefs()[className].size(); - for (unsigned int ii = 0; ii < num; ++ii) - { - const string& name = const_cast(cinfo)->getFieldElementFinfo(ii)->name(); + for (unsigned int ii = 0; ii < num; ++ii) { + const string &name = + const_cast(cinfo)->getFieldElementFinfo(ii)->name(); PyGetSetDef getset; get_getsetdefs()[className].push_back(getset); - get_getsetdefs()[className][currIndex].name = (char*)calloc(name.size() + 1, sizeof(char)); - strncpy(const_cast(get_getsetdefs()[className][currIndex].name) - , const_cast(name.c_str()), name.size()); - get_getsetdefs()[className][currIndex].doc = (char*) "Element field"; + get_getsetdefs()[className][currIndex].name = + (char *)calloc(name.size() + 1, sizeof(char)); + strncpy(const_cast(get_getsetdefs()[className][currIndex].name), + const_cast(name.c_str()), + name.size()); + get_getsetdefs()[className][currIndex].doc = (char *)"Element field"; get_getsetdefs()[className][currIndex].get = (getter)moose_ObjId_get_elementField_attr; - PyObject * args = PyTuple_New(1); + PyObject *args = PyTuple_New(1); PyTuple_SetItem(args, 0, PyString_FromString(name.c_str())); - get_getsetdefs()[className][currIndex].closure = (void*)args; + get_getsetdefs()[className][currIndex].closure = (void *)args; #ifndef NDEBUG - if (verbosity > 1) - { - cout << "\tDefined elementField " << get_getsetdefs()[className][currIndex].name << endl; + if (verbosity > 1) { + cout << "\tDefined elementField " + << get_getsetdefs()[className][currIndex].name << endl; } #endif @@ -2737,162 +2408,172 @@ int defineElementFinfos(const Cinfo * cinfo) return 1; } -PyObject * oid_to_element(ObjId oid) +PyObject *oid_to_element(ObjId oid) { string classname = Field::get(oid, "className"); map::iterator it = get_moose_classes().find(classname); - if (it == get_moose_classes().end()) - { + if (it == get_moose_classes().end()) { return NULL; } - PyTypeObject * pyclass = it->second; - _ObjId * new_obj = PyObject_New(_ObjId, pyclass); + PyTypeObject *pyclass = it->second; + _ObjId *new_obj = PyObject_New(_ObjId, pyclass); new_obj->oid_ = oid; // Py_XINCREF(new_obj); // why? PyObject_New initializes refcnt to 1 - return (PyObject*)new_obj; + return (PyObject *)new_obj; } -PyDoc_STRVAR(moose_element_documentation, - "moose.element(arg) -> moose object\n" - "\n" - "Convert a path or an object to the appropriate builtin moose class\n" - "instance\n" - "\n" - "Parameters\n" - "----------\n" - "arg : str/vec/moose object\n" - " path of the moose element to be converted or another element (possibly\n" - " available as a superclass instance).\n" - "\n" - "Returns\n" - "-------\n" - "melement\n" - " MOOSE element (object) corresponding to the `arg` converted to write subclass.\n" - "\n"); -PyObject * moose_element(PyObject* dummy, PyObject * args) +PyDoc_STRVAR( + moose_element_documentation, + "moose.element(arg) -> moose object\n" + "\n" + "Convert a path or an object to the appropriate builtin moose class\n" + "instance\n" + "\n" + "Parameters\n" + "----------\n" + "arg : str/vec/moose object\n" + " path of the moose element to be converted or another element " + "(possibly\n" + " available as a superclass instance).\n" + "\n" + "Returns\n" + "-------\n" + "melement\n" + " MOOSE element (object) corresponding to the `arg` converted to write " + "subclass.\n" + "\n"); +PyObject *moose_element(PyObject *dummy, PyObject *args) { - char * path = NULL; - PyObject * obj = NULL; + char *path = NULL; + PyObject *obj = NULL; ObjId oid; unsigned nid = 0, did = 0, fidx = 0; Id id; unsigned int numData = 0; // Don't use s* here: See https://github.com/BhallaLab/moose-core/issues/397 - if (PyArg_ParseTuple(args, "s", &path)) - { + if (PyArg_ParseTuple(args, "s", &path)) { oid = ObjId(path); - if ( oid.bad() ) - { - PyErr_SetString(PyExc_ValueError - , (std::string("moose_element: '") + std::string(path) + std::string("' does not exist!")).c_str() - ); + if (oid.bad()) { + PyErr_SetString(PyExc_ValueError, + (std::string("moose_element: '") + std::string(path) + + std::string("' does not exist!")).c_str()); return NULL; } - PyObject * new_obj = oid_to_element(oid); - if (new_obj) - { + PyObject *new_obj = oid_to_element(oid); + if (new_obj) { return new_obj; } PyErr_SetString(PyExc_TypeError, "moose_element: unknown class"); return NULL; } PyErr_Clear(); - if (PyArg_ParseTuple(args, "I|II", &nid, &did, &fidx)) - { + if (PyArg_ParseTuple(args, "I|II", &nid, &did, &fidx)) { oid = ObjId(id, did, fidx); // Todo: test for validity - PyObject * new_obj = oid_to_element(oid); - if (!new_obj) - { - PyErr_SetString(PyExc_RuntimeError, "moose_element: not a moose class."); + PyObject *new_obj = oid_to_element(oid); + if (!new_obj) { + PyErr_SetString(PyExc_RuntimeError, + "moose_element: not a moose class."); } return new_obj; } PyErr_Clear(); - if (!PyArg_ParseTuple(args, "O|II", &obj, &did, &fidx)) - { - PyErr_SetString(PyExc_TypeError, "moose_element: argument must be a path or an existing element or an vec"); + if (!PyArg_ParseTuple(args, "O|II", &obj, &did, &fidx)) { + PyErr_SetString(PyExc_TypeError, + "moose_element: argument must be a path or an existing " + "element or an vec"); return NULL; } // PyErr_Clear(); - if (PyObject_IsInstance(obj, (PyObject*)&ObjIdType)) - { - oid = ((_ObjId*)obj)->oid_; - } - else if (PyObject_IsInstance(obj, (PyObject*)&IdType)) - { - oid = ObjId(((_Id*)obj)->id_, did, fidx); // TODO: check for validity - } - else if (ElementField_SubtypeCheck(obj)) - { - oid = ObjId(((_Id*)moose_ElementField_getId((_Field*)obj, NULL))->id_); - } - if (oid.bad()) - { - PyErr_SetString(PyExc_TypeError, "moose_element: cannot convert to moose element."); + if (PyObject_IsInstance(obj, (PyObject *)&ObjIdType)) { + oid = ((_ObjId *)obj)->oid_; + } else if (PyObject_IsInstance(obj, (PyObject *)&IdType)) { + oid = ObjId(((_Id *)obj)->id_, did, fidx); // TODO: check for validity + } else if (ElementField_SubtypeCheck(obj)) { + oid = ObjId(((_Id *)moose_ElementField_getId((_Field *)obj, NULL))->id_); + } + if (oid.bad()) { + PyErr_SetString(PyExc_TypeError, + "moose_element: cannot convert to moose element."); return NULL; } - PyObject * new_obj = oid_to_element(oid); - if (!new_obj) - { - PyErr_SetString(PyExc_RuntimeError, "moose_element: not a moose class."); + PyObject *new_obj = oid_to_element(oid); + if (!new_obj) { + PyErr_SetString(PyExc_RuntimeError, + "moose_element: not a moose class."); } return new_obj; } - ///////////////////////////////////////////////////////////////////// // Method definitions for MOOSE module ///////////////////////////////////////////////////////////////////// -static PyMethodDef MooseMethods[] = -{ - {"element", (PyCFunction)moose_element, METH_VARARGS, moose_element_documentation}, - {"getFieldNames", (PyCFunction)moose_getFieldNames, METH_VARARGS, moose_getFieldNames_documentation}, - {"copy", (PyCFunction)moose_copy, METH_VARARGS|METH_KEYWORDS, moose_copy_documentation}, - {"move", (PyCFunction)moose_move, METH_VARARGS, "Move a vec object to a destination."}, - {"delete", (PyCFunction)moose_delete, METH_VARARGS, moose_delete_documentation}, - {"useClock", (PyCFunction)moose_useClock, METH_VARARGS, moose_useClock_documentation}, - {"setClock", (PyCFunction)moose_setClock, METH_VARARGS, moose_setClock_documentation}, - {"start", (PyCFunction)moose_start, METH_VARARGS, moose_start_documentation}, - {"reinit", (PyCFunction)moose_reinit, METH_VARARGS, moose_reinit_documentation}, +static PyMethodDef MooseMethods[] = { + {"element", (PyCFunction)moose_element, + METH_VARARGS, moose_element_documentation}, + {"getFieldNames", (PyCFunction)moose_getFieldNames, + METH_VARARGS, moose_getFieldNames_documentation}, + {"copy", (PyCFunction)moose_copy, + METH_VARARGS | METH_KEYWORDS, moose_copy_documentation}, + {"move", (PyCFunction)moose_move, + METH_VARARGS, "Move a vec object to a destination."}, + {"delete", (PyCFunction)moose_delete, + METH_VARARGS, moose_delete_documentation}, + {"useClock", (PyCFunction)moose_useClock, + METH_VARARGS, moose_useClock_documentation}, + {"setClock", (PyCFunction)moose_setClock, + METH_VARARGS, moose_setClock_documentation}, + {"start", (PyCFunction)moose_start, + METH_VARARGS, moose_start_documentation}, + {"reinit", (PyCFunction)moose_reinit, + METH_VARARGS, moose_reinit_documentation}, {"stop", (PyCFunction)moose_stop, METH_VARARGS, "Stop simulation"}, - {"isRunning", (PyCFunction)moose_isRunning, METH_VARARGS, "True if the simulation is currently running."}, - {"exists", (PyCFunction)moose_exists, METH_VARARGS, "True if there is an object with specified path."}, - {"loadModelInternal", (PyCFunction)moose_loadModelInternal, METH_VARARGS, moose_loadModelInternal_documentation}, - //{"saveModel", (PyCFunction)moose_saveModel, METH_VARARGS, moose_saveModel_documentation}, - {"connect", (PyCFunction)moose_connect, METH_VARARGS, moose_connect_documentation}, - {"getCwe", (PyCFunction)moose_getCwe, METH_VARARGS, "Get the current working element. 'pwe' is an alias of this function."}, - {"setCwe", (PyCFunction)moose_setCwe, METH_VARARGS, "Set the current working element. 'ce' is an alias of this function"}, - {"getFieldDict", (PyCFunction)moose_getFieldDict, METH_VARARGS, moose_getFieldDict_documentation}, - { - "getField", (PyCFunction)moose_getField, METH_VARARGS, - "getField(element, field, fieldtype) -- Get specified field of specified type from object vec." - }, + {"isRunning", (PyCFunction)moose_isRunning, + METH_VARARGS, "True if the simulation is currently running."}, + {"exists", (PyCFunction)moose_exists, + METH_VARARGS, "True if there is an object with specified path."}, + {"loadModelInternal", (PyCFunction)moose_loadModelInternal, + METH_VARARGS, moose_loadModelInternal_documentation}, + //{"saveModel", (PyCFunction)moose_saveModel, METH_VARARGS, + // moose_saveModel_documentation}, + {"connect", (PyCFunction)moose_connect, + METH_VARARGS, moose_connect_documentation}, + {"getCwe", (PyCFunction)moose_getCwe, METH_VARARGS, + "Get the current working element. 'pwe' is an alias of this " + "function."}, + {"setCwe", (PyCFunction)moose_setCwe, METH_VARARGS, + "Set the current working element. 'ce' is an alias of this " + "function"}, + {"getFieldDict", (PyCFunction)moose_getFieldDict, + METH_VARARGS, moose_getFieldDict_documentation}, + {"getField", (PyCFunction)moose_getField, METH_VARARGS, + "getField(element, field, fieldtype) -- Get specified field of " + "specified " + "type from object vec."}, {"seed", (PyCFunction)moose_seed, METH_VARARGS, moose_seed_documentation}, {"rand", (PyCFunction)moose_rand, METH_NOARGS, moose_rand_documentation}, - {"wildcardFind", (PyCFunction)moose_wildcardFind, METH_VARARGS, moose_wildcardFind_documentation}, - { - "quit", (PyCFunction)moose_quit, METH_NOARGS, "Finalize MOOSE threads and quit MOOSE. This is made available for" - " debugging purpose only. It will automatically get called when moose" - " module is unloaded. End user should not use this function." - }, - - {NULL, NULL, 0, NULL} /* Sentinel */ + {"wildcardFind", (PyCFunction)moose_wildcardFind, + METH_VARARGS, moose_wildcardFind_documentation}, + {"quit", (PyCFunction)moose_quit, METH_NOARGS, + "Finalize MOOSE threads and quit MOOSE. This is made available for" + " debugging purpose only. It will automatically get called when " + "moose" + " module is unloaded. End user should not use this function."}, + {NULL, NULL, 0, NULL} /* Sentinel */ }; - - /////////////////////////////////////////////////////////// // module initialization /////////////////////////////////////////////////////////// -PyDoc_STRVAR(moose_module_documentation, - "MOOSE = Multiscale Object-Oriented Simulation Environment.\n" - "\n" - "Moose is the core of a modern software platform for the simulation\n" - "of neural systems ranging from subcellular components and\n" - "biochemical reactions to complex models of single neurons, large\n" - "networks, and systems-level processes."); +PyDoc_STRVAR( + moose_module_documentation, + "MOOSE = Multiscale Object-Oriented Simulation Environment.\n" + "\n" + "Moose is the core of a modern software platform for the simulation\n" + "of neural systems ranging from subcellular components and\n" + "biochemical reactions to complex models of single neurons, large\n" + "networks, and systems-level processes."); #ifdef PY3K @@ -2905,24 +2586,24 @@ int moose_traverse(PyObject *m, visitproc visit, void *arg) int moose_clear(PyObject *m) { Py_CLEAR(GETSTATE(m)->error); - // I did get a segmentation fault at exit (without running a reinit() or start()) after creating a compartment. After putting the finalize here it went away. But did not reoccur even after commenting it out. Will need closer debugging. + // I did get a segmentation fault at exit (without running a reinit() or + // start()) after creating a compartment. After putting the finalize here it + // went away. But did not reoccur even after commenting it out. Will need + // closer debugging. // - Subha 2012-08-18, 00:36 finalize(); return 0; } - -static struct PyModuleDef MooseModuleDef = -{ - PyModuleDef_HEAD_INIT, - "moose", /* m_name */ - moose_module_documentation, /* m_doc */ - sizeof(struct module_state), /* m_size */ - MooseMethods, /* m_methods */ - 0, /* m_reload */ - moose_traverse, /* m_traverse */ - moose_clear, /* m_clear */ - NULL /* m_free */ +static struct PyModuleDef MooseModuleDef = { + PyModuleDef_HEAD_INIT, "moose", /* m_name */ + moose_module_documentation, /* m_doc */ + sizeof(struct module_state), /* m_size */ + MooseMethods, /* m_methods */ + 0, /* m_reload */ + moose_traverse, /* m_traverse */ + moose_clear, /* m_clear */ + NULL /* m_free */ }; #define INITERROR return NULL @@ -2934,90 +2615,83 @@ static struct PyModuleDef MooseModuleDef = PyMODINIT_FUNC MODINIT(_moose) { - clock_t modinit_start = clock(); - - // Now initialize the module #ifdef PY3K - PyObject * moose_module = PyModule_Create(&MooseModuleDef); + PyObject *moose_module = PyModule_Create(&MooseModuleDef); #else - PyObject *moose_module = Py_InitModule3("_moose", - MooseMethods, - moose_module_documentation); + PyObject *moose_module = + Py_InitModule3("_moose", MooseMethods, moose_module_documentation); #endif - if (moose_module == NULL) - { + if (moose_module == NULL) { INITERROR; } - struct module_state * st = GETSTATE(moose_module); + struct module_state *st = GETSTATE(moose_module); char error[] = "moose.Error"; st->error = PyErr_NewException(error, NULL, NULL); - if (st->error == NULL) - { + if (st->error == NULL) { Py_XDECREF(moose_module); INITERROR; } int registered = Py_AtExit(&finalize); - if (registered != 0) - { + if (registered != 0) { cerr << "Failed to register finalize() to be called at exit. " << endl; } import_array(); // Add Id type - // Py_TYPE(&IdType) = &PyType_Type; // unnecessary - filled in by PyType_Ready + // Py_TYPE(&IdType) = &PyType_Type; // unnecessary - filled in by + // PyType_Ready IdType.tp_new = PyType_GenericNew; - if (PyType_Ready(&IdType) < 0) - { + if (PyType_Ready(&IdType) < 0) { PyErr_Print(); exit(-1); }; Py_INCREF(&IdType); - PyModule_AddObject(moose_module, "vec", (PyObject*)&IdType); + PyModule_AddObject(moose_module, "vec", (PyObject *)&IdType); // Add ObjId type - // Py_TYPE(&ObjIdType) = &PyType_Type; // unnecessary - filled in by PyType_Ready + // Py_TYPE(&ObjIdType) = &PyType_Type; // unnecessary - filled in by + // PyType_Ready ObjIdType.tp_new = PyType_GenericNew; - if (PyType_Ready(&ObjIdType) < 0) - { + if (PyType_Ready(&ObjIdType) < 0) { PyErr_Print(); exit(-1); }; Py_INCREF(&ObjIdType); - PyModule_AddObject(moose_module, "melement", (PyObject*)&ObjIdType); + PyModule_AddObject(moose_module, "melement", (PyObject *)&ObjIdType); // Add LookupField type - // Py_TYPE(&moose_LookupField) = &PyType_Type; // unnecessary - filled in by PyType_Ready + // Py_TYPE(&moose_LookupField) = &PyType_Type; // unnecessary - filled in + // by PyType_Ready // moose_LookupField.tp_new = PyType_GenericNew; - if (PyType_Ready(&moose_LookupField) < 0) - { + if (PyType_Ready(&moose_LookupField) < 0) { PyErr_Print(); exit(-1); } Py_INCREF(&moose_LookupField); - PyModule_AddObject(moose_module, "LookupField", (PyObject*)&moose_LookupField); + PyModule_AddObject(moose_module, "LookupField", (PyObject *)&moose_LookupField); - if (PyType_Ready(&moose_ElementField) < 0) - { + if (PyType_Ready(&moose_ElementField) < 0) { PyErr_Print(); exit(-1); } Py_INCREF(&moose_ElementField); - PyModule_AddObject(moose_module, "ElementField", (PyObject*)&moose_ElementField); + PyModule_AddObject(moose_module, "ElementField", (PyObject *)&moose_ElementField); // Add DestField type - // Py_TYPE(&moose_DestField) = &PyType_Type; // unnecessary - filled in by PyType_Ready + // Py_TYPE(&moose_DestField) = &PyType_Type; // unnecessary - filled in by + // PyType_Ready // moose_DestField.tp_flags = Py_TPFLAGS_DEFAULT; // moose_DestField.tp_call = moose_DestField_call; // moose_DestField.tp_doc = DestField_documentation; // moose_DestField.tp_new = PyType_GenericNew; - if (PyType_Ready(&moose_DestField) < 0) - { + if (PyType_Ready(&moose_DestField) < 0) { PyErr_Print(); exit(-1); } Py_INCREF(&moose_DestField); - PyModule_AddObject(moose_module, "DestField", (PyObject*)&moose_DestField); + PyModule_AddObject(moose_module, "DestField", (PyObject *)&moose_DestField); - // PyModule_AddIntConstant(moose_module, "SINGLETHREADED", isSingleThreaded); + // PyModule_AddIntConstant(moose_module, "SINGLETHREADED", + // isSingleThreaded); // PyModule_AddIntConstant(moose_module, "NUMCORES", numCores); // PyModule_AddIntConstant(moose_module, "NUMNODES", numNodes); // PyModule_AddIntConstant(moose_module, "NUMPTHREADS", numProcessThreads); @@ -3025,32 +2699,16 @@ PyMODINIT_FUNC MODINIT(_moose) PyModule_AddIntConstant(moose_module, "INFINITE", isInfinite); PyModule_AddStringConstant(moose_module, "__version__", SHELLPTR->doVersion().c_str()); PyModule_AddStringConstant(moose_module, "VERSION", SHELLPTR->doVersion().c_str()); - PyObject * module_dict = PyModule_GetDict(moose_module); - clock_t defclasses_start = clock(); - if (!defineAllClasses(module_dict)) - { + PyObject *module_dict = PyModule_GetDict(moose_module); + if (!defineAllClasses(module_dict)) { PyErr_Print(); exit(-1); } - for (map ::iterator ii = get_moose_classes().begin(); - ii != get_moose_classes().end(); ++ii) - { - PyModule_AddObject(moose_module, ii->first.c_str(), (PyObject*)(ii->second)); + for (map::iterator ii = get_moose_classes().begin(); + ii != get_moose_classes().end(); + ++ii) { + PyModule_AddObject(moose_module, ii->first.c_str(), (PyObject *)(ii->second)); } - - clock_t defclasses_end = clock(); - - LOG( moose::debug, "`Time to define moose classes:" - << (defclasses_end - defclasses_start) * 1.0 /CLOCKS_PER_SEC - ); - - //PyGILState_Release(gstate); - clock_t modinit_end = clock(); - - LOG( moose::debug, "`Time to initialize module:" - << (modinit_end - modinit_start) * 1.0 /CLOCKS_PER_SEC - ); - #ifdef PY3K return moose_module; #endif diff --git a/pymoose/moosemodule.h b/pymoose/moosemodule.h index 97e01705ac..2a97fc903d 100644 --- a/pymoose/moosemodule.h +++ b/pymoose/moosemodule.h @@ -33,11 +33,11 @@ PyMODINIT_FUNC PyInit_moose(); #define PyString_Check PyUnicode_Check #define PyString_FromString PyUnicode_FromString #define PyString_FromFormat PyUnicode_FromFormat -#define PyString_AsString(str) \ - PyBytes_AS_STRING(PyUnicode_AsEncodedString(str, "utf-8", "Error~")) -// Python 3 does not like global module state +#define PyString_AsString(str) PyBytes_AS_STRING(PyUnicode_AsEncodedString(str, "utf-8", "Error~")) #define GETSTATE(m) ((struct module_state*)PyModule_GetState(m)) + #else // Python 2 + PyMODINIT_FUNC init_moose(); static struct module_state _state; #define GETSTATE(m) (&_state) @@ -57,11 +57,11 @@ static struct module_state _state; // Minimum number of arguments for setting destFinfo - 1-st // the finfo name. -#define minArgs 1 +#define MIN_ARGS 1 // Arbitrarily setting maximum on variable argument list. Read: // http://www.swig.org/Doc1.3/Varargs.html to understand why -#define maxArgs 10 +#define MAX_ARGS 10 /////////////////////////////////// diff --git a/pymoose/pymooseinit.cpp b/pymoose/pymooseinit.cpp index 04f3f87a37..22a08bd7ad 100644 --- a/pymoose/pymooseinit.cpp +++ b/pymoose/pymooseinit.cpp @@ -29,27 +29,25 @@ unsigned int getNumCores() { auto numCores = std::thread::hardware_concurrency(); - if(0 == numCores) + if (0 == numCores) numCores = 1; return numCores; } ////////////////////////////////////////////////////////////////// -void checkChildren( Id parent, const string& info ) +void checkChildren(Id parent, const string &info) { - vector< Id > ret; - Neutral::children( parent.eref(), ret ); - cout << info << " checkChildren of " << - parent.element()->getName() << ": " << - ret.size() << " children\n"; - for ( vector< Id >::iterator i = ret.begin(); i != ret.end(); ++i ) - { + vector ret; + Neutral::children(parent.eref(), ret); + cout << info << " checkChildren of " << parent.element()->getName() << ": " + << ret.size() << " children\n"; + for (vector::iterator i = ret.begin(); i != ret.end(); ++i) { cout << i->element()->getName() << endl; } } -Id init( int argc, char** argv, bool& doUnitTests) +Id init(int argc, char **argv, bool &doUnitTests) { unsigned int numCores = getNumCores(); int numNodes = 1; @@ -59,46 +57,45 @@ Id init( int argc, char** argv, bool& doUnitTests) Cinfo::rebuildOpIndex(); #ifdef USE_MPI - MPI_Init( &argc, &argv ); - MPI_Comm_size( MPI_COMM_WORLD, &numNodes ); - MPI_Comm_rank( MPI_COMM_WORLD, &myNode ); + MPI_Init(&argc, &argv); + MPI_Comm_size(MPI_COMM_WORLD, &numNodes); + MPI_Comm_rank(MPI_COMM_WORLD, &myNode); #endif Id shellId; - Element* shelle = - new GlobalDataElement( shellId, Shell::initCinfo(), "root", 1 ); + Element *shelle = new GlobalDataElement(shellId, Shell::initCinfo(), "root", 1); Id clockId = Id::nextId(); - assert( clockId.value() == 1 ); + assert(clockId.value() == 1); Id classMasterId = Id::nextId(); Id postMasterId = Id::nextId(); - Shell* s = reinterpret_cast< Shell* >( shellId.eref().data() ); - s->setShellElement( shelle ); - s->setHardware( numCores, numNodes, myNode ); + Shell *s = reinterpret_cast(shellId.eref().data()); + s->setShellElement(shelle); + s->setHardware(numCores, numNodes, myNode); s->loadBalance(); /// Sets up the Elements that represent each class of Msg. unsigned int numMsg = Msg::initMsgManagers(); - new GlobalDataElement( clockId, Clock::initCinfo(), "clock", 1 ); - new GlobalDataElement( classMasterId, Neutral::initCinfo(), "classes", 1); - new GlobalDataElement( postMasterId, PostMaster::initCinfo(), "postmaster", 1 ); + new GlobalDataElement(clockId, Clock::initCinfo(), "clock", 1); + new GlobalDataElement(classMasterId, Neutral::initCinfo(), "classes", 1); + new GlobalDataElement(postMasterId, PostMaster::initCinfo(), "postmaster", 1); - assert ( shellId == Id() ); - assert( clockId == Id( 1 ) ); - assert( classMasterId == Id( 2 ) ); - assert( postMasterId == Id( 3 ) ); + assert(shellId == Id()); + assert(clockId == Id(1)); + assert(classMasterId == Id(2)); + assert(postMasterId == Id(3)); // s->connectMasterMsg(); - Shell::adopt( shellId, clockId, numMsg++ ); - Shell::adopt( shellId, classMasterId, numMsg++ ); - Shell::adopt( shellId, postMasterId, numMsg++ ); + Shell::adopt(shellId, clockId, numMsg++); + Shell::adopt(shellId, classMasterId, numMsg++); + Shell::adopt(shellId, postMasterId, numMsg++); - assert( numMsg == 10 ); // Must be the same on all nodes. + assert(numMsg == 10); // Must be the same on all nodes. - Cinfo::makeCinfoElements( classMasterId ); + Cinfo::makeCinfoElements(classMasterId); return shellId; } diff --git a/pymoose/vec.cpp b/pymoose/vec.cpp index c2ba9bd01c..b8838cc558 100644 --- a/pymoose/vec.cpp +++ b/pymoose/vec.cpp @@ -37,18 +37,19 @@ extern int verbosity; /////////////////////////////////////////////// // Python method lists for PyObject of Id /////////////////////////////////////////////// -PyDoc_STRVAR(moose_Id_delete_doc, - "vec.delete() -> None" - "\n" - "\nDelete the underlying moose object. This will invalidate all" - "\nreferences to this object and any attempt to access it will raise a" - "\nValueError." - "\n Example" - "\n--------" - "\n >>>iaf.delete()" - "\n >>>print iaf.path" - "\n \\ " - "\n"); +PyDoc_STRVAR( + moose_Id_delete_doc, + "vec.delete() -> None" + "\n" + "\nDelete the underlying moose object. This will invalidate all" + "\nreferences to this object and any attempt to access it will raise a" + "\nValueError." + "\n Example" + "\n--------" + "\n >>>iaf.delete()" + "\n >>>print iaf.path" + "\n \\ " + "\n"); PyDoc_STRVAR(moose_Id_setField_doc, "setField(fieldname, value_vector) -> None\n" @@ -61,7 +62,7 @@ PyDoc_STRVAR(moose_Id_setField_doc, " field to be set.\n" "value: sequence of values\n" " sequence of values corresponding to individual elements" - " under this vec.\n" + " under this vec.\n" "\n Example" "\n--------" "\n >>> iaf.setField('Vm', 20)" @@ -75,191 +76,179 @@ PyDoc_STRVAR(moose_Id_setField_doc, " This is an interface to SetGet::setVec" "\n"); -static PyMethodDef IdMethods[] = -{ +static PyMethodDef IdMethods[] = { // {"init", (PyCFunction)moose_Id_init, METH_VARARGS, // "Initialize a Id object."}, - { - "delete", (PyCFunction)moose_Id_delete, METH_NOARGS, - moose_Id_delete_doc - }, - { - "getValue", (PyCFunction)moose_Id_getValue, METH_NOARGS, - "Returns integer representation of the id of the element." - }, - { - "getPath", (PyCFunction)moose_Id_getPath, METH_NOARGS, - "Returns the path of this vec object." - }, - { - "getShape", (PyCFunction)moose_Id_getShape, METH_NOARGS, - "Returns the shape of the vec object as a tuple." - }, - { - "setField", (PyCFunction)moose_Id_setField, METH_VARARGS, - moose_Id_setField_doc - }, - {NULL, NULL, 0, NULL}, /* Sentinel */ + {"delete", (PyCFunction)moose_Id_delete, METH_NOARGS, moose_Id_delete_doc}, + {"getValue", (PyCFunction)moose_Id_getValue, + METH_NOARGS, "Returns integer representation of the id of the element."}, + {"getPath", (PyCFunction)moose_Id_getPath, + METH_NOARGS, "Returns the path of this vec object."}, + {"getShape", (PyCFunction)moose_Id_getShape, + METH_NOARGS, "Returns the shape of the vec object as a tuple."}, + {"setField", (PyCFunction)moose_Id_setField, + METH_VARARGS, moose_Id_setField_doc}, + {NULL, NULL, 0, NULL}, /* Sentinel */ }; -static PySequenceMethods IdSequenceMethods = -{ - (lenfunc)moose_Id_getLength, // sq_length - 0, //sq_concat - 0, //sq_repeat - (ssizeargfunc)moose_Id_getItem, //sq_item +static PySequenceMethods IdSequenceMethods = { + (lenfunc)moose_Id_getLength, // sq_length + 0, // sq_concat + 0, // sq_repeat + (ssizeargfunc)moose_Id_getItem, // sq_item #ifndef PY3K (ssizessizeargfunc)moose_Id_getSlice, // getslice #else 0, #endif - 0, //sq_ass_item - 0, // setslice + 0, // sq_ass_item + 0, // setslice (objobjproc)moose_Id_contains, // sq_contains - 0, // sq_inplace_concat - 0 // sq_inplace_repeat + 0, // sq_inplace_concat + 0 // sq_inplace_repeat }; -static PyMappingMethods IdMappingMethods = -{ - (lenfunc)moose_Id_getLength, //mp_length - (binaryfunc)moose_Id_subscript, // mp_subscript - 0 // mp_ass_subscript +static PyMappingMethods IdMappingMethods = {(lenfunc)moose_Id_getLength, // mp_length + (binaryfunc)moose_Id_subscript, // mp_subscript + 0 // mp_ass_subscript }; /////////////////////////////////////////////// // Type defs for PyObject of Id /////////////////////////////////////////////// -PyDoc_STRVAR(moose_Id_doc, - "An object uniquely identifying a moose array-element.\n" - "\n" - "array-elements are array-like objects which can have one or more" - " single-elements within them." - " vec can be traversed like a Python sequence and its each item is an" - " element identifying single-objects contained in the array element.\n" - "\n" - "you can create multiple references to the same MOOSE object in Python." - " As long as they have the same path/id value, they all point to" - " the same entity in MOOSE.\n" - "\n" - "Field access are vectorized. For example, if `comp` is a vec of" - " Compartments (of size 10), which has a field called `Vm` as membrane voltage, then" - " `comp.Vm` returns a" - " tuple containing the `Vm` value of all 10 single-elements in this" - " vec. There are a few special fields that are unique for vec and are not" - " vectorized. These are `path`, `name`, `value`, `shape` and `className`." - " There are two ways an vec can be initialized, \n" - "(1) create a new array element or \n" - "(2) create a reference to an existing object.\n" - "\n" - "\n Constructor:" - "\n" - "\n vec(self, path=path, n=size, g=isGlobal, dtype=className)" - "\n " - "\n " - "\n Parameters" - "\n ----------" - "\n path : str/vec/int " - "\n Path of an existing array element or for creating a new one. This has" - "\n the same format as unix file path: /{element1}/{element2} ... " - "\n If there is no object with the specified path, moose attempts to create " - "\n a new array element. For that to succeed everything until the last `/`" - "\n character must exist or an error is raised" - "\n" - "\n Alternatively, path can be vec or integer value of the Id of an" - "\n existing vec object. The new object will be another reference to" - "\n the existing object." - "\n " - "\n n : positive int" - "\n This is a positive integers specifying the size of the array element" - "\n to be created. Thus n=2 will create an vec with 2 elements." - "\n " - "\n g : int" - "\n Specify if this is a global or local element. Global elements are" - "\n shared between nodes in a computing cluster." - "\n " - "\n dtype: string" - "\n The vector will be of this moose-class." - "\n " - "\n Attributes:" - "\n -----------" - "\n path : str" - "\n Path of the vec. In moose vecs are organized in a tree structure" - " like unix file system and the paths follow the same convention." - "\n" - "\n name : str" - "\n Name of the vec." - "\n" - "\n value : int/long" - "\n Numeric identifier of the vec. This is unique within a single" - " execution. vec comparison is based on this value and its hash is also" - " this. So you can compare and sort vecs and use them as dict keys." - "\n" - "\n shape : tuple of ints" - "\n Dimensions of the vec (as shape in numpy.ndarray). Currently only" - " one-dimensional vecs are implemented." - "\n" - "\n className: str" - "\n The class of the moose object this vec contains. MOOSE core" - " implements its own class system independent of Python. pymoose creates" - " thin wrappers around them. This field provides you the moose class" - " name as defined in C++" - "\n" - "\n " - "\n Examples" - "\n ---------" - "\n >>> iaf = moose.vec('/iaf', n=10, dtype='IntFire')" - "\n >>> iaf.Vm = range(10)" - "\n >>> print iaf[5].Vm" - "\n 5.0" - "\n >>> print iaf.Vm" - "\n array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])" - ); - -PyTypeObject IdType = -{ - PyVarObject_HEAD_INIT(NULL, 0) /* tp_head */ - "moose.vec", /* tp_name */ - sizeof(_Id), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_compare */ - (reprfunc)moose_Id_repr, /* tp_repr */ - 0, /* tp_as_number */ - &IdSequenceMethods, /* tp_as_sequence */ - &IdMappingMethods, /* tp_as_mapping */ - (hashfunc)moose_Id_hash, /* tp_hash */ - 0, /* tp_call */ - (reprfunc)moose_Id_str, /* tp_str */ - (getattrofunc)moose_Id_getattro, /* tp_getattro */ - (setattrofunc)moose_Id_setattro, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, +PyDoc_STRVAR( moose_Id_doc, - 0, /* tp_traverse */ - 0, /* tp_clear */ - (richcmpfunc)moose_Id_richCompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - IdMethods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc) moose_Id_init, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ -}; + "An object uniquely identifying a moose array-element.\n" + "\n" + "array-elements are array-like objects which can have one or more" + " single-elements within them." + " vec can be traversed like a Python sequence and its each item is an" + " element identifying single-objects contained in the array element.\n" + "\n" + "you can create multiple references to the same MOOSE object in Python." + " As long as they have the same path/id value, they all point to" + " the same entity in MOOSE.\n" + "\n" + "Field access are vectorized. For example, if `comp` is a vec of" + " Compartments (of size 10), which has a field called `Vm` as membrane " + "voltage, then" + " `comp.Vm` returns a" + " tuple containing the `Vm` value of all 10 single-elements in this" + " vec. There are a few special fields that are unique for vec and are not" + " vectorized. These are `path`, `name`, `value`, `shape` and `className`." + " There are two ways an vec can be initialized, \n" + "(1) create a new array element or \n" + "(2) create a reference to an existing object.\n" + "\n" + "\n Constructor:" + "\n" + "\n vec(self, path=path, n=size, g=isGlobal, dtype=className)" + "\n " + "\n " + "\n Parameters" + "\n ----------" + "\n path : str/vec/int " + "\n Path of an existing array element or for creating a new one. " + "This has" + "\n the same format as unix file path: /{element1}/{element2} ... " + "\n If there is no object with the specified path, moose attempts " + "to create " + "\n a new array element. For that to succeed everything until the " + "last `/`" + "\n character must exist or an error is raised" + "\n" + "\n Alternatively, path can be vec or integer value of the Id of an" + "\n existing vec object. The new object will be another reference to" + "\n the existing object." + "\n " + "\n n : positive int" + "\n This is a positive integers specifying the size of the array " + "element" + "\n to be created. Thus n=2 will create an vec with 2 elements." + "\n " + "\n g : int" + "\n Specify if this is a global or local element. Global elements " + "are" + "\n shared between nodes in a computing cluster." + "\n " + "\n dtype: string" + "\n The vector will be of this moose-class." + "\n " + "\n Attributes:" + "\n -----------" + "\n path : str" + "\n Path of the vec. In moose vecs are organized in a tree structure" + " like unix file system and the paths follow the same convention." + "\n" + "\n name : str" + "\n Name of the vec." + "\n" + "\n value : int/long" + "\n Numeric identifier of the vec. This is unique within a single" + " execution. vec comparison is based on this value and its hash is also" + " this. So you can compare and sort vecs and use them as dict keys." + "\n" + "\n shape : tuple of ints" + "\n Dimensions of the vec (as shape in numpy.ndarray). Currently " + "only" + " one-dimensional vecs are implemented." + "\n" + "\n className: str" + "\n The class of the moose object this vec contains. MOOSE core" + " implements its own class system independent of Python. pymoose creates" + " thin wrappers around them. This field provides you the moose class" + " name as defined in C++" + "\n" + "\n " + "\n Examples" + "\n ---------" + "\n >>> iaf = moose.vec('/iaf', n=10, dtype='IntFire')" + "\n >>> iaf.Vm = range(10)" + "\n >>> print iaf[5].Vm" + "\n 5.0" + "\n >>> print iaf.Vm" + "\n array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])"); +PyTypeObject IdType = {PyVarObject_HEAD_INIT(NULL, 0) /* tp_head */ + "moose.vec", /* tp_name */ + sizeof(_Id), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + (reprfunc)moose_Id_repr, /* tp_repr */ + 0, /* tp_as_number */ + &IdSequenceMethods, /* tp_as_sequence */ + &IdMappingMethods, /* tp_as_mapping */ + (hashfunc)moose_Id_hash, /* tp_hash */ + 0, /* tp_call */ + (reprfunc)moose_Id_str, /* tp_str */ + (getattrofunc)moose_Id_getattro, /* tp_getattro */ + (setattrofunc)moose_Id_setattro, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, + moose_Id_doc, 0, /* tp_traverse */ + 0, /* tp_clear */ + (richcmpfunc)moose_Id_richCompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + IdMethods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)moose_Id_init, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ +}; extern PyTypeObject ObjIdType; @@ -267,27 +256,18 @@ extern PyTypeObject ObjIdType; // Id functions ////////////////////////////////////////////////// -PyObject* get_Id_attr(_Id * id, string attribute) +PyObject *get_Id_attr(_Id *id, string attribute) { - if (attribute == "path") - { + if (attribute == "path") { return moose_Id_getPath(id); - } - else if (attribute == "name") - { + } else if (attribute == "name") { string name = Field::get(id->id_, "name"); return Py_BuildValue("s", name.c_str()); - } - else if (attribute == "value") - { + } else if (attribute == "value") { return moose_Id_getValue(id); - } - else if (attribute == "shape") - { + } else if (attribute == "shape") { return moose_Id_getShape(id); - } - else if (attribute == "className") - { + } else if (attribute == "className") { // !NOTE: Subha: 2012-08-20 19:52:21 (+0530) - the second // !check is to catch a strange bug where the field passed // !to moose_Id_getattro is 'class' in stead of @@ -318,73 +298,57 @@ Id create_Id_from_path(string path, unsigned int numData, unsigned int isGlobal, string parent_path; string name; - string trimmed_path = moose::trim( path ); + string trimmed_path = moose::trim(path); size_t pos = trimmed_path.rfind("/"); - if (pos != string::npos) - { - name = trimmed_path.substr(pos+1); + if (pos != string::npos) { + name = trimmed_path.substr(pos + 1); parent_path = trimmed_path.substr(0, pos); - //cerr << "Parent path is : " << parent_path << endl; - } - else - { + // cerr << "Parent path is : " << parent_path << endl; + } else { name = trimmed_path; } // handle relative path - if (trimmed_path[0] != '/') - { + if (trimmed_path[0] != '/') { string current_path = SHELLPTR->getCwe().path(); - if (current_path != "/") - { + if (current_path != "/") { parent_path = current_path + "/" + parent_path; - } - else - { + } else { parent_path = current_path + parent_path; } - } - else if (parent_path.empty()) - { + } else if (parent_path.empty()) { parent_path = "/"; } ObjId parent_id(parent_path); - if (parent_id.bad() ) - { + if (parent_id.bad()) { string message = "Parent element does not exist: "; message += parent_path; PyErr_SetString(PyExc_ValueError, message.c_str()); return Id(); } - Id nId = SHELLPTR->doCreate(type, - parent_id, - string(name), - numData, - static_cast< NodePolicy >( isGlobal ) - ); - if (nId == Id() && trimmed_path != "/" && trimmed_path != "/root") - { + Id nId = SHELLPTR->doCreate( + type, parent_id, string(name), numData, static_cast(isGlobal)); + if (nId == Id() && trimmed_path != "/" && trimmed_path != "/root") { string message = "no such moose class : " + type; PyErr_SetString(PyExc_TypeError, message.c_str()); - } return nId; } -int moose_Id_init(_Id * self, PyObject * args, PyObject * kwargs) +int moose_Id_init(_Id *self, PyObject *args, PyObject *kwargs) { extern PyTypeObject IdType; - PyObject * src = NULL; + PyObject *src = NULL; unsigned int id = 0; unsigned int isGlobal = 0; - char * type = NULL; + char *type = NULL; // first try parsing the arguments as (path, size, classname) static char _path[] = "path"; static char _dtype[] = "dtype"; static char _size[] = "n"; static char _global[] = "g"; - static char * kwlist[] = {_path, _size, _global, _dtype, NULL}; - char * path = NULL; + static char *kwlist[] = {_path, _size, _global, _dtype, NULL}; + char *path = NULL; char _default_type[] = "Neutral"; // set it to 0 for unspecified value in case the user tries to // get an existing id without specifying it. If the user is @@ -399,18 +363,14 @@ int moose_Id_init(_Id * self, PyObject * args, PyObject * kwargs) [unsigned int isGlobal] - default: 0 [string type] - default: Neutral */ - if (PyArg_ParseTupleAndKeywords(args, kwargs, "s|IIs:moose_Id_init", - kwlist, &path, &numData, &isGlobal, - &type) - ) - { + if (PyArg_ParseTupleAndKeywords( + args, kwargs, "s|IIs:moose_Id_init", kwlist, &path, &numData, &isGlobal, &type)) { // Parsing args successful, if any error happens now, // different argument processing will not help. Return error string trimmed_path(path); trimmed_path = moose::trim(trimmed_path); size_t length = trimmed_path.length(); - if (length <= 0) - { + if (length <= 0) { PyErr_SetString(PyExc_ValueError, "moose_Id_init: path must be non-empty string."); return -1; @@ -418,11 +378,14 @@ int moose_Id_init(_Id * self, PyObject * args, PyObject * kwargs) self->id_ = Id(trimmed_path); // Return already existing object - if (self->id_ != Id() || trimmed_path == "/" || trimmed_path == "/root") - { - if ((numData > 0) && (numData != Field::get(self->id_, "numData"))) - { - PyErr_WarnEx(NULL, "moose_Id_init_: Length specified does not match that of existing object.", 1); + if (self->id_ != Id() || trimmed_path == "/" || + trimmed_path == "/root") { + if ((numData > 0) && + (numData != Field::get(self->id_, "numData"))) { + PyErr_WarnEx(NULL, + "moose_Id_init_: Length specified does not match " + "that of existing object.", + 1); } return 0; } @@ -432,8 +395,7 @@ int moose_Id_init(_Id * self, PyObject * args, PyObject * kwargs) numData = 1; self->id_ = create_Id_from_path(trimmed_path, numData, isGlobal, type); - if (self->id_ == Id() && PyErr_Occurred()) - { + if (self->id_ == Id() && PyErr_Occurred()) { return -1; } return 0; @@ -441,43 +403,38 @@ int moose_Id_init(_Id * self, PyObject * args, PyObject * kwargs) // The arguments could not be parsed as (path, dims, class), // try to parse it as an existing Id PyErr_Clear(); - if (PyArg_ParseTuple(args, "O:moose_Id_init", &src) && Id_SubtypeCheck(src)) - { - self->id_ = ((_Id*)src)->id_; + if (PyArg_ParseTuple(args, "O:moose_Id_init", &src) && Id_SubtypeCheck(src)) { + self->id_ = ((_Id *)src)->id_; return 0; } // The arguments could not be parsed as (path, dims, class), or Id // try to parse it as an existing ObjId PyErr_Clear(); - if (PyArg_ParseTuple(args, "O:moose_Id_init", &src) && ObjId_SubtypeCheck(src)) - { - self->id_ = ((_ObjId*)src)->oid_.id; + if (PyArg_ParseTuple(args, "O:moose_Id_init", &src) && ObjId_SubtypeCheck(src)) { + self->id_ = ((_ObjId *)src)->oid_.id; return 0; } // Next try to parse it as an integer value for an existing Id PyErr_Clear(); // clear the error from parsing error - if (PyArg_ParseTuple(args, "I:moose_Id_init", &id)) - { + if (PyArg_ParseTuple(args, "I:moose_Id_init", &id)) { self->id_ = Id(id); return 0; } return -1; -}// ! moose_Id_init +} // ! moose_Id_init -long moose_Id_hash(_Id * self) +long moose_Id_hash(_Id *self) { return self->id_.value(); // hash is the same as the Id value } - // This IS UGLY! Destroying one // ObjId will destroy the containing element and invalidate all // the other ObjId with the same Id. -PyObject * deleteObjId(ObjId oid) +PyObject *deleteObjId(ObjId oid) { #ifndef NDEBUG - if (verbosity > 1) - { + if (verbosity > 1) { cout << "Deleting ObjId " << oid << endl; } #endif @@ -485,15 +442,14 @@ PyObject * deleteObjId(ObjId oid) Py_RETURN_NONE; } -PyObject * moose_Id_delete(_Id * self) +PyObject *moose_Id_delete(_Id *self) { - if (self->id_ == Id()) - { - PyErr_SetString(PyExc_ValueError, "moose_Id_delete: cannot delete moose shell."); + if (self->id_ == Id()) { + PyErr_SetString(PyExc_ValueError, + "moose_Id_delete: cannot delete moose shell."); return NULL; } - if (!Id::isValid(self->id_)) - { + if (!Id::isValid(self->id_)) { RAISE_INVALID_ID(NULL, "moose_Id_delete"); } deleteObjId(self->id_); @@ -502,144 +458,122 @@ PyObject * moose_Id_delete(_Id * self) Py_RETURN_NONE; } -PyObject * moose_Id_repr(_Id * self) +PyObject *moose_Id_repr(_Id *self) { - if (!Id::isValid(self->id_)) - { + if (!Id::isValid(self->id_)) { RAISE_INVALID_ID(NULL, "moose_Id_repr"); } ostringstream repr; - repr << ""; return PyString_FromString(repr.str().c_str()); } // ! moose_Id_repr // The string representation is unused. repr is used everywhere. -PyObject * moose_Id_str(_Id * self) +PyObject *moose_Id_str(_Id *self) { - if (!Id::isValid(self->id_)) - { + if (!Id::isValid(self->id_)) { RAISE_INVALID_ID(NULL, "moose_Id_str"); } return PyString_FromFormat("", Field::get(self->id_, "className").c_str(), - self->id_.value(), self->id_.path().c_str()); + self->id_.value(), + self->id_.path().c_str()); } // ! moose_Id_str // 2011-03-23 15:09:19 (+0530) -PyObject* moose_Id_getValue(_Id * self) +PyObject *moose_Id_getValue(_Id *self) { unsigned int id = self->id_.value(); - PyObject * ret = Py_BuildValue("I", id); + PyObject *ret = Py_BuildValue("I", id); return ret; } /** Not to be redone. 2011-03-23 14:42:48 (+0530) */ -PyObject * moose_Id_getPath(_Id * self) +PyObject *moose_Id_getPath(_Id *self) { - if (!Id::isValid(self->id_)) - { + if (!Id::isValid(self->id_)) { RAISE_INVALID_ID(NULL, "moose_Id_getPath"); } string path = self->id_.path(); string default_end("[0]"); - if (moose::endswith(path, default_end)) - { + if (moose::endswith(path, default_end)) { path.erase(path.length() - default_end.length(), default_end.length()); } - PyObject * ret = Py_BuildValue("s", path.c_str()); + PyObject *ret = Py_BuildValue("s", path.c_str()); return ret; } //////////////////////////////////////////// // Subset of sequence protocol functions //////////////////////////////////////////// -Py_ssize_t moose_Id_getLength(_Id * self) +Py_ssize_t moose_Id_getLength(_Id *self) { - if (!Id::isValid(self->id_)) - { + if (!Id::isValid(self->id_)) { RAISE_INVALID_ID(-1, "moose_Id_getLength"); } - if (self->id_.element()->hasFields()) - { - return (Py_ssize_t)(Field < unsigned int >::get(self->id_, "numField")); - } - else - { + if (self->id_.element()->hasFields()) { + return (Py_ssize_t)(Field::get(self->id_, "numField")); + } else { return (Py_ssize_t)(self->id_.element()->numData()); } } -PyObject * moose_Id_getShape(_Id * self) +PyObject *moose_Id_getShape(_Id *self) { - if (!Id::isValid(self->id_)) - { + if (!Id::isValid(self->id_)) { RAISE_INVALID_ID(NULL, "moose_Id_getShape"); } unsigned int numData = 1; - if (self->id_.element()->hasFields()) - { - numData = Field < unsigned int >::get(self->id_, "numField"); - } - else - { - // numData = Field < unsigned int >::get(self->id_, "numData"); + if (self->id_.element()->hasFields()) { + numData = Field::get(self->id_, "numField"); + } else { + // numData = Field < unsigned int >::get(self->id_, + // "numData"); numData = self->id_.element()->numData(); } - PyObject * ret = PyTuple_New((Py_ssize_t)1); - if (PyTuple_SetItem(ret, (Py_ssize_t)0, Py_BuildValue("I", numData))) - { + PyObject *ret = PyTuple_New((Py_ssize_t)1); + if (PyTuple_SetItem(ret, (Py_ssize_t)0, Py_BuildValue("I", numData))) { Py_XDECREF(ret); - PyErr_SetString(PyExc_RuntimeError, "moose_Id_getShape: could not set tuple entry."); + PyErr_SetString(PyExc_RuntimeError, + "moose_Id_getShape: could not set tuple entry."); return NULL; } return ret; } -PyObject * moose_Id_getItem(_Id * self, Py_ssize_t index) +PyObject *moose_Id_getItem(_Id *self, Py_ssize_t index) { - if (!Id::isValid(self->id_)) - { + if (!Id::isValid(self->id_)) { RAISE_INVALID_ID(NULL, "moose_Id_getItem"); } - if (index < 0) - { + if (index < 0) { index += moose_Id_getLength(self); } - if ((index < 0) || (index >= moose_Id_getLength(self))) - { + if ((index < 0) || (index >= moose_Id_getLength(self))) { PyErr_SetString(PyExc_IndexError, "index out of bounds."); return NULL; } ObjId oid(self->id_.path()); // This is just to get the dataIndex of parent - if (self->id_.element()->hasFields()) - { + if (self->id_.element()->hasFields()) { // How to efficiently get the dataIndex of parent element // without creating ObjId from path? oid = ObjId(self->id_, oid.dataIndex, index); - } - else - { + } else { oid = ObjId(self->id_, index, 0); } return oid_to_element(oid); } -static PyObject* moose_Id_fillSlice(_Id *self, - Py_ssize_t start, - Py_ssize_t end, - Py_ssize_t step, - Py_ssize_t slicelength) +static PyObject *moose_Id_fillSlice(_Id *self, Py_ssize_t start, Py_ssize_t end, Py_ssize_t step, Py_ssize_t slicelength) { - PyObject * ret = PyTuple_New(slicelength); + PyObject *ret = PyTuple_New(slicelength); bool has_fields = self->id_.element()->hasFields(); - for (int ii = start; ii < end; ii += step) - { + for (int ii = start; ii < end; ii += step) { ObjId oid(self->id_.path()); PyObject *value; if (has_fields) @@ -647,44 +581,40 @@ static PyObject* moose_Id_fillSlice(_Id *self, else value = oid_to_element(ObjId(self->id_, ii)); - PyTuple_SET_ITEM(ret, (Py_ssize_t)(ii-start)/step, value); + PyTuple_SET_ITEM(ret, (Py_ssize_t)(ii - start) / step, value); } return ret; } #ifndef PY3K -PyObject * moose_Id_getSlice(_Id * self, Py_ssize_t start, Py_ssize_t end) +PyObject *moose_Id_getSlice(_Id *self, Py_ssize_t start, Py_ssize_t end) { - if (!Id::isValid(self->id_)) - { + if (!Id::isValid(self->id_)) { RAISE_INVALID_ID(NULL, "moose_Id_getSlice"); } Py_ssize_t len = moose_Id_getLength(self); - while (start < 0) - { + while (start < 0) { start += len; } - while (end < 0) - { + while (end < 0) { end += len; } - return moose_Id_fillSlice(self, start, end, 1, std::max(end - start, (Py_ssize_t) 0)); + return moose_Id_fillSlice(self, start, end, 1, std::max(end - start, (Py_ssize_t)0)); } #endif #ifdef PY3K -# define SLICE_OBJ(x) (x) +#define SLICE_OBJ(x) (x) #else -# define SLICE_OBJ(x) ((PySliceObject*)(x)) +#define SLICE_OBJ(x) ((PySliceObject *)(x)) #endif /////////////////////////////////////////////////// // Mapping protocol /////////////////////////////////////////////////// -PyObject * moose_Id_subscript(_Id * self, PyObject *op) +PyObject *moose_Id_subscript(_Id *self, PyObject *op) { - if (PySlice_Check(op)) - { + if (PySlice_Check(op)) { const Py_ssize_t len = moose_Id_getLength(self); Py_ssize_t start, stop, step, slicelength; @@ -694,95 +624,72 @@ PyObject * moose_Id_subscript(_Id * self, PyObject *op) return moose_Id_fillSlice(self, start, stop, step, slicelength); } - if (PyInt_Check(op) || PyLong_Check(op)) - { + if (PyInt_Check(op) || PyLong_Check(op)) { Py_ssize_t value = PyInt_AsLong(op); return moose_Id_getItem(self, value); - } - else - { + } else { PyErr_SetString(PyExc_KeyError, "moose_Id_subscript: invalid index."); return NULL; } } -PyObject * moose_Id_richCompare(_Id * self, PyObject * other, int op) +PyObject *moose_Id_richCompare(_Id *self, PyObject *other, int op) { extern PyTypeObject IdType; bool ret = false; - Id other_id = ((_Id*)other)->id_; - if (!self || !other) - { + Id other_id = ((_Id *)other)->id_; + if (!self || !other) { ret = false; - } - else if (!PyObject_IsInstance(other, (PyObject*)&IdType)) - { + } else if (!PyObject_IsInstance(other, (PyObject *)&IdType)) { ret = false; - } - else if (op == Py_EQ) - { + } else if (op == Py_EQ) { ret = self->id_ == other_id; - } - else if (op == Py_NE) - { + } else if (op == Py_NE) { ret = self->id_ != other_id; - } - else if (op == Py_LT) - { + } else if (op == Py_LT) { ret = self->id_ < other_id; - } - else if (op == Py_GT) - { + } else if (op == Py_GT) { ret = other_id < self->id_; - } - else if (op == Py_LE) - { + } else if (op == Py_LE) { ret = (self->id_ < other_id) || (self->id_ == other_id); - } - else if (op == Py_GE) - { + } else if (op == Py_GE) { ret = (other_id < self->id_) || (self->id_ == other_id); } - if (ret) - { + if (ret) { Py_RETURN_TRUE; } Py_RETURN_FALSE; } -int moose_Id_contains(_Id * self, PyObject * obj) +int moose_Id_contains(_Id *self, PyObject *obj) { extern PyTypeObject ObjIdType; int ret = 0; - if (ObjId_SubtypeCheck(obj)) - { - ret = (((_ObjId*)obj)->oid_.id == self->id_); + if (ObjId_SubtypeCheck(obj)) { + ret = (((_ObjId *)obj)->oid_.id == self->id_); } return ret; } -PyObject * moose_Id_getattro(_Id * self, PyObject * attr) +PyObject *moose_Id_getattro(_Id *self, PyObject *attr) { int new_attr = 0; - if (!Id::isValid(self->id_)) - { + if (!Id::isValid(self->id_)) { RAISE_INVALID_ID(NULL, "moose_Id_getattro"); } - char * field = PyString_AsString(attr); - PyObject * _ret = get_Id_attr(self, field); - if (_ret != NULL) - { + char *field = PyString_AsString(attr); + PyObject *_ret = get_Id_attr(self, field); + if (_ret != NULL) { return _ret; } string className = Field::get(self->id_, "className"); string type = getFieldType(className, string(field)); - if (type.empty()) - { - // Check if this field name is aliased and update fieldname and type if so. + if (type.empty()) { + // Check if this field name is aliased and update fieldname and type if + // so. map::const_iterator it = get_field_alias().find(string(field)); - if (it != get_field_alias().end()) - { - field = const_cast((it->second).c_str()); + if (it != get_field_alias().end()) { + field = const_cast((it->second).c_str()); type = getFieldType(Field::get(self->id_, "className"), it->second); // Update attr for next level (PyObject_GenericGetAttr) in case. // Py_XDECREF(attr); @@ -790,420 +697,345 @@ PyObject * moose_Id_getattro(_Id * self, PyObject * attr) new_attr = 1; } } - if (type.empty()) - { - return PyObject_GenericGetAttr((PyObject*)self, attr); + if (type.empty()) { + return PyObject_GenericGetAttr((PyObject *)self, attr); } char ftype = shortType(type); - if (!ftype) - { - return PyObject_GenericGetAttr((PyObject*)self, attr); + if (!ftype) { + return PyObject_GenericGetAttr((PyObject *)self, attr); } - switch (ftype) - { - case 'd': - { - vector < double > val; - Field< double >::getVec(self->id_, string(field), val); + switch (ftype) { + case 'd': { + vector val; + Field::getVec(self->id_, string(field), val); _ret = to_pytuple(&val, ftype); break; } - case 's': - { - vector < string > val; - Field< string >::getVec(self->id_, string(field), val); + case 's': { + vector val; + Field::getVec(self->id_, string(field), val); _ret = to_pytuple(&val, ftype); break; } - case 'l': - { - vector < long > val; - Field< long >::getVec(self->id_, string(field), val); + case 'l': { + vector val; + Field::getVec(self->id_, string(field), val); _ret = to_pytuple(&val, ftype); break; } - case 'x': - { - vector < Id > val; - Field< Id >::getVec(self->id_, string(field), val); + case 'x': { + vector val; + Field::getVec(self->id_, string(field), val); _ret = to_pytuple(&val, ftype); break; } - case 'y': - { - vector < ObjId > val; - Field< ObjId >::getVec(self->id_, string(field), val); + case 'y': { + vector val; + Field::getVec(self->id_, string(field), val); _ret = to_pytuple(&val, ftype); break; } - case 'i': - { - vector < int > val; - Field< int >::getVec(self->id_, string(field), val); + case 'i': { + vector val; + Field::getVec(self->id_, string(field), val); _ret = to_pytuple(&val, ftype); break; } - case 'I': - { - vector < unsigned int > val; - Field< unsigned int >::getVec(self->id_, string(field), val); + case 'I': { + vector val; + Field::getVec(self->id_, string(field), val); _ret = to_pytuple(&val, ftype); break; } - case 'k': - { - vector < unsigned long > val; - Field< unsigned long >::getVec(self->id_, string(field), val); + case 'k': { + vector val; + Field::getVec(self->id_, string(field), val); _ret = to_pytuple(&val, ftype); break; } - case 'f': - { - vector < float > val; - Field< float >::getVec(self->id_, string(field), val); + case 'f': { + vector val; + Field::getVec(self->id_, string(field), val); _ret = to_pytuple(&val, ftype); break; } - case 'b': - { + case 'b': { vector val; - Field< bool >::getVec(self->id_, string(field), val); + Field::getVec(self->id_, string(field), val); _ret = to_pytuple(&val, ftype); break; } - case 'c': - { - vector < char > val; - Field< char >::getVec(self->id_, string(field), val); + case 'c': { + vector val; + Field::getVec(self->id_, string(field), val); _ret = to_pytuple(&val, ftype); break; } - case 'h': - { - vector < short > val; - Field< short >::getVec(self->id_, string(field), val); + case 'h': { + vector val; + Field::getVec(self->id_, string(field), val); _ret = to_pytuple(&val, ftype); break; } - case 'z': - { - PyErr_SetString(PyExc_NotImplementedError, - "moose_Id_getattro: DataId handling not implemented yet."); + case 'z': { + PyErr_SetString( + PyExc_NotImplementedError, + "moose_Id_getattro: DataId handling not implemented yet."); _ret = NULL; break; } default: ostringstream msg; msg << "moose_Id_getattro: unhandled field type '" << type << "'\n" - << "This is a vec object. Perhaps you are trying to access the field in an" + << "This is a vec object. Perhaps you are trying to access the " + "field in an" << " element in this. Then use indexing to get the element first."; PyErr_SetString(PyExc_ValueError, msg.str().c_str()); _ret = NULL; break; } - if (new_attr) - { + if (new_attr) { Py_DECREF(attr); } return _ret; } -PyObject * moose_Id_setField(_Id * self, PyObject * args) +PyObject *moose_Id_setField(_Id *self, PyObject *args) { - if (!Id::isValid(self->id_)) - { + if (!Id::isValid(self->id_)) { RAISE_INVALID_ID(NULL, "moose_Id_setField"); } - PyObject * field = NULL; - PyObject * value = NULL; - if (!PyArg_ParseTuple(args, "OO:moose_Id_setField", &field, &value)) - { + PyObject *field = NULL; + PyObject *value = NULL; + if (!PyArg_ParseTuple(args, "OO:moose_Id_setField", &field, &value)) { return NULL; } - if (moose_Id_setattro(self, field, value) == -1) - { + if (moose_Id_setattro(self, field, value) == -1) { return NULL; } Py_RETURN_NONE; } -int moose_Id_setattro(_Id * self, PyObject * attr, PyObject *value) +int moose_Id_setattro(_Id *self, PyObject *attr, PyObject *value) { - if (!Id::isValid(self->id_)) - { + if (!Id::isValid(self->id_)) { RAISE_INVALID_ID(-1, "moose_Id_setattro"); } - char * fieldname = NULL; + char *fieldname = NULL; int ret = -1; - if (PyString_Check(attr)) - { + if (PyString_Check(attr)) { fieldname = PyString_AsString(attr); - } - else - { - PyErr_SetString(PyExc_TypeError, "moose_Id_setattro: Attribute name must be a string"); + } else { + PyErr_SetString(PyExc_TypeError, + "moose_Id_setattro: Attribute name must be a string"); return -1; } string moose_class = Field::get(self->id_, "className"); string fieldtype = getFieldType(moose_class, string(fieldname)); - if (fieldtype.length() == 0) - { + if (fieldtype.length() == 0) { // If it is instance of a MOOSE Id then throw // error (to avoid silently creating new attributes due to // typos). Otherwise, it must have been subclassed in // Python. Then we allow normal Pythonic behaviour and // consider such mistakes user's responsibility. - string className = ((PyTypeObject*)PyObject_Type((PyObject*)self))->tp_name; - if (className != "vec") - { + string className = ((PyTypeObject *)PyObject_Type((PyObject *)self))->tp_name; + if (className != "vec") { Py_INCREF(attr); - ret = PyObject_GenericSetAttr((PyObject*)self, attr, value); + ret = PyObject_GenericSetAttr((PyObject *)self, attr, value); Py_XDECREF(attr); return ret; } ostringstream msg; - msg << "moose_Id_setattro: '" << moose_class << "' class has no field '" << fieldname << "'" << endl; + msg << "moose_Id_setattro: '" << moose_class << "' class has no field '" + << fieldname << "'" << endl; PyErr_SetString(PyExc_AttributeError, msg.str().c_str()); return -1; } char ftype = shortType(fieldtype); Py_ssize_t length = moose_Id_getLength(self); bool is_seq = true; - if (!PySequence_Check(value)) - { + if (!PySequence_Check(value)) { is_seq = false; - } - else if (length != PySequence_Length(value)) - { + } else if (length != PySequence_Length(value)) { PyErr_SetString(PyExc_IndexError, - "moose_Id_setattro: length of the sequence on the right hand side does not match Id size."); + "moose_Id_setattro: length of the sequence on the " + "right hand side does not match Id size."); return -1; } - switch(ftype) - { - case 'd': //SET_VECFIELD(double, d) + switch (ftype) { + case 'd': // SET_VECFIELD(double, d) { vector _value; - if (is_seq) - { - for ( int ii = 0; ii < length; ++ii) - { - PyObject * vo = PySequence_GetItem(value, ii); + if (is_seq) { + for (int ii = 0; ii < length; ++ii) { + PyObject *vo = PySequence_GetItem(value, ii); double v = PyFloat_AsDouble(vo); Py_XDECREF(vo); _value.push_back(v); } - } - else - { + } else { double v = PyFloat_AsDouble(value); _value.assign(length, v); } ret = Field::setVec(self->id_, string(fieldname), _value); break; } - case 's': - { + case 's': { vector _value; - if (is_seq) - { - for ( int ii = 0; ii < length; ++ii) - { - PyObject * vo = PySequence_GetItem(value, ii); - char * v = PyString_AsString(vo); + if (is_seq) { + for (int ii = 0; ii < length; ++ii) { + PyObject *vo = PySequence_GetItem(value, ii); + char *v = PyString_AsString(vo); Py_XDECREF(v); _value.push_back(string(v)); } - } - else - { - char * v = PyString_AsString(value); + } else { + char *v = PyString_AsString(value); _value.assign(length, string(v)); } ret = Field::setVec(self->id_, string(fieldname), _value); break; } - case 'i': - { + case 'i': { vector _value; - if (is_seq) - { - for ( int ii = 0; ii < length; ++ii) - { - PyObject * vo = PySequence_GetItem(value, ii); + if (is_seq) { + for (int ii = 0; ii < length; ++ii) { + PyObject *vo = PySequence_GetItem(value, ii); int v = PyInt_AsLong(vo); Py_XDECREF(vo); _value.push_back(v); } - } - else - { + } else { int v = PyInt_AsLong(value); _value.assign(length, v); } - ret = Field< int >::setVec(self->id_, string(fieldname), _value); + ret = Field::setVec(self->id_, string(fieldname), _value); break; } - case 'I': //SET_VECFIELD(unsigned int, I) + case 'I': // SET_VECFIELD(unsigned int, I) { vector _value; - if (is_seq) - { - for ( int ii = 0; ii < length; ++ii) - { - PyObject * vo = PySequence_GetItem(value, ii); + if (is_seq) { + for (int ii = 0; ii < length; ++ii) { + PyObject *vo = PySequence_GetItem(value, ii); unsigned int v = PyInt_AsUnsignedLongMask(vo); Py_DECREF(vo); _value.push_back(v); } - } - else - { + } else { unsigned int v = PyInt_AsUnsignedLongMask(value); _value.assign(length, v); } - ret = Field< unsigned int >::setVec(self->id_, string(fieldname), _value); + ret = Field::setVec(self->id_, string(fieldname), _value); break; } - case 'l': //SET_VECFIELD(long, l) + case 'l': // SET_VECFIELD(long, l) { vector _value; - if (is_seq) - { - for ( int ii = 0; ii < length; ++ii) - { - PyObject * vo = PySequence_GetItem(value, ii); + if (is_seq) { + for (int ii = 0; ii < length; ++ii) { + PyObject *vo = PySequence_GetItem(value, ii); long v = PyInt_AsLong(vo); Py_DECREF(vo); _value.push_back(v); } - } - else - { + } else { long v = PyInt_AsLong(value); _value.assign(length, v); } ret = Field::setVec(self->id_, string(fieldname), _value); break; } - case 'k': //SET_VECFIELD(unsigned long, k) + case 'k': // SET_VECFIELD(unsigned long, k) { vector _value; - if (is_seq) - { - for ( int ii = 0; ii < length; ++ii) - { - PyObject * vo = PySequence_GetItem(value, ii); + if (is_seq) { + for (int ii = 0; ii < length; ++ii) { + PyObject *vo = PySequence_GetItem(value, ii); unsigned long v = PyInt_AsUnsignedLongMask(vo); Py_XDECREF(vo); _value.push_back(v); } - } - else - { + } else { unsigned long v = PyInt_AsUnsignedLongMask(value); _value.assign(length, v); } - ret = Field< unsigned long >::setVec(self->id_, string(fieldname), _value); + ret = Field::setVec(self->id_, string(fieldname), _value); break; } - case 'b': - { + case 'b': { vector _value; - if (is_seq) - { - for ( int ii = 0; ii < length; ++ii) - { - PyObject * _v = PySequence_GetItem(value, ii); - bool v = (Py_True ==_v) || (PyInt_AsLong(_v) != 0); + if (is_seq) { + for (int ii = 0; ii < length; ++ii) { + PyObject *_v = PySequence_GetItem(value, ii); + bool v = (Py_True == _v) || (PyInt_AsLong(_v) != 0); Py_XDECREF(_v); _value.push_back(v); } - } - else - { - bool v = (Py_True ==value) || (PyInt_AsLong(value) != 0); + } else { + bool v = (Py_True == value) || (PyInt_AsLong(value) != 0); _value.assign(length, v); } - ret = Field< bool >::setVec(self->id_, string(fieldname), _value); + ret = Field::setVec(self->id_, string(fieldname), _value); break; } - case 'c': - { + case 'c': { vector _value; - if (is_seq) - { - for ( int ii = 0; ii < length; ++ii) - { - PyObject * _v = PySequence_GetItem(value, ii); - char * v = PyString_AsString(_v); + if (is_seq) { + for (int ii = 0; ii < length; ++ii) { + PyObject *_v = PySequence_GetItem(value, ii); + char *v = PyString_AsString(_v); Py_XDECREF(_v); - if (v && v[0]) - { + if (v && v[0]) { _value.push_back(v[0]); - } - else - { + } else { ostringstream err; err << "moose_Id_setattro:" << ii << "-th element is NUL"; PyErr_SetString(PyExc_ValueError, err.str().c_str()); return -1; } } - } - else - { - char * v = PyString_AsString(value); - if (v && v[0]) - { + } else { + char *v = PyString_AsString(value); + if (v && v[0]) { _value.assign(length, v[0]); - } - else - { - PyErr_SetString(PyExc_ValueError, "moose_Id_setattro: value is an empty string"); + } else { + PyErr_SetString(PyExc_ValueError, + "moose_Id_setattro: value is an empty string"); return -1; } } - ret = Field< char >::setVec(self->id_, string(fieldname), _value); + ret = Field::setVec(self->id_, string(fieldname), _value); break; } - case 'h': - { + case 'h': { vector _value; - if (is_seq) - { - for ( int ii = 0; ii < length; ++ii) - { - PyObject * vo = PySequence_GetItem(value, ii); + if (is_seq) { + for (int ii = 0; ii < length; ++ii) { + PyObject *vo = PySequence_GetItem(value, ii); short v = PyInt_AsLong(vo); Py_XDECREF(vo); _value.push_back(v); } - } - else - { + } else { short v = PyInt_AsLong(value); _value.assign(length, v); } - ret = Field< short >::setVec(self->id_, string(fieldname), _value); + ret = Field::setVec(self->id_, string(fieldname), _value); break; } - case 'f': //SET_VECFIELD(float, f) + case 'f': // SET_VECFIELD(float, f) { vector _value; - if (is_seq) - { - for ( int ii = 0; ii < length; ++ii) - { - PyObject * vo = PySequence_GetItem(value, ii); + if (is_seq) { + for (int ii = 0; ii < length; ++ii) { + PyObject *vo = PySequence_GetItem(value, ii); float v = PyFloat_AsDouble(vo); Py_XDECREF(vo); _value.push_back(v); } - } - else - { + } else { float v = PyFloat_AsDouble(value); _value.assign(length, v); }