LoLab-MSM / pysb

Python framework for Systems Biology modeling [Lopez Lab Mods]
BSD 2-Clause "Simplified" License
6 stars 8 forks source link

Convert scipy_weave to cython in integrate.py #23

Closed JamesPino closed 6 years ago

JamesPino commented 9 years ago

scipy_weave is deprecated. http://docs.scipy.org/doc/scipy/reference/weave.html

So I propose to create a RHS.pyx and compile with cython. Then we can pass ode this function. Similar example of creating a cython file and compiling from within a python file is found in https://github.com/LoLab-VU/LogicalModel/main_attractor_synch_cython.py

Example. pyxfile = open(prefix+'.pyx','w') outstring = \ 'from future import division\ \nimport numpy as np\ \ncimport numpy as np\ \ncimport cython\ \n\nDTYPE = np.int\ \nctypedef np.int_t DTYPE_t\ \n@cython.boundscheck(False)\ \ndef function(np.ndarray[DTYPE_t, ndim=1] x):\ \n\tcdef unsigned int vectorsize = %d\ \n\tcdef np.ndarray[DTYPE_t, ndim=1] vector = np.zeros([vectorsize],dtype=int)\n'%numNodes for line in functions:

Replace function name

    line = re.sub('f\d+', 'vector[%d]' % (int(re.match('f(\d+)', line).group(1))-1), line)
    # Convert powers (^) to simple multiplications
    matches = re.findall('(x\d+)^(\d+)', line)
    for m in matches:
        repl = m[0]
        for i in range(1,int(m[1])):
            repl += "*%s" % m[0]
        line = re.sub('x\d+^\d+', repl, line, count=1)
    # Replace node names
    matches = np.array(re.findall('x(\d+)', line), dtype=int)
    for m in matches:
        line = re.sub('x\d+', 'x[%d]' % (m-1), line, count=1)
    outstring += '\t%s\n' % line
#outstring += '\tvector = np.fmod(vector,%d)\n\treturn vector\n' %  numStates
outstring += '\tfor i in xrange(%d):\n\t\tvector[i] = vector[i]%%%d\n\treturn vector,tuple(vector)\n' %  (numNodes,numStates)
pyxfile.write(outstring)
pyxfile.close()
setup = open('setup.py','w')
outstring = \
"from distutils.core import setup\
\nimport numpy\
\nfrom Cython.Build import cythonize\
\nsetup(\
\n    ext_modules = cythonize('"+prefix+".pyx',),\
      include_dirs = [numpy.get_include()])"
setup.write(outstring)
setup.close()
os.system('python setup.py build_ext --inplace')
sys.path.append(dir)
function = import_module(prefix).function
alubbock commented 6 years ago

@JamesPino I've implemented Cython compiling for ScipyOdeSimulator using cython.inline rather than an extension as above, in pysb/pysb#320. It's slightly slower than weave (but not by much). If you have any performance tips for that PR that'd be helpful. Thanks.