Ejemplo n.º 1
0
                def rhs(t, y, p):
                    # note that the evaluated code sets ydot as a side effect
                    Cython.inline(
                        code_eqs, quiet=True,
                        cython_compiler_directives=cython_directives)

                    return ydot
Ejemplo n.º 2
0
def grad_dist2(ls, x1, x2=None):
    if x2 is None:
        x2 = x1

    # Rescale.
    x1 = x1 / ls
    x2 = x2 / ls

    N = x1.shape[0]
    M = x2.shape[0]
    D = x1.shape[1]
    gX = np.zeros((x1.shape[0], x2.shape[0], x1.shape[1]))

    code = \
    """
    for (int i=0; i<N; i++)
      for (int j=0; j<M; j++)
        for (int d=0; d<D; d++)
          gX(i,j,d) = (2/ls(d))*(x1(i,d) - x2(j,d));
    """
    try:
        # THIS CURRENTLY DOES NOT WORK, NEED TO CONVERT TO CYTHON
        weave.inline(code, ['x1','x2','gX','ls','M','N','D'], \
                       type_converters=weave.converters.blitz, \
                       compiler='gcc')
    except:
        # The C code weave above is 10x faster than this:
        for i in range(0, x1.shape[0]):
            gX[i, :, :] = 2 * (x1[i, :] - x2[:, :]) * (1 / ls)

    return gX
Ejemplo n.º 3
0
def load_ipython_extension(ip):
    """Load the extension in IPython."""
    
    print("""The Cython magic has been move to the Cython package, hence """)
    print("""`%load_ext cythonmagic` is deprecated; Please use `%load_ext Cython` instead.""")
    
    if Cython is None or not version.check_version(Cython.__version__, "0.21"):
        print("You need Cython version >=0.21 to use the Cython magic")
        return 
    print("""\nThough, because I am nice, I'll still try to load it for you this time.""")
    Cython.load_ipython_extension(ip)
Ejemplo n.º 4
0
def load_ipython_extension(ip):
    """Load the extension in IPython."""
    
    print("""The Cython magic has been moved to the Cython package, hence """)
    print("""`%load_ext cythonmagic` is deprecated; please use `%load_ext Cython` instead.""")
    
    if Cython is None or not version.check_version(Cython.__version__, "0.21"):
        print("You need Cython version >=0.21 to use the Cython magic")
        return 
    print("""\nThough, because I am nice, I'll still try to load it for you this time.""")
    Cython.load_ipython_extension(ip)
Ejemplo n.º 5
0
 def _test_cython(cls):
     if not hasattr(cls, '_use_cython'):
         cls._use_cython = False
         if Cython is None:
             return
         try:
             Cython.inline('x = 1', force=True, quiet=True)
             cls._use_cython = True
         except (Cython.Compiler.Errors.CompileError,
                 distutils.errors.DistutilsPlatformError, ValueError) as e:
             if not cls._check_compiler_error(e, 'cython'):
                 raise
Ejemplo n.º 6
0
 def _test_cython(cls):
     if not hasattr(cls, '_use_cython'):
         cls._use_cython = False
         if Cython is None:
             return
         try:
             Cython.inline('x = 1', force=True, quiet=True)
             cls._use_cython = True
         except (Cython.Compiler.Errors.CompileError,
                 distutils.errors.DistutilsPlatformError,
                 ValueError) as e:
             if not cls._check_compiler_error(e, 'cython'):
                 raise
Ejemplo n.º 7
0
 def _test_cython(cls):
     if not hasattr(cls, '_use_cython'):
         cls._use_cython = False
         if Cython is None:
             return
         try:
             Cython.inline('x = 1', force=True, quiet=True)
             cls._use_cython = True
         except Cython.Compiler.Errors.CompileError:
             pass
         except ValueError as e:
             if len(e.args) == 1 and e.args[0] == "Symbol table not found":
                 get_logger(__name__).debug(
                     "'ValueError: Symbol table not found' "
                     "encountered; Cython compiler is not functional")
             else:
                 raise
Ejemplo n.º 8
0
def to_python(schema):
    definition = copy.deepcopy(schema.definition)
    metadata = schema.definition.pop('__metadata__', {})
    code = _compile_schema(schema)
    if Cython and hasattr(Cython, 'inline'):
        name_space = schema.supported_types.copy()
        name_space['metadata'] = schema.metadata
        name_space = Cython.inline(code, name_space)
    else:
        name_space = schema.supported_types.copy()
        name_space['metadata'] = schema.metadata
        exec(compile(code, '<string>', 'exec'), name_space)
    return name_space['apply_schema']
