def copy_sbml_simulators(self, from_cell: object, to_cell: object, sbml_names: Union[list, None] = None,
                             options: Union[dict, None] = None):
        """
        Copies SBML solvers (with their states - effectively clones the solver) from one cell to another
        :param from_cell: source CellG cell
        :param to_cell: target CellG cell
        :param sbml_names: list of SBML model name whose solver are to be copied
        :param options: - deprecated - list of SBML solver options
        :return: None
        """
        sbml_names = self.__default_mutable_type(sbml_names, [])
        options = self.__default_mutable_type(options, {})

        sbml_names_to_copy = []
        if not (len(sbml_names)):
            # if user does not specify _sbmlNames we copy all SBML networks
            try:
                dict_attrib = CompuCell.getPyAttrib(from_cell)
                sbml_dict = dict_attrib['SBMLSolver']
                sbml_names_to_copy = list(sbml_dict.keys())
            except LookupError as e:
                pass
        else:
            sbml_names_to_copy = sbml_names

        try:
            dict_attrib_from = CompuCell.getPyAttrib(from_cell)
            sbml_dict_from = dict_attrib_from['SBMLSolver']
        except LookupError:
            return

        try:
            dict_attrib_to = CompuCell.getPyAttrib(to_cell)
            # sbml_dict_to = dict_attrib_to['SBMLSolver']
        except LookupError:
            pass
            # if _toCell does not have SBMLSolver dictionary entry we simply add it
            # dict_attrib_to['SBMLSolver'] = {}
            # sbml_dict_to = dict_attrib_to['SBMLSolver']

        for sbml_name in sbml_names_to_copy:
            rr_from = sbml_dict_from[sbml_name]
            current_state_sbml = sbml_dict_from[sbml_name].getCurrentSBML()
            self.add_sbml_to_cell(
                model_file=rr_from.path,  # necessary to get deserialization working properly
                model_name=sbml_name,
                cell=to_cell,
                step_size=rr_from.stepSize,
                options=options,
                current_state_sbml=current_state_sbml
            )
    def delete_sbml_from_cell_ids(self, model_name: str, cell_ids: Union[None, list] = None) -> None:
        """
        Deletes  SBML model from cells whose ids match those stered int he _ids list
        :param model_name: model name
        :param cell_ids: list of cell ids
        :return:
        """
        """

        :param _modelName {str}: 
        :param _ids {list}: 
        :return: None
        """
        cell_ids = self.__default_mutable_type(cell_ids, [])

        for cell_id in cell_ids:
            cell = self.inventory.attemptFetchingCellById(cell_id)
            if not cell:
                continue

            dict_attrib = CompuCell.getPyAttrib(cell)
            try:
                sbml_dict = dict_attrib['SBMLSolver']
                del sbml_dict[model_name]
            except LookupError as e:
                pass
def step_sbml_model_cell(cell, sbml_model_name=vr_model_name):
    """
    Steps SBML model for a cell
    :param cell: cell with a SBML model to step
    :param sbml_model_name: name of SBML model to step
    :return: None
    """
    dict_attrib = CompuCell.getPyAttrib(cell)
    assert 'SBMLSolver' in dict_attrib
    dict_attrib['SBMLSolver'][sbml_model_name].timestep()
    def delete_sbml_from_cell(self, model_name: str = '', cell: object = None) -> None:
        """
        Deletes SBML from a particular cell
        :param model_name: model name
        :param cell: CellG cell obj
        :return: None
        """

        dict_attrib = CompuCell.getPyAttrib(cell)
        try:
            sbml_dict = dict_attrib['SBMLSolver']
            del sbml_dict[model_name]
        except LookupError:
            pass
    def timestep_cell_sbml(self):
        """
        advances (integrats forward) models stored as attributes of cells
        :return: None
        """

        # time-stepping SBML attached to cells
        for cell in self.cellList:
            dict_attrib = CompuCell.getPyAttrib(cell)
            if 'SBMLSolver' in dict_attrib:
                sbml_dict = dict_attrib['SBMLSolver']

                for model_name, rrTmp in sbml_dict.items():
                    # integrating SBML
                    rrTmp.timestep()
    def set_step_size_for_cell(self, model_name: str = '', cell: object = None, step_size: float = 1.0):
        """
        Sets integration step size for SBML model attached to _cell

        :param model_name: model name
        :param cell: CellG cell object
        :param step_size: integration step size
        :return: None
        """
        dict_attrib = CompuCell.getPyAttrib(cell)

        try:
            sbmlSolver = dict_attrib['SBMLSolver'][model_name]
        except LookupError:
            return

        sbmlSolver.stepSize = step_size
