Пример #1
0
def run_simulation(t,
                   y0={},
                   volume=1.0,
                   model=None,
                   solver='ode',
                   factory=None,
                   is_netfree=False,
                   species_list=None,
                   without_reset=False,
                   return_type='matplotlib',
                   plot_args={}):
    """Run a simulation with the given model and plot the result on IPython
    notebook with matplotlib.

    Parameters
    ----------
    t: array
        A sequence of time points for which to solve for 'm'.
    y0: dict
        Initial condition.
    volume: Real, optional
    model: Model, optional
    solver: str, optional
        Solver type. Choose one from 'ode', 'gillespie', 'lattice', 'meso',
        'bd' and 'egfrd'. Default is 'ode'.
    species_list: list of str, optional
        A list of names of Species observed. If None, log all.
        Default is None.
    return_type: str, optional
        Choose a type of return value from 'array', 'observer',
        'matplotlib', 'nyaplot' or None.
        If None, return and plot nothing. Default is 'matplotlib'.
    plot_args: dict, optional
        Arguments for plotting. If plot_type is None, just ignored.
    factory: Factory, optional
    is_netfree: bool, optional
        Whether the model is netfree or not. When a model is given as an
        argument, just ignored. Default is False.
    """
    import ecell4

    if factory is not None:
        f = factory
    elif solver == 'ode':
        f = ecell4.ode.ODEFactory()
    elif solver == 'gillespie':
        f = ecell4.gillespie.GillespieFactory()
    elif solver == 'lattice':
        f = ecell4.lattice.LatticeFactory()
    elif solver == 'meso':
        f = ecell4.meso.MesoscopicFactory()
    elif solver == 'bd':
        f = ecell4.bd.BDFactory()
    elif solver == 'egfrd':
        f = ecell4.egfrd.EGFRDFactory()
    else:
        raise ValueError('unknown solver name was given: ' + repr(solver) +
                         '. use ode, gillespie, lattice, meso, bd or egfrd')

    L = ecell4.cbrt(volume)

    if model is None:
        model = ecell4.util.decorator.get_model(is_netfree, without_reset)

    edge_lengths = ecell4.Real3(L, L, L)
    w = f.create_world(edge_lengths)

    if isinstance(w, ecell4.ode.ODEWorld):
        # w.bind_to(model)  # stop binding for ode
        for serial, n in y0.items():
            w.set_value(ecell4.Species(serial), n)
    else:
        w.bind_to(model)
        for serial, n in y0.items():
            w.add_molecules(ecell4.Species(serial), n)

    if species_list is None:
        if isinstance(model, ecell4.ode.ODENetworkModel):
            #XXX: A bit messy way
            species_list = [sp.serial() for sp in model.list_species()]
        else:
            seeds = [ecell4.Species(serial) for serial in y0.keys()]
            species_list = [
                sp.serial() for sp in model.expand(seeds).list_species()
            ]

    obs = ecell4.TimingNumberObserver(t, species_list)
    sim = f.create_simulator(model, w)
    # sim = f.create_simulator(w)
    sim.run(t[-1], obs)

    if return_type == 'matplotlib':
        ecell4.viz.plot_number_observer(obs, **plot_args)
    elif return_type == 'nyaplot':
        ecell4.viz.plot_number_observer_with_nya(obs, **plot_args)
    elif return_type == 'observer':
        return obs
    elif return_type == 'array':
        return obs.data()
