Пример #1
0
    class ArrayAccess(SimObject):
        _clibname_ = clibname
        _clibdir_ = relpath('ext/build', __file__)
        _cmembers_ = gene_cmembers(nd, _list_cdt, carrtype)
        _cfuncs_ = gene_cfuncs(nd, _list_cdt)
        num_names = gene_nums(nd)
        ndim = nd
        list_cdt = _list_cdt

        def arr(self, cdt, dim):
            """Get array member '{cdt}{dim}d' (e.g., 'int2d')"""
            return getattr(self, '%s%dd' % (cdt, dim))

        def arr_via_ret(self, cdt, dim):
            """Get copy of array using 'get_{cdt}{dim}d' c-function"""
            get = getattr(self, 'get_%s%dd' % (cdt, dim))
            arr = self.arr(cdt, dim)
            garr = numpy.zeros_like(arr)
            for idx in numpy.ndindex(*arr.shape):
                get(*idx)  # call get_* c-func. which store val. in ret_{cdt}
                garr[idx] = getattr(self, 'ret_%s' % cdt)
            return garr

        def fill(self):
            """Fill array members using arange"""
            for cdt in self.list_cdt:
                if cdt == 'char':
                    arange = alpharange
                elif cdt == 'bool':
                    arange = lambda n: numpy.arange(n) % 2
                else:
                    arange = numpy.arange
                for dim in range(1, 1 + self.ndim):
                    arr = self.arr(cdt, dim)
                    arr.flat = arange(arr.size)
Пример #2
0
class LinearOrdinaryDifferentialEquation(SimObject):  # != LinearODE
    """
    Solve D-dimensional linear ordinary differential equations

    Equation::

        dX/dt(t) = A X(t)
        X: D-dimensional vector
        A: DxD matrix

    """

    _clibname_ = 'liblode.so'  # name of shared library
    _clibdir_ = relpath('.', __file__)  # library directory
    _cstructname_ = 'LinearODE'  # specify the C struct name
    _cmembers_ = [  # declaring members of struct
        'num_d',  # num_* as size of array (no need to write `int`)
        'num_s = 10000',  # setting default value
        'double dt = 0.001',
        'double a[d][d]',  # num_d x num_d array
        'double x[s][d]',  # num_s x num_d array
        ]
    _cfuncs_ = [  # declaring functions to load
        "x run(s< s_end=num_s)"
        # argument `s_end` has index `s` type and default is `num_s`
        # '<' means it is upper bound of the index so the range is [1, num_s]
        # this function returns member x
        ]
Пример #3
0
class VectCalc(SimObject):
    _clibname_ = 'vectclac.so'
    _clibdir_ = relpath('ext/build', __file__)

    _cmembers_ = [
        'num_i',
        'int v1[i] = 1',
        'int v2[i] = 2',
        'int v3[i]',
        'int ans',
    ]

    _cfuncs_ = [
        "vec_{op | plus, minus, times, divide}()",
        "subvec_{op | plus, minus, times, divide}(i i1=0, i< i2=num_i)",
        "fill_{vec | v1, v2, v3}(int s)",
        "ans subvec_dot(i i1=0, i< i2=num_i)",
    ]

    def __init__(self, num_i=10, **kwds):
        SimObject.__init__(self, num_i=num_i, **kwds)

    @classmethod
    def another_clib(cls, clibname):
        """
        Generate a class which loads `clibname` instead
        """
        class AnotherClass(cls):
            _cstructname_ = cls.__name__
            _clibname_ = clibname

        return AnotherClass
Пример #4
0
class LinearODERK4(SimObject):
    """
    Solve D-dimensional linear ODE using the Runge-Kutta method

    Equation::

        dX/dt(t) = A X(t)
        X: D-dimensional vector
        A: DxD matrix

    """

    _clibname_ = 'liblode_rk4.so'  # name of shared library
    _clibdir_ = relpath('.', __file__)  # library directory
    _cmembers_ = [  # declaring members of struct
        'num_d',  # num_* as size of array (no need to write `int`)
        'num_s',  # setting default value
        'double dt = 0.001',
        'double a[d][d]',  # num_d x num_d array
        'double x[s][d]',  # num_s x num_d array
    ] + (
        cm.double('k%s[d]' % s for s in '1234') +
        cm.double('x%s[d]' % s for s in '123') +
        cm.double('k%s_debug[s][d]' % s for s in '1234') +
        cm.double('x%s_debug[s][d]' % s for s in '123')
    )
    _cfuncs_ = ["x run_{mode | normal, debug}()"]
    _cmemsubsets_ = dict(
        debug=dict(
            funcs=['run_debug'],
            members=(['k%s_debug' % s for s in '1234'] +
                     ['x%s_debug' % s for s in '123'])),
        )

    def plot_x(self):
        import pylab
        t = pylab.arange(self.num_s) * self.dt

        for d in range(self.num_d):
            pylab.plot(t, self.x[:,d], label='x%s'% d)
        pylab.legend()

    def plot_k(self):
        import pylab
        t = pylab.arange(self.num_s) * self.dt
        klist = self.getv(*['k%s_debug' % s for s in '1234'])

        for d in range(self.num_d):
            for (i, k) in enumerate(klist):
                pylab.plot(t, k[:,d], label='k%s_%s'% (i, d))
        pylab.legend()