Exemple #7
0
    def timestep_model(self, model_name: str):
        """
        Integrate an ode model one step in time.

        :param model_name: name of the ode model
        :return: None
        """
        if model_name not in self.model_names:
            raise ValueError('Model not registered:', model_name)
        o = self._ode_models[model_name]
        if o.cell_types is None:
            from cc3d.CompuCellSetup import persistent_globals as pg
            pg.free_floating_sbml_simulators[model_name].timestep()
        else:
            for cell in self.cell_list_by_type(
                    *self.cell_types_by_model(model_name)):
                dict_attrib = CompuCell.getPyAttrib(cell)
                dict_attrib['SBMLSolver'][model_name].timestep()
    def get_sbml_simulator(self, model_name: str, cell: object = None) -> Union[object, None]:
        """
        Returns a reference to RoadRunnerPy or None
        :param model_name: model name
        :param cell: CellG cell object
        :return {instance of RoadRunnerPy} or {None}:
        """

        pg = CompuCellSetup.persistent_globals
        if not cell:
            try:

                return pg.free_floating_sbml_simulators[model_name]

            except LookupError:
                return None
        else:
            try:
                dict_attrib = CompuCell.getPyAttrib(cell)
                return dict_attrib['SBMLSolver'][model_name]
            except LookupError:
                return None
    def delete_sbml_from_cell_types(self, model_name: str, cell_types: Union[None, list] = None) -> None:
        """
        Deletes  SBML model from cells whose type match those stered in the cell_types list
        :param model_name: model name
        :param cell_types: list of cell cell types
        :return:
        """
        """

        :param _modelName {str}: 
        :param types: 
        :return: None

        """
        cell_types = self.__default_mutable_type(cell_types, [])

        for cell in self.cellListByType(*cell_types):
            dict_attrib = CompuCell.getPyAttrib(cell)
            try:
                sbml_dict = dict_attrib['SBMLSolver']
                del sbml_dict[model_name]
            except LookupError:
                pass
    def add_sbml_to_cell(self, model_file: str = '', model_string: str = '', model_name: str = '', cell: object = None,
                         step_size: float = 1.0,
                         initial_conditions: Union[None, dict] = None, options: Union[None, dict] = None,
                         current_state_sbml: object = None) -> None:
        """
        Attaches RoadRunner SBML solver to a particular cell. The sbml solver is stored as an element
        of the cell's dictionary - cell.dict['SBMLSolver'][_modelName]. The function has a dual operation mode.
        When user provides current_state_sbml, cell model_name, step_size the add_sbml_to_cell function creates a clone
        of a solver whose state is described by the current_state_sbml . If current_state_sbml is None
        then the new SBML solver
        is being created,  SBML file (model_file) or string (model_string) loaded and initial conditions are applied.
        It is important to always set
        ste_size to make sure that after calling timestep() fcn the solver advances appropriate delta time

        :param model_file: name of the SBML file - can be relative path (e.g. Simulation/file.sbml) or absolute path

        :param model_string: string of SBML file

        :param model_name: name of the model - this is a label used to store mode in the cell.dict['SBMLSolver']
        dictionary

        :param cell: {CellG object} cc3d cell object

        :param step_size:  time step- determines how much in "real" time units timestep() fcn advances SBML solver

        :param initial_conditions: initial conditions dictionary

        :param options: dictionary that currently only defines what type of ODE solver to choose.
        In the newer versions of RR this might be not necessary. The keys that are supported are the following:

        :param current_state_sbml:  string representation  of the SBML representing current state of the solver.

        :return: None
        """

        initial_conditions = self.__default_mutable_type(initial_conditions, {})
        options = self.__default_mutable_type(options, {})

        core_model_name = model_name
        if core_model_name == '':
            core_model_name, ext = os.path.splitext(os.path.basename(model_file))

        if model_string == '':
            if not model_file:
                warnings.warn('\n\n\n _modelFile argument not provided to addSBMLToCell. '
                              'This will prevent proper restart of the simulation'
                              'You may ignore this warning if you are not '
                              'serializing simulation for future restarts', RuntimeWarning)

            model_path_normalized = self.normalize_path(model_file)
        else:
            model_path_normalized = ''

        dict_attrib = CompuCell.getPyAttrib(cell)

        sbml_dict = {}
        if 'SBMLSolver' in dict_attrib:
            sbml_dict = dict_attrib['SBMLSolver']
        else:
            dict_attrib['SBMLSolver'] = sbml_dict

        if current_state_sbml is None:
            rr = RoadRunnerPy(_path=model_file, _modelString=model_string)
            # setting stepSize
            rr.stepSize = step_size
            # loading SBML and LLVM-ing it
            rr.loadSBML(_externalPath=model_path_normalized, _modelString=model_string)

        else:
            rr = RoadRunnerPy(sbml=current_state_sbml)
            # setting stepSize
            rr.stepSize = step_size

            # setting up paths - IMPORTANT FOR RESTARTING
            rr.path = model_file
            rr.modelString = model_string
            if os.path.exists(model_path_normalized):
                rr.absPath = model_path_normalized

        # storing rr instance in the cell dictionary
        sbml_dict[core_model_name] = rr

        # setting initial conditions - this has to be done after loadingSBML
        for name, value in initial_conditions.items():
            # have to catch exceptions in case initial conditions contain
            # "unsettable" entries such as reaction rate etc...
            try:
                rr.model[name] = value
            except:
                pass
                # we are turning off dynamic python properties because rr is not used in the interactive mode.
                # rr.options.disablePythonDynamicProperties = True

        # setting output results array size
        rr.selections = []  # by default we do not request any output array at each intergration step

        if options:
            for name, value in options.items():

                try:
                    setattr(rr.getIntegrator(), name, value)
                except AttributeError:
                    setattr(rr.getIntegrator(), self.option_name_dict[name], value)
        else:

            # check for global options

            global_options = self.get_sbml_global_options()
            if global_options:
                for name, value in global_options.items():
                    try:
                        setattr(rr.getIntegrator(), name, value)
                    except (AttributeError, ValueError):
                        setattr(rr.getIntegrator(), self.option_name_dict[name], value)