def compareModels(sbmlModel, antModel):
    '''
    This code needs to be rewritten.
    '''

    import roadrunner, pylab, antimony

    sbmlModel = "00001-sbml-l2v4.xml"
    antModel = sbmlModel.replace(sbmlModel[-3:], "ant")

    # Make a round trip to and from Antimony
    antimony.loadSBMLFile(sbmlModel)
    antimony.writeAntimonyFile(antModel, antimony.getModuleNames()[1])
    antimony.loadAntimonyFile(antModel)
    antimony.writeSBMLFile("test.xml", antimony.getModuleNames()[1])

    rr1 = roadrunner.RoadRunner(sbmlModel)
    rr2 = roadrunner.RoadRunner("test.xml")

    result1 = rr1.simulate(0, 10, 101)
    result2 = rr2.simulate(0, 10, 101)

    result = result1 - result2

    pylab.plot(result[:, 0], result[:, 1:])

    pylab.show()
    def fitness(self, x):
        if self.rr is None:
            self.rr = roadrunner.RoadRunner(self.sbml)

        # Reset road runner for a new simulation
        self.rr.resetToOrigin()

        # Set the parameter values
        self.rr.vs = x[0]
        self.rr.vm = x[1]
        self.rr.Km = x[2]
        self.rr.KI = x[3]
        self.rr.n  = x[4]
        self.rr.ks = x[5]
        self.rr.vd = x[6]
        self.rr.Kd = x[7]
        self.rr.k1 = x[8]
        self.rr.k2 = x[9]

        # Run road runner
        self.rr.timeCourseSelections = ['time', 'M', 'FC', 'FN']
        result = self.rr.simulate(0, 96, 97)

        # Compare simulation result with experiment data for all three
        # species from hour 48 onwards
        sum_of_squares_error = np.sum(np.square(np.array(result[48:, 1:])-self.experimentData))

        # Nmmso finds the maximum so need to negate the sum of squares error
        return -sum_of_squares_error
Ejemplo n.º 3
0
def timeit(name, path, loadTimeCap, runTimeCap):
  print('Model: {}'.format(name), file=stderr)
  startTime = time.time()
  global regDetected
  passFail = 'pass'

  # Load the model
  r=roadrunner.RoadRunner(path)

  # use these settings for consistent performance
  r.getIntegrator().setValue('relative_tolerance', rel_tol_default)
  r.getIntegrator().setValue('absolute_tolerance', absolute_tol_default)
  r.getIntegrator().setValue('stiff', False)

  loadTime = time.time()
  if loadTime-startTime > loadTimeCap:
    regDetected = True
    passFail = '***FAIL***'

  m=r.simulate(start, end, steps)
  endTime = time.time()
  if endTime-loadTime > runTimeCap:
    regDetected = True
    passFail = '***FAIL***'

  csvwriter.writerow([name, formatTime(loadTime-startTime), formatTime(endTime-loadTime), formatTime(endTime-startTime), passFail])
Ejemplo n.º 4
0
    def simulator(self, model):
        try:
            import roadrunner as rr

            self._simulator = rr.RoadRunner(model)
        except ImportError:
            print("libroadrunner is not installed!")
Ejemplo n.º 5
0
 def setup_model(cls,
                 model_file,
                 inputs=[],
                 outputs=[],
                 integrator=None,
                 integrator_settings={}):
     r"""Set up model class instance."""
     import roadrunner
     from yggdrasil.languages.Python.YggInterface import (YggInput,
                                                          YggOutput)
     model = roadrunner.RoadRunner(model_file)
     if integrator is not None:
         model.setIntegrator(integrator)
     for k, v in integrator_settings.items():
         model.getIntegrator().setValue(k, v)
     input_map = {}
     output_map = {}
     for x in inputs:
         input_map[x['name']] = {
             'vars': x.get('vars', []),
             'comm': YggInput(x['name'], new_process=True)
         }
     for x in outputs:
         output_map[x['name']] = {
             'as_array': x.get('as_array', False),
             'vars': x.get('vars', []),
             'comm': YggOutput(x['name'], new_process=True)
         }
     return model, input_map, output_map