Пример #5
0
class KaplanYorkeMap(SimObject):
    """
    Simulating Kaplan-Yorke Map using RailGun
    """

    _clibname_ = 'libkaplan_yorke_map.so'  # name of shared library
    _clibdir_ = relpath('.', __file__)  # library directory
    _cmembers_ = [  # declaring members of struct
        'num_i',  # num_* as size of array (no need to write `int`)
        'double xt[i]',  # array with num_i elements
        'double yt[i]',  # array with num_i elements
        'double mu',
        'double lmd',
    ]
    _cfuncs_ = ["gene_seq()"]
Пример #6
0
class VectCalc(SimObject):
    _clibname_ = 'vectclac.so'
    _clibdir_ = relpath('ext/build', __file__)

    _cmembers_ = [
        'num_i = 10',
        'int v1[i] = 1',
        'int v2[i] = 2',
        'int v3[i]',
        'int ans',
    ]

    _cfuncs_ = [
        "vec_{op | plus, minus, times, divide}()",
        "subvec_{op | plus, minus, times, divide}(i i1=0, i< i2=num_i)",
        "fill_{vec | v1, v2, v3}(int s)",
        "ans subvec_dot(i i1=0, i< i2=num_i)",
    ]
Пример #7
0
class BaseArrayAccess(SimObject):

    _cstructname_ = 'ArrayAccess'
    _clibdir_ = relpath('ext/build', __file__)

    list_cdt = [
        'char', 'short', 'ushort', 'int', 'uint', 'long', 'ulong', 'float',
        'double', 'longdouble', 'size_t'
    ]

    def __init__(self, **kwds):
        for name in self.num_names:
            kwds.setdefault(name, 2)
        super(BaseArrayAccess, self).__init__(**kwds)

    def arr(self, cdt, dim):
        """Get array member '{cdt}{dim}d' (e.g., 'int2d')"""
        return getattr(self, '%s%dd' % (cdt, dim))

    def arr_via_ret(self, cdt, dim):
        """Get copy of array using 'get_{cdt}{dim}d' c-function"""
        get = getattr(self, 'get_%s%dd' % (cdt, dim))
        arr = self.arr(cdt, dim)
        garr = numpy.zeros_like(arr)
        for idx in numpy.ndindex(*arr.shape):
            get(*idx)  # call get_* c-func. which store val. in ret_{cdt}
            garr[idx] = getattr(self, 'ret_%s' % cdt)
        return garr

    def fill(self):
        """Fill array members using arange"""
        for cdt in self.list_cdt:
            if cdt == 'char':
                arange = alpharange
            elif cdt == 'bool':
                arange = lambda n: numpy.arange(n) % 2
            else:
                arange = numpy.arange
            for dim in range(1, 1 + self.ndim):
                arr = self.arr(cdt, dim)
                arr.flat = arange(arr.size)
Пример #8
0
    class ClassNameIsNotVectCalc(SimObject):
        _clibname_ = 'vectclac.so'
        _clibdir_ = relpath('ext/build', __file__)

        _cmembers_ = [
            'num_i',
            'int v1[i]',
            'int v2[i]',
            'int v3[i]',
            'int ans',
            ]

        _cfuncs_ = ['VectCalc_' + f for f in [
            "vec_{op | plus, minus, times, divide}()",
            "subvec_{op | plus, minus, times, divide}(i i1=0, i< i2=num_i)",
            "fill_{vec | v1, v2, v3}(int s)",
            "subvec_dot(i i1=0, i< i2=num_i)",
            ]]

        if cfuncprefix is not None:
            _cfuncprefix_ = cfuncprefix
Пример #9
0
class LogisticMap(SimObject):

    _clibname_ = 'liblogistic_map.so'
    _clibdir_ = relpath('.', __file__)
    _cmembers_ = [
        'num_i',
        'double xt[i]',
        'double mu',
        'double sigma',
        cmem(gsl_rng, 'rng'),
    ]
    _cfuncs_ = ["xt gene_seq()"]

    def __init__(self, num_i, seed=None, **kwds):
        SimObject.__init__(self, num_i=num_i, rng=gsl_rng(seed), **kwds)

    def _cwrap_gene_seq(old_gene_seq):
        def gene_seq(self, **kwds):
            # use the previous "last state" as initial state, but setv
            # may overwrite this by `xt_0=SOMEVAL`
            self.xt[0] = self.xt[-1]
            self.setv(**kwds)
            return old_gene_seq(self)

        return gene_seq

    def bifurcation_diagram(self, mu_start, mu_stop, mu_num, **kwds):
        mu_list = numpy.linspace(mu_start, mu_stop, mu_num)
        self.gene_seq(mu=mu_list[0], **kwds)  # through first steps away
        xt_list = [self.gene_seq(mu=mu).copy() for mu in mu_list]
        return (mu_list, xt_list)

    def plot_bifurcation_diagram(self, mu_start, mu_stop, mu_num, **kwds):
        import pylab
        bd = self.bifurcation_diagram(mu_start, mu_stop, mu_num, **kwds)
        ones = numpy.ones(self.num_i)

        for (mu, x) in zip(*bd):
            pylab.plot(ones * mu, x, 'ko', markersize=0.5)
        pylab.ylim(0, 1)