Пример #2
0
def run_simulation(
        t, y0={}, volume=1.0, model=None, solver='ode',
        factory=None, is_netfree=False, species_list=None, without_reset=False,
        return_type='matplotlib', opt_args=(), opt_kwargs={},
        structures={}, observers=(), progressbar=0):
    """Run a simulation with the given model and plot the result on IPython
    notebook with matplotlib.

    Parameters
    ----------
    t : array or Real
        A sequence of time points for which to solve for 'm'.
    y0 : dict
        Initial condition.
    volume : Real or Real3, optional
        A size of the simulation volume.
    model : Model, optional
    solver : str, tuple or Factory, optional
        Solver type. Choose one from 'ode', 'gillespie', 'spatiocyte', 'meso',
        'bd' and 'egfrd'. Default is 'ode'.
        When tuple is given, the first value must be str as explained above.
        All the rest is used as arguments for the corresponding factory class.
    species_list : list of str, optional
        A list of names of Species observed. If None, log all.
        Default is None.
    return_type : str, optional
        Choose a type of return value from 'array', 'observer',
        'matplotlib', 'nyaplot', 'world', 'dataframe' or None.
        If None, return and plot nothing. Default is 'matplotlib'.
        'dataframe' requires numpy and pandas libraries.
    opt_args: list, tuple or dict, optional
        Arguments for plotting. If return_type suggests no plotting, just ignored.
    opt_kwargs: dict, optional
        Arguments for plotting. If return_type suggests no plotting or
        opt_args is a list or tuple, just ignored.
        i.e.) viz.plot_number_observer(obs, *opt_args, **opt_kwargs)
    factory: Factory, optional
    is_netfree: bool, optional
        Whether the model is netfree or not. When a model is given as an
        argument, just ignored. Default is False.
    structures : dict, optional
        A dictionary which gives pairs of a name and shape of structures.
        Not fully supported yet.
    observers : Observer or list, optional
        A list of extra observer references.
    progressbar : float, optional
        A timeout for a progress bar in seconds.
        When the value is not more than 0, show nothing.
        Default is 0.

    Returns
    -------
    value : list, TimingNumberObserver, World or None
        Return a value suggested by ``return_type``.
        When ``return_type`` is 'array', return a time course data.
        When ``return_type`` is 'observer', return an observer.
        When ``return_type`` is 'world', return the last state of ``World``.
        Return nothing if else.

    """
    import ecell4

    if factory is not None:
        f = factory  #XXX: will be deprecated in the future. just use solver
    elif isinstance(solver, str):
        f = get_factory(solver)
    elif isinstance(solver, collections.Iterable):
        f = get_factory(*solver)
    else:
        f = solver

    if model is None:
        model = ecell4.util.decorator.get_model(is_netfree, without_reset)

    if isinstance(volume, ecell4.Real3):
        edge_lengths = volume
    else:
        L = ecell4.cbrt(volume)
        edge_lengths = ecell4.Real3(L, L, L)

    w = f.create_world(edge_lengths)

    for (name, shape) in structures.items():
        w.add_structure(ecell4.Species(name), shape)

    if isinstance(w, ecell4.ode.ODEWorld):
        # w.bind_to(model)  # stop binding for ode
        for serial, n in y0.items():
            w.set_value(ecell4.Species(serial), n)
    else:
        w.bind_to(model)
        for serial, n in y0.items():
            w.add_molecules(ecell4.Species(serial), n)

    if species_list is None:
        if isinstance(model, ecell4.ode.ODENetworkModel):
            #XXX: A bit messy way
            species_list = [sp.serial() for sp in model.list_species()]
        else:
            seeds = [ecell4.Species(serial) for serial in y0.keys()]
            species_list = [
                sp.serial() for sp in model.expand(seeds).list_species()]
            species_list = sorted(set(list(y0.keys()) + species_list))

    if not isinstance(t, collections.Iterable):
        t = [float(t) * i / 100 for i in range(101)]

    obs = ecell4.TimingNumberObserver(t, species_list)
    sim = f.create_simulator(model, w)
    # sim = f.create_simulator(w)

    if not isinstance(observers, collections.Iterable):
        observers = (observers, )
    if return_type not in ('world', None):
        observers = (obs, ) + tuple(observers)

    if progressbar > 0:
        from .progressbar import progressbar as pb
        pb(sim, timeout=progressbar, flush=True).run(t[-1], observers)
    else:
        sim.run(t[-1], observers)

    if return_type == 'matplotlib':
        if isinstance(opt_args, (list, tuple)):
            ecell4.viz.plot_number_observer(obs, *opt_args, **opt_kwargs)
        elif isinstance(opt_args, dict):
            # opt_kwargs is ignored
            ecell4.viz.plot_number_observer(obs, **opt_args)
        else:
            raise ValueError('opt_args [{}] must be list or dict.'.format(
                repr(opt_args)))
    elif return_type == 'nyaplot':
        if isinstance(opt_args, (list, tuple)):
            ecell4.viz.plot_number_observer_with_nya(obs, *opt_args, **opt_kwargs)
        elif isinstance(opt_args, dict):
            # opt_kwargs is ignored
            ecell4.viz.plot_number_observer_with_nya(obs, **opt_args)
        else:
            raise ValueError('opt_args [{}] must be list or dict.'.format(
                repr(opt_args)))
    elif return_type == 'observer':
        return obs
    elif return_type == 'array':
        return obs.data()
    elif return_type == 'dataframe':
        import pandas
        import numpy
        data = numpy.array(obs.data()).T
        return pandas.concat([
            pandas.DataFrame(dict(Time=data[0], Value=data[i + 1],
                                  Species=sp.serial(), **opt_kwargs))
            for i, sp in enumerate(obs.targets())])
    elif return_type == 'world':
        return sim.world()
