Пример #1
0
 def simulate(self, timepoints, **kwargs):
     ''' 
     To simulate using bioscrape.
     '''
     type = kwargs.get('type')
     species_to_plot = kwargs.get('species_to_plot')
     plot_show = kwargs.get('plot_show')
     if not plot_show:
         plot_show = False
     if self.M:
         # If bioscrape model
         M = self.M
         s = ModelCSimInterface(M)
         if type == 'deterministic':
             s.py_prep_deterministic_simulation()
             s.py_set_initial_time(timepoints[0])
             sim = DeterministicSimulator()
             result = sim.py_simulate(s, timepoints)
             result = result.py_get_result()
             if plot_show:
                 for species in species_to_plot:
                     ind = M.get_species_index(species)
                     plt.plot(timepoints, result[:, ind])
                 plt.title(str(species_to_plot) + ' vs time')
                 plt.show()
             return result, M
         elif type == 'stochastic':
             warnings.warn(
                 'For stochastic simulation of SBML models using bioscrape, it is highly recommended to NOT use reversible reactions as the SSA algorithm might not work for such cases.'
             )
             sim = SSASimulator()
             s.py_set_initial_time(timepoints[0])
             result = sim.py_simulate(s, timepoints)
             result = result.py_get_result()
             if plot_show:
                 for species in species_to_plot:
                     ind = M.get_species_index(species)
                     plt.plot(timepoints, result[:, ind])
                 plt.title(str(species_to_plot) + ' vs time')
                 plt.show()
             return result, M
         else:
             raise ValueError(
                 'Optional argument "type" must be either deterministic or stochastic'
             )
     else:
         raise ValueError('Model not found')
Пример #2
0
from bioscrape.simulator import ModelCSimInterface

# Load the model by creating a model with the file name containing the model
m = Model('models/sbml_to_txt.xml')
# Expose the model's core characteristics for simulation. (i.e. stoichiometry,
# delays, and propensities)
s = ModelCSimInterface(m)

# Set the initial simulation time
s.py_set_initial_time(0)

# This function uses sparsity to further optimize the speed of deterministic
# simulations. You must call it before doing deterministic simulations.
s.py_prep_deterministic_simulation()

det_simulator = DeterministicSimulator()
# Set up our desired timepoints for which to simulate.
# Must match with initial time.
timepoints = np.linspace(0, 14 * 60 * 60, 100)
result = det_simulator.py_simulate(s, timepoints)
ListOfSpeciesToPlot = [
    'mw877e5da9_7092_45a9_a813_ef218b4c657d_B1',
    'mwf2ce0d3a_c24a_40e1_97ae_5d8239face0e_A1', 'protein_tetRdimer_combined'
]
species_ind = []
for species in ListOfSpeciesToPlot:
    species_ind.append(m.get_species_index(species))