Ejemplo n.º 6
0
 def __init__(self, string, sbml=None):
     super().__init__()
     self.knownatts.add("doc")
     self.knownatts.add("rr")
     self.knownatts.add("outputVariables")
     self.knownatts.add("rr_default_int")
     self.outputVariables = ['time']
     print("This is the constructor method.")
     if isfile(string):
         super().__setattr__("doc", tesbml.readSBMLFromFile(string))
         if self.doc.getModel() == None:
             raise Exception("No SBML model present at '" + string + "'.")
     elif sbml is not None:
         self.doc = sbml.clone()
     else:
         self.doc = tesbml.readSBMLFromString(string)
         if self.doc.getModel() == None:
             raise Exception(
                 "Unable to parse string as an SBML model, or file not found."
             )
     self.rr = roadrunner.RoadRunner(self.doc.toSBML())
     self.rr_default_int = self.rr.getIntegrator().getName()
     self.saveModelElements()
     self.saveRRElements()
     self['time'] = 0
def loada(sbstr):
    import antimony as sb
    r = sb.loadAntimonyString(sbstr)
    if r < 0:
        raise RuntimeError('Failed to load Antimony model: {}'.format(
            sb.getLastError()))
    return roadrunner.RoadRunner(sb.getSBMLString(sb.getModuleNames()[-1]))
def main():

    # Obtain SBML model from Biomodels and populate Road Runner
    model = urllib.request.urlopen('http://www.ebi.ac.uk/biomodels-main/download?mid=BIOMD0000000299')
    sbml = model.read().decode('utf-8')
    rr = roadrunner.RoadRunner(sbml)

    # Run the simulation and produce some fake experiment data.  If you have
    # actual experiment data you will not need to run this simulation.
    rr.resetToOrigin()
    rr.timeCourseSelections = ['time', 'M', 'FC', 'FN']
    fake_experiment_data = rr.simulate(0, 96, 97)

    # Reduce the experiment data to be the data from 48 hours
    # onwards when limit cycle has been reached and remove the
    # time from the experiment data
    fake_experiment_data = np.array(fake_experiment_data[48:, 1:])

    # Now run NMMSO to find the modes
    nmmso = Nmmso(UniformRangeProblem(SbmlModelProblem(sbml, fake_experiment_data)), 10)
    nmmso.add_listener(TraceListener(1))
    my_result = nmmso.run(50000)

    for mode_result in my_result:
        print("Mode at {} has value {}".format(mode_result.location, mode_result.value))
Ejemplo n.º 9
0
def load_model(info=True):
    """ Loads the latest model version. """
    path = model_path()
    logging.info(f'Model:{path}')
    r = roadrunner.RoadRunner(path)
    set_selections(r)
    return r
Ejemplo n.º 10
0
def example(model_id: str) -> None:
    """XPP example conversion."""
    # convert xpp to sbml
    xpp_dir = Path(__file__).parent / "xpp_example"
    out_dir = xpp_dir / "results"

    xpp_file = xpp_dir / f"{model_id}.ode"
    sbml_file = out_dir / f"{model_id}.xml"
    xpp.xpp2sbml(xpp_file=xpp_file, sbml_file=sbml_file)
    sbmlreport.create_report(sbml_file, output_dir=out_dir, validate=False)

    # test simulation
    r = roadrunner.RoadRunner(str(sbml_file))
    s = r.simulate(start=0, end=1000, steps=100)

    fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(14, 7))
    axes = (ax1, ax2)

    for ax in axes:
        for sid in r.timeCourseSelections[1:]:
            ax.plot(s["time"], s[sid], label=sid)
    ax2.set_yscale("log")
    for ax in axes:
        ax.set_ylabel("Value [?]")
        ax.set_xlabel("Time [?]")
        ax.legend()

    fig.savefig(out_dir / f"{model_id}.png", bbox_inches="tight")