Ejemplo n.º 9
0
def to_python(schema):
    _ = copy.deepcopy(schema.definition)
    _ = schema.definition.pop("__metadata__", {})
    code = _compile_schema(schema)
    if Cython and hasattr(Cython, "inline"):
        name_space = schema.supported_types.copy()
        name_space["metadata"] = schema.metadata
        name_space = Cython.inline(code, globals=name_space, language_level=3)
    else:
        name_space = schema.supported_types.copy()
        name_space["metadata"] = schema.metadata
        exec(compile(code, "<string>", "exec"), name_space)
    return name_space["apply_schema"]
Ejemplo n.º 10
0
 def check(cls):
     # Quick return if previous check succeeded, otherwise re-run the checks
     # so the exception is always raised if called repeatedly.
     if cls._check_ok:
         return
     compiler_exc = None
     try:
         import Cython
         Cython.inline("x = 1", force=True, quiet=True)
         cls._check_ok = True
         return
     except ImportError:
         raise RuntimeError(
             "Please install the Cython package to use this compiler.")
     # Catch some common C compiler configuration problems so we can raise a
     # chained exception with a more helpful message.
     except (
             Cython.Compiler.Errors.CompileError,
             distutils.errors.CCompilerError,
             distutils.errors.DistutilsPlatformError,
     ) as e:
         compiler_exc = e
     except ValueError as e:
         if e.args == ("Symbol table not found", ):
             # This is a common error building against numpy with mingw32.
             compiler_exc = e
         else:
             raise
     message = "Please check you have a functional C compiler"
     if os.name == "nt":
         message += ", available from " \
                    "https://wiki.python.org/moin/WindowsCompilers"
     else:
         message += "."
     # Reference chained exceptions for specifics on what went wrong.
     message += "\nSee the above error messages for more details."
     raise RuntimeError(message) from compiler_exc
Ejemplo n.º 11
0
    def cython_inline(self, line, cell):
        """Compile and run a Cython code cell using Cython.inline.

        This magic simply passes the body of the cell to Cython.inline
        and returns the result. If the variables `a` and `b` are defined
        in the user's namespace, here is a simple example that returns
        their sum::

            %%cython_inline
            return a+b

        For most purposes, we recommend the usage of the `%%cython` magic.
        """
        locs = self.shell.user_global_ns
        globs = self.shell.user_ns
        return Cython.inline(cell, locals=locs, globals=globs)
Ejemplo n.º 12
0
    def cython_inline(self, line, cell):
        """Compile and run a Cython code cell using Cython.inline.

        This magic simply passes the body of the cell to Cython.inline
        and returns the result. If the variables `a` and `b` are defined
        in the user's namespace, here is a simple example that returns
        their sum::

            %%cython_inline
            return a+b

        For most purposes, we recommend the usage of the `%%cython` magic.
        """
        locs = self.shell.user_global_ns
        globs = self.shell.user_ns
        return Cython.inline(cell, locals=locs, globals=globs)
Ejemplo n.º 13
0
                def rhs(t, y, p):
                    # note that the evaluated code sets ydot as a side effect
                    Cython.inline(code_eqs, quiet=True)

                    return ydot
Ejemplo n.º 14
0
 def jacobian(t, y, p):
     Cython.inline(jac_eqs, quiet=True)
     return jac
Ejemplo n.º 15
0
 def ode_rhs(t, y, p):
     ydot = self.ydot
     Cython.inline(code_eqs, quiet=True)
     return ydot
Ejemplo n.º 16
0
import numpy
import scipy.integrate
import collections
import itertools
import distutils.errors

_use_cython = False
# try to inline a C statement to see if Cython is functional
try:
    import Cython
except ImportError:
    Cython = None
if Cython:
    from Cython.Compiler.Errors import CompileError
    try:
        Cython.inline('x = 1', force=True, quiet=True)
        _use_cython = True
    except (CompileError, distutils.errors.CompileError, ValueError):
        pass

Parameter = collections.namedtuple('Parameter', 'name value')
Observable = collections.namedtuple('Observable', 'name species coefficients')
Initial = collections.namedtuple('Initial', 'param_index species_index')


class Model(object):
    def __init__(self):
        self.y = None
        self.yobs = None
        self.y0 = numpy.empty(3)
        self.ydot = numpy.empty(3)
Ejemplo n.º 17
0
 def jacobian(t, y, p):
     Cython.inline(
         jac_eqs, quiet=True,
         cython_compiler_directives=cython_directives)
     return jac