for i in range(len(species_ind)):
    plt.plot(timepoints, result.py_get_result()[:, species_ind[i]])
    def __init__(self, parameters=None):
        super(Bioscrape, self).__init__(parameters)

        # get the parameters out of self.parameters if available, or use defaults
        if 'sbml_file' not in self.parameters and 'bioscrape_model' not in self.parameters:
            raise ValueError(
                "Bioscrape Process requires either an sbml_file or bioscrape_model parameter."
            )
        elif 'sbml_file' not in self.parameters and isinstance(
                self.parameters['bioscrape_model'], Model):
            # load the sbml file to create the model
            self.sbml_file = None
            self.model = self.parameters['bioscrape_model']
        elif isinstance(self.parameters['sbml_file'],
                        str) and 'bioscrape_model' not in self.parameters:
            self.sbml_file = self.parameters['sbml_file']
            if self.parameters["lineage"]:
                self.model = LineageModel(sbml_filename=self.sbml_file, )
            else:
                self.model = Model(sbml_filename=self.sbml_file,
                                   sbml_warnings=False)
        elif isinstance(self.parameters['sbml_file'], str) and isinstance(
                self.parameters['bioscrape_model'], Model):
            raise ValueError(
                "Bioscrape recieved an sbml_file and a bioscrape_model. Please use one or the other."
            )
        else:
            raise ValueError(
                f"Bioscrape did not recieve a valid bioscrape_model "
                f"(recieved: {self.parameters['bioscrape_model']} or a "
                f"valid sbml_file (recieved: {self.parameters['sbml_file']}).")

        self.internal_dt = self.parameters['internal_dt']
        self.stochastic = self.parameters['stochastic']

        #Toggle using Lineage Model
        if self.parameters["lineage"]:
            if not self.stochastic:
                raise ValueError(
                    "Bioscrape lineage only available with stochastic = True")
            self.simulator = LineageSSASimulator()
            self.interface = LineageCSimInterface(self.model)
            self.volume = LineageVolumeCellState(
            )  #Create an internal bioscrape Volume
        #Otherwise use normal bioscrape models
        else:
            # create the interface
            if self.parameters["safe_mode"]:
                self.interface = SafeModelCSimInterface(
                    self.model, max_species_count=10**8)
            else:
                self.interface = ModelCSimInterface(self.model)

            #Stochastic
            if self.stochastic:
                self.simulator = VolumeSSASimulator()
            #Not Stochastic
            elif not self.stochastic:
                self.interface.py_prep_deterministic_simulation()
                # create a Simulator
                self.simulator = DeterministicSimulator()
            self.volume = Volume()  #Create an internal bioscrape Volume

        #Set dt
        self.interface.py_set_dt(self.internal_dt)
        #Set the volume
        self.volume.py_set_volume(self.parameters['initial_volume'])