Пример #3
0
def run_simulation(
        t, y0={}, volume=1.0, model=None, solver='ode',
        factory=None, is_netfree=False, species_list=None, without_reset=False,
        return_type='matplotlib', plot_args={}):
    """Run a simulation with the given model and plot the result on IPython
    notebook with matplotlib.

    Parameters
    ----------
    t: array
        A sequence of time points for which to solve for 'm'.
    y0: dict
        Initial condition.
    volume: Real, optional
    model: Model, optional
    solver: str, optional
        Solver type. Choose one from 'ode', 'gillespie', 'lattice', 'meso',
        'bd' and 'egfrd'. Default is 'ode'.
    species_list: list of str, optional
        A list of names of Species observed. If None, log all.
        Default is None.
    return_type: str, optional
        Choose a type of return value from 'array', 'observer',
        'matplotlib', 'nyaplot' or None.
        If None, return and plot nothing. Default is 'matplotlib'.
    plot_args: dict, optional
        Arguments for plotting. If plot_type is None, just ignored.
    factory: Factory, optional
    is_netfree: bool, optional
        Whether the model is netfree or not. When a model is given as an
        argument, just ignored. Default is False.
    """
    import ecell4

    if factory is not None:
        f = factory
    elif solver == 'ode':
        f = ecell4.ode.ODEFactory()
    elif solver == 'gillespie':
        f = ecell4.gillespie.GillespieFactory()
    elif solver == 'lattice':
        f = ecell4.lattice.LatticeFactory()
    elif solver == 'meso':
        f = ecell4.meso.MesoscopicFactory()
    elif solver == 'bd':
        f = ecell4.bd.BDFactory()
    elif solver == 'egfrd':
        f = ecell4.egfrd.EGFRDFactory()
    else:
        raise ValueError(
            'unknown solver name was given: ' + repr(solver)
            + '. use ode, gillespie, lattice, meso, bd or egfrd')

    L = ecell4.cbrt(volume)

    if model is None:
        model = ecell4.util.decorator.get_model(is_netfree, without_reset)

    edge_lengths = ecell4.Real3(L, L, L)
    w = f.create_world(edge_lengths)

    if isinstance(w, ecell4.ode.ODEWorld):
        # w.bind_to(model)  # stop binding for ode
        for serial, n in y0.items():
            w.set_value(ecell4.Species(serial), n)
    else:
        w.bind_to(model)
        for serial, n in y0.items():
            w.add_molecules(ecell4.Species(serial), n)

    if species_list is None:
        if isinstance(model, ecell4.ode.ODENetworkModel):
            #XXX: A bit messy way
            species_list = [sp.serial() for sp in model.list_species()]
        else:
            seeds = [ecell4.Species(serial) for serial in y0.keys()]
            species_list = [
                sp.serial() for sp in model.expand(seeds).list_species()]

    obs = ecell4.TimingNumberObserver(t, species_list)
    sim = f.create_simulator(model, w)
    # sim = f.create_simulator(w)
    sim.run(t[-1], obs)

    if return_type == 'matplotlib':
        ecell4.viz.plot_number_observer(obs, **plot_args)
    elif return_type == 'nyaplot':
        ecell4.viz.plot_number_observer_with_nya(obs, **plot_args)
    elif return_type == 'observer':
        return obs
    elif return_type == 'array':
        return obs.data()