Ejemplo n.º 11
0
def example(model_id):
    # convert xpp to sbml
    xpp_dir = "./xpp_example"
    out_dir = "./xpp_example/results"

    xpp_file = os.path.join(xpp_dir, "{}.ode".format(model_id))
    sbml_file = os.path.join(out_dir, "{}.xml".format(model_id))
    xpp.xpp2sbml(xpp_file=xpp_file, sbml_file=sbml_file)
    sbmlreport.create_report(sbml_file, target_dir=out_dir, validate=False)

    # test simulation
    r = roadrunner.RoadRunner(sbml_file)
    s = r.simulate(start=0, end=1000, steps=100)

    fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(14, 7))
    axes = (ax1, ax2)

    for ax in axes:
        for sid in r.timeCourseSelections[1:]:
            ax.plot(s["time"], s[sid], label=sid)
    ax2.set_yscale("log")
    for ax in axes:
        ax.set_ylabel("Value [?]")
        ax.set_xlabel("Time [?]")
        ax.legend()

    fig.savefig(os.path.join(out_dir, "{}.png".format(model_id)), bbox_inches="tight")
Ejemplo n.º 12
0
    def _process_models(self):
        """ Process and prepare models for simulation.

        Resolves the replacements and model couplings between the
        different frameworks and creates models which can be simulated with
        the different frameworks.

        An important step is finding the fba rules in the top model.

        :return:
        :rtype:
        """
        logging.debug('* _process_models')
        ###########################
        # FBA rules
        ###########################
        # process FBA assignment rules of the top model
        self.flux_rules = DFBAModel._process_flux_rules(self.model_top)

        ###########################
        # ODE model
        ###########################
        # the roadrunner ode file is the flattened comp file.
        # FBA parts do not change any of the kinetic subparts (only connections via replaced bounds
        # and fluxes).
        # Consequently, the ODE part can be solved as is, only the iterative update between ode and fba has
        # to be performed

        # remove FBA assignment rules from the model, so they can be set via the simulator
        # not allowed to set assignment rules directly in roadrunner
        for variable in self.flux_rules.values():
            self.model_top.removeRuleByVariable(variable)

        mixed_sbml_cleaned = tempfile.NamedTemporaryFile("w", suffix=".xml")
        libsbml.writeSBMLToFile(self.doc_top, mixed_sbml_cleaned.name)
        self.rr_comp = roadrunner.RoadRunner(mixed_sbml_cleaned.name)

        ###########################
        # prepare FBA models
        ###########################
        # FBA models are found based on the FBA modeling framework
        mdoc = self.doc_top.getPlugin("comp")
        for submodel in self.submodels[builder.MODEL_FRAMEWORK_FBA]:
            mref = submodel.getModelRef()
            emd = mdoc.getExternalModelDefinition(mref)
            source = emd.getSource()
            # check if relative path
            if not os.path.exists(source):
                s2 = os.path.join(self.sbml_dir, source)
                if not os.path.exists(s2):
                    warnings.warn('FBA source cannot be resolved:' + source)
                else:
                    source = s2

            # Create FBA model and process
            fba_model = FBAModel(submodel=submodel,
                                 source=source,
                                 model_top=self.model_top)
            self.fba_models.append(fba_model)
Ejemplo n.º 13
0
def getRoadRunner(resource):
    """
    return a RoadRunner instance loaded with one of the test files.
    """
    data = pkgutil.get_data(__name__, resource)
    r = roadrunner.RoadRunner()
    r.load(data)
    return r