class Bioscrape(Process):
    '''
    This process provides a wrapper around a bioscrape model, interface, and simulator.
    It allows for stochastic or determinstic simulation, variable volume, and generates ports
    to access all bioscrape species and rate parameters.
    '''

    # give the process a name, so that it can register in the process_repository
    name = NAME

    # declare default parameters as class variables
    defaults = {
        'internal_dt': 0.01,
        'stochastic': False,
        'initial_volume': 1.0,
        'safe_mode': False,
        'lineage': False
    }

    def __init__(self, parameters=None):
        super(Bioscrape, self).__init__(parameters)

        # get the parameters out of self.parameters if available, or use defaults
        if 'sbml_file' not in self.parameters and 'bioscrape_model' not in self.parameters:
            raise ValueError(
                "Bioscrape Process requires either an sbml_file or bioscrape_model parameter."
            )
        elif 'sbml_file' not in self.parameters and isinstance(
                self.parameters['bioscrape_model'], Model):
            # load the sbml file to create the model
            self.sbml_file = None
            self.model = self.parameters['bioscrape_model']
        elif isinstance(self.parameters['sbml_file'],
                        str) and 'bioscrape_model' not in self.parameters:
            self.sbml_file = self.parameters['sbml_file']
            if self.parameters["lineage"]:
                self.model = LineageModel(sbml_filename=self.sbml_file, )
            else:
                self.model = Model(sbml_filename=self.sbml_file,
                                   sbml_warnings=False)
        elif isinstance(self.parameters['sbml_file'], str) and isinstance(
                self.parameters['bioscrape_model'], Model):
            raise ValueError(
                "Bioscrape recieved an sbml_file and a bioscrape_model. Please use one or the other."
            )
        else:
            raise ValueError(
                f"Bioscrape did not recieve a valid bioscrape_model "
                f"(recieved: {self.parameters['bioscrape_model']} or a "
                f"valid sbml_file (recieved: {self.parameters['sbml_file']}).")

        self.internal_dt = self.parameters['internal_dt']
        self.stochastic = self.parameters['stochastic']

        #Toggle using Lineage Model
        if self.parameters["lineage"]:
            if not self.stochastic:
                raise ValueError(
                    "Bioscrape lineage only available with stochastic = True")
            self.simulator = LineageSSASimulator()
            self.interface = LineageCSimInterface(self.model)
            self.volume = LineageVolumeCellState(
            )  #Create an internal bioscrape Volume
        #Otherwise use normal bioscrape models
        else:
            # create the interface
            if self.parameters["safe_mode"]:
                self.interface = SafeModelCSimInterface(
                    self.model, max_species_count=10**8)
            else:
                self.interface = ModelCSimInterface(self.model)

            #Stochastic
            if self.stochastic:
                self.simulator = VolumeSSASimulator()
            #Not Stochastic
            elif not self.stochastic:
                self.interface.py_prep_deterministic_simulation()
                # create a Simulator
                self.simulator = DeterministicSimulator()
            self.volume = Volume()  #Create an internal bioscrape Volume

        #Set dt
        self.interface.py_set_dt(self.internal_dt)
        #Set the volume
        self.volume.py_set_volume(self.parameters['initial_volume'])

    def get_species_names(self):
        #Gets the names of teh species in a bioscrape model
        model_species = self.model.get_species_dictionary()
        return list(model_species.keys())

    def get_state(self, array):
        #Gets the state of a bioscrape simulation
        mapping = self.model.get_species2index()

        return {species: array[index] for species, index in mapping.items()}

    def initial_state(self, config=None):
        #gets the current (or initial) state of a bioscrape simulation.
        if config is None:
            config = {}
        self.model.set_species(config)
        state = self.model.get_species_array()
        return {'species': self.get_state(state)}

    def ports_schema(self):
        '''
        ports_schema returns a dictionary that declares how each state will behave.
        Each key can be assigned settings for the schema_keys declared in Store:

        * `_default`
        * `_updater`
        * `_divider`
        * `_value`
        * `_properties`
        * `_emit`
        * `_serializer`
        '''

        #Different divide settings between stochastic and determinsitic CRNs
        if self.stochastic:
            divider = "binomial"
        else:
            divider = "set"  #division does not change concentrations

        return {
            'species': {
                species: {
                    '_default': 0.0,
                    '_updater': 'accumulate',
                    '_emit': True,
                    '_divider': divider
                }
                for species in self.model.get_species()
            },
            'delta_species': {
                species: {
                    '_default': 0.0,
                    '_updater': 'set',
                    '_emit': False
                }
                for species in self.model.get_species()
            },
            'rates': {
                p: {
                    '_default': self.model.get_parameter_dictionary()[p],
                    '_updater': 'set',
                }
                for p in self.model.get_param_list()
            },
            'globals': {
                'volume': {
                    '_default': self.parameters['initial_volume'],
                    '_updater': 'accumulate',
                    '_emit': True
                }
            }
        }

    def next_update(self, timestep, states):
        if 'species' in states:
            self.model.set_species(states['species'])
            self.interface.py_set_initial_state(self.model.get_species_array())
        if 'rates' in states:
            self.model.set_params(states['rates'])

        #Set Volume if needed
        if 'volume' in states:
            self.volume.py_set_volume(states['globals']['volume'])

        # create the interface

        timepoints = np.arange(0, timestep, self.internal_dt)
        if self.parameters["lineage"]:
            output = self.simulator.py_SimulateSingleCell(
                timepoints,
                Model=self.model,
                interface=self.interface,
                v=self.volume)
        elif self.stochastic:
            output = self.simulator.py_volume_simulate(self.interface,
                                                       self.volume, timepoints)
        else:
            output = self.simulator.py_simulate(self.interface, timepoints)

        result = output.py_get_result()[-1]
        result_state = self.get_state(result)
        delta = get_delta(states['species'], result_state)
        rates = self.model.get_parameter_dictionary()

        #If the simulation is a volume simulation, return the change in volume
        if getattr(output, "py_get_volume", None) is not None:
            Vi = output.py_get_volume()[0]
            Vf = output.py_get_volume()[-1]
            deltaV = Vf - Vi
        else:
            deltaV = 0

        return {
            'species': delta,
            'delta_species': delta,
            'rates': rates,
            'globals': {
                'volume': deltaV
            }
        }

    def get_model(self):
        return self.model

    def get_model_species(self):
        return self.model.get_species_dictionary()

    def get_model_species_ids(self):
        return list(self.model.get_species_dictionary().keys())

    def get_volume(self):
        return self.volume.py_get_volume()