Пример #4
0
def run_simulation(
        t,
        y0=None,
        volume=1.0,
        model=None,
        solver='ode',
        is_netfree=False,
        species_list=None,
        without_reset=False,
        return_type='matplotlib',
        opt_args=(),
        opt_kwargs=None,
        structures=None,
        observers=(),
        progressbar=0,
        rndseed=None,
        factory=None,  ## deprecated
        **kwargs):
    """Run a simulation with the given model and plot the result on IPython
    notebook with matplotlib.

    Parameters
    ----------
    t : array or Real
        A sequence of time points for which to solve for 'm'.
    y0 : dict
        Initial condition.
    volume : Real or Real3, optional
        A size of the simulation volume.
        Keyword 'v' is a shortcut for specifying 'volume'.
    model : Model, optional
        Keyword 'm' is a shortcut for specifying 'model'.
    solver : str, tuple or Factory, optional
        Solver type. Choose one from 'ode', 'gillespie', 'spatiocyte', 'meso',
        'bd' and 'egfrd'. Default is 'ode'.
        When tuple is given, the first value must be str as explained above.
        All the rest is used as arguments for the corresponding factory class.
        Keyword 's' is a shortcut for specifying 'solver'.
    species_list : list of str, optional
        A list of names of Species observed. If None, log all.
        Default is None.
    return_type : str, optional
        Choose a type of return value from 'array', 'observer',
        'matplotlib', 'nyaplot', 'world', 'dataframe', 'none' or None.
        If None or 'none', return and plot nothing. Default is 'matplotlib'.
        'dataframe' requires numpy and pandas libraries.
        Keyword 'r' is a shortcut for specifying 'return_type'.
    opt_args: list, tuple or dict, optional
        Arguments for plotting. If return_type suggests no plotting, just ignored.
    opt_kwargs: dict, optional
        Arguments for plotting. If return_type suggests no plotting or
        opt_args is a list or tuple, just ignored.
        i.e.) viz.plot_number_observer(obs, *opt_args, **opt_kwargs)
    is_netfree: bool, optional
        Whether the model is netfree or not. When a model is given as an
        argument, just ignored. Default is False.
    structures : dict, optional
        A dictionary which gives pairs of a name and shape of structures.
        Not fully supported yet.
    observers : Observer or list, optional
        A list of extra observer references.
    progressbar : float, optional
        A timeout for a progress bar in seconds.
        When the value is not more than 0, show nothing.
        Default is 0.
    rndseed : int, optional
        A random seed for a simulation.
        This argument will be ignored when 'solver' is given NOT as a string.

    Returns
    -------
    value : list, TimingNumberObserver, World or None
        Return a value suggested by ``return_type``.
        When ``return_type`` is 'array', return a time course data.
        When ``return_type`` is 'observer', return an observer.
        When ``return_type`` is 'world', return the last state of ``World``.
        Return nothing if else.

    """
    y0 = y0 or {}
    opt_kwargs = opt_kwargs or {}
    structures = structures or {}

    for key, value in kwargs.items():
        if key == 'r':
            return_type = value
        elif key == 'v':
            volume = value
        elif key == 's':
            solver = value
        elif key == 'm':
            model = value
        else:
            raise ValueError(
                "An unknown keyword argument was given [{}={}]".format(
                    key, value))

    import ecell4

    if factory is not None:
        # f = factory  #XXX: will be deprecated in the future. just use solver
        raise ValueError(
            "Argument 'factory' is no longer available. Use 'solver' instead.")
    elif isinstance(solver, str):
        f = get_factory(solver)
    elif isinstance(solver, collections.Iterable):
        f = get_factory(*solver)
    else:
        f = solver

    if rndseed is not None:
        f = f.rng(ecell4.GSLRandomNumberGenerator(rndseed))

    if model is None:
        model = ecell4.util.decorator.get_model(is_netfree, without_reset)

    if isinstance(volume, ecell4.Real3):
        edge_lengths = volume
    else:
        L = ecell4.cbrt(volume)
        edge_lengths = ecell4.Real3(L, L, L)

    w = f.create_world(edge_lengths)

    for (name, shape) in structures.items():
        w.add_structure(ecell4.Species(name), shape)

    if isinstance(w, ecell4.ode.ODEWorld):
        # w.bind_to(model)  # stop binding for ode
        for serial, n in y0.items():
            w.set_value(ecell4.Species(serial), n)
    else:
        w.bind_to(model)
        for serial, n in y0.items():
            w.add_molecules(ecell4.Species(serial), n)

    if species_list is None:
        species_list = list_species(model, y0.keys())

    if not isinstance(t, collections.Iterable):
        t = [float(t) * i / 100 for i in range(101)]

    obs = ecell4.TimingNumberObserver(t, species_list)
    sim = f.create_simulator(model, w)
    # sim = f.create_simulator(w)

    if not isinstance(observers, collections.Iterable):
        observers = (observers, )
    if return_type not in ('world', 'none', None):
        observers = (obs, ) + tuple(observers)

    if progressbar > 0:
        from .progressbar import progressbar as pb
        pb(sim, timeout=progressbar, flush=True).run(t[-1], observers)
    else:
        sim.run(t[-1], observers)

    if return_type in ('matplotlib', 'm'):
        if isinstance(opt_args, (list, tuple)):
            ecell4.viz.plot_number_observer(obs, *opt_args, **opt_kwargs)
        elif isinstance(opt_args, dict):
            # opt_kwargs is ignored
            ecell4.viz.plot_number_observer(obs, **opt_args)
        else:
            raise ValueError('opt_args [{}] must be list or dict.'.format(
                repr(opt_args)))
    elif return_type in ('nyaplot', 'n'):
        if isinstance(opt_args, (list, tuple)):
            ecell4.viz.plot_number_observer_with_nya(obs, *opt_args,
                                                     **opt_kwargs)
        elif isinstance(opt_args, dict):
            # opt_kwargs is ignored
            ecell4.viz.plot_number_observer_with_nya(obs, **opt_args)
        else:
            raise ValueError('opt_args [{}] must be list or dict.'.format(
                repr(opt_args)))
    elif return_type in ('observer', 'o'):
        return obs
    elif return_type in ('array', 'a'):
        return obs.data()
    elif return_type in ('dataframe', 'd'):
        import pandas
        import numpy
        data = numpy.array(obs.data()).T
        return pandas.concat([
            pandas.DataFrame(
                dict(Time=data[0],
                     Value=data[i + 1],
                     Species=sp.serial(),
                     **opt_kwargs)) for i, sp in enumerate(obs.targets())
        ])
    elif return_type in ('world', 'w'):
        return sim.world()
    elif return_type is None or return_type in ('none', ):
        return
    else:
        raise ValueError('An invald value for "return_type" was given [{}].'.
                         format(str(return_type)) +
                         'Use "none" if you need nothing to be returned.')