Ejemplo n.º 14
0
    def diffplot(self):
        """
        Run the SBML test. Returns True or False depending on if the test passes or not. 
        If the test fails, any errors will be available in the SBMLTest.errors property.
        """

        import matplotlib.pyplot as plt

        self.errors = []
        result = True

        try:
            # run the simulation

            plt.figure(1)

            r = rr.RoadRunner(self.sbmlFileName, _getLoadOptions())

            # need to tweak the tolerances for the current integrator
            opt = self.settings.copy()
            opt.tweakTolerances()
            opt.structuredResult = True

            plt.subplot(211)
            r.simulate(opt, plot=True, show=False)
            plt.xlim([0, opt.duration])

            r = rr.RoadRunner(self.sbmlFileName, _getLoadOptions())

            # need to tweak the tolerances for the current integrator
            opt = self.settings.copy()
            opt.tweakTolerances()
            opt.variableStep = True
            opt.structuredResult = True

            plt.subplot(212)
            r.simulate(opt, plot=True, show=False)
            plt.xlim([0, opt.duration])

            plt.show()

        except Exception as e:
            result = False
            self._addError(str(e))

        return result
Ejemplo n.º 15
0
def load_model(sbml):
    '''
    Load an SBML file in roadrunner
    '''
    print 'Loading :', sbml
    start = time.clock()
    r = roadrunner.RoadRunner(sbml)
    print 'SBML Rules load :', (time.clock() - start)
    return r
def loadSBMLModel(sbml):
    """ Load SBML model from a string or file.

    :param sbml: SBML model
    :type sbml: str | file
    :returns: RoadRunner instance with model loaded
    :rtype: roadrunner.RoadRunner
    """
    return roadrunner.RoadRunner(sbml)
Ejemplo n.º 17
0
def loadSBMLModel(sbml):
    """Load SBML model with tellurium

    :param sbml: SBML model
    :type sbml: str | file
    :returns: RoadRunner instance with model loaded
    :rtype: roadrunner.RoadRunner
    """
    return roadrunner.RoadRunner(sbml)
Ejemplo n.º 18
0
 def simulate(self, tstart, tend, nsteps):
     rr = roadrunner.RoadRunner(self.toSBML());
     pop_tags = sorted(self.strains.keys());
     selections = ['time'];
     for i in range(len(self.strains)):
         selections.append('N_' + pop_tags[i]);
     rr.timeCourseSelections = selections;
     result = rr.simulate(tstart, tend, nsteps);
     return result;
Ejemplo n.º 19
0
def load_model(info=True):
    """ Loads the latest model version. """

    model_path = get_model_path()
    if info:
        print('Model:', model_path)

    r = roadrunner.RoadRunner(model_path)
    set_selections(r)
    return r
def loadCellMLModel(cellml):
    """ Load CellML model with tellurium.

    :param cellml: CellML model
    :type cellml: str | file
    :returns: RoadRunner instance with model loaded
    :rtype: roadrunner.RoadRunner
    """
    sbml = cellmlToSBML(cellml)
    return roadrunner.RoadRunner(sbml)
Ejemplo n.º 21
0
def test_fixed_step_simulation() -> None:
    rr = roadrunner.RoadRunner(str(DEMO_SBML))
    tend = 10.0
    steps = 100
    s = rr.simulate(start=0, end=tend, steps=steps)

    # test end point reached
    assert s[-1, 0] == 10
    # test correct number of steps
    assert len(s["time"]) == steps + 1
Ejemplo n.º 22
0
 def pass_to_roadrunner(self):
     """
     Warning, this function crashes Python
     :return:
     """
     import roadrunner # note: this causes RoadRunner::regenerate to crash if imported at top level!
     rr = roadrunner.RoadRunner()
     # passes ownership of the roadrunner model in self._obj to roadrunner
     rr.setModel(self._obj)
     return rr
Ejemplo n.º 23
0
def getRoadRunner(resource):
    """
    return a RoadRunner instance loaded with one of the test files.
    """
    data = pkgutil.get_data(__name__, resource)
    r = roadrunner.RoadRunner()
    if sys.version_info[0] < 3:
        r.load(data)
    else:
        r.load(data.decode())
    return r
Ejemplo n.º 24
0
def test_fixed_step_simulation():
    rr = roadrunner.RoadRunner(data.GALACTOSE_SINGLECELL_SBML)

    tend = 10.0
    steps = 100
    s = rr.simulate(start=0, end=tend, steps=steps)

    # test end point reached
    assert s[-1, 0] == 10
    # test correct number of steps
    assert len(s['time']) == steps + 1