Пример #5
0
def run_simulation(
        t, y0, volume=1.0, model=None, with_plot=True, solver='ode',
        factory=None, is_netfree=False, species_list=None, as_observer=False):
    """Run a simulation with the given model and plot the result on IPython
    notebook with matplotlib.

    Parameters
    ----------
    t: array
        A sequence of time points for which to solve for 'm'.
    y0: dict
        Initial condition.
    volume: Real, optional
    model: Model, optional
    with_plot: bool, optional
        Whether to show the result as a plot.
    solver: str, optional
        Solver type. Choose one from 'ode', 'gillespie', 'lattice', 'meso',
        'bd' and 'egfrd'.
    factory: Factory, optional
    is_netfree: bool, optional
        Whether the model is netfree or not. When a model is given as an
        argument, just ignored.
    as_observer: bool, optional
        Return an Observer, but not an array.
    """
    import ecell4

    if factory is not None:
        f = factory
    elif solver == 'ode':
        f = ecell4.ode.ODEFactory()
    elif solver == 'gillespie':
        f = ecell4.gillespie.GillespieFactory()
    elif solver == 'lattice':
        f = ecell4.lattice.LatticeFactory()
    elif solver == 'meso':
        f = ecell4.meso.MesoscopicFactory()
    elif solver == 'bd':
        f = ecell4.bd.BDFactory()
    elif solver == 'egfrd':
        f = ecell4.egfrd.EGFRDFactory()
    else:
        raise ValueError(
            'unknown solver name was given: ' + repr(solver)
            + '. use ode, gillespie, lattice, meso, bd or egfrd')

    L = ecell4.cbrt(volume)

    if model is None:
        model = ecell4.util.decorator.get_model(is_netfree, True)

    edge_lengths = ecell4.Real3(L, L, L)
    w = f.create_world(edge_lengths)
    w.bind_to(model)
    for serial, n in y0.items():
        w.add_molecules(ecell4.Species(serial), n)

    if species_list is None:
        seeds = [ecell4.Species(serial) for serial in y0.keys()]
        species_list = [
            sp.serial() for sp in model.expand(seeds).list_species()]

    obs = ecell4.TimingNumberObserver(t, species_list)
    sim = f.create_simulator(w)
    sim.run(t[-1], obs)

    if with_plot:
        ecell4.viz.plot_number_observer(obs)

    if as_observer:
        return obs

    return obs.data()