Ejemplo n.º 25
0
def load_model(path, selections: List[str] = None) -> roadrunner.RoadRunner:
    """ Loads the latest model version.

    :param path: path to SBML model or SBML string
    :param selections: boolean flag to set selections
    :return: roadrunner instance
    """
    logging.info("Loading: '{}'".format(path))
    r = roadrunner.RoadRunner(path)
    set_timecourse_selections(r, selections)
    return r
Ejemplo n.º 26
0
def testEvents(fileName):
    r = roadrunner.RoadRunner(fileName)

    eventIds = r.model.getEventIds()

    for eid in eventIds:
        e = r.model.getEvent(eid)
        e.setOnTrigger(onEventTrigger)
        e.setOnAssignment(onEventAssignment)

    r.simulate()
def loadAntimonyModel(ant):
    """Load Antimony model with tellurium.

    See also: :func:`loada`

    :param ant: Antimony model
    :type ant: str | file
    :returns: RoadRunner instance with model loaded
    :rtype: roadrunner.RoadRunner
    """
    sbml = antimonyToSBML(ant)
    return roadrunner.RoadRunner(sbml)
Ejemplo n.º 28
0
def test_result():
    r = roadrunner.RoadRunner(MODEL_REPRESSILATOR)
    dfs = []
    for _ in range(10):
        s = r.simulate(0, 10, steps=10)
        dfs.append(pd.DataFrame(s, columns=s.colnames))

    result = Result(dfs)
    assert result
    assert result.nframes == 10
    assert result.nrow == 11
    assert result.data is not None
Ejemplo n.º 29
0
def load_model(model_path, timeCourseSelections=True):
    """ Loads model and sets selections.

    :param model_path:
    :param set_selections boolean flag if timeCourseSelections are set on model.
    :return:
    """
    logging.info('Model:', model_path)
    r = roadrunner.RoadRunner(model_path)
    if timeCourseSelections:
        set_selections(r)
    return r
Ejemplo n.º 30
0
def run_models_roadrunner(model_paths: List[Path],
                          output_dir: Path) -> pd.DataFrame:
    """ODE optimization for all given models."""
    results = []
    n_models = len(model_paths)
    for k, path in enumerate(model_paths):
        model_id = path.stem
        try:
            # load model
            start_time = time.time()
            rr: roadrunner.RoadRunner = roadrunner.RoadRunner(str(path))
            load_time = time.time() - start_time  # [s]

            model: roadrunner.ExecutableModel = rr.model
            # set tolerances
            integrator: roadrunner.Integrator = rr.integrator
            integrator.setValue("absolute_tolerance", ABSOLUTE_TOLERANCE)
            integrator.setValue("relative_tolerance", RELATIVE_TOLERANCE)

            # set selections
            rr.selections = [
                "time"
            ] + model.getFloatingSpeciesIds() + model.getBoundarySpeciesIds()

            # run optimization
            start_time = time.time()
            s = rr.simulate(start=START, end=END, steps=STEPS)
            simulate_time = time.time() - start_time  # [s]

            # filter models with delay
            if model_id in [
                    "BIOMD0000000024", "BIOMD0000000025", "BIOMD0000000034"
            ]:
                raise RuntimeError("delays not supported")
            status = "success"
        except (RuntimeError) as err:
            print(f"ERROR in '{model_id}'", err)
            simulate_time = np.NaN
            status = "failure"

        # store result
        df = pd.DataFrame(s, columns=s.colnames)
        df.to_csv(output_dir / f"{model_id}.tsv", sep="\t", index=False)
        res = (model_id, status, load_time, simulate_time)
        results.append(res)

        print("[{}/{}]".format(k, n_models), res)

    df = pd.DataFrame(data=results,
                      columns=("model", "status", "load_time",
                               "simulate_time"))
    return df