Ejemplo n.º 1
0
    private void AddModel <T>(out T instance) where T : CModelBase, new()
    {
        instance = new T();
        models.Add(instance);

        //自动注册所有的消息监听函数
        foreach (var method in typeof(T).GetMethods())
        {
            if (method.Name.StartsWith("OnSc"))
            {
                //获取到泛型
                var args = method.GetParameters()[1].ParameterType;

                List <Callback> calls;
                if (!msgRegister.TryGetValue(args, out calls))
                {
                    calls = new List <Callback>();
                    msgRegister.Add(args, calls);
                }
                calls.Add(new Callback(method, instance));
            }
        }
        instance.Init();

        if (instance.update != null && !updateList.Contains(instance.update))
        {
            updateList.Add(instance.update);
        }
    }
Ejemplo n.º 2
0
    public static void Main(String[] args)
    {
        if (args.Length == 0)
        {
            Console.WriteLine("Need one argument, copasi file");
            Environment.Exit(1);
        }

        CDataModel dataModel = CRootContainer.addDatamodel();

        if (!dataModel.loadModel(args[0]))
        {
            Console.WriteLine("Could not open file");
            Console.WriteLine(CCopasiMessage.getAllMessageText());
            Environment.Exit(1);
        }

        CModel model = dataModel.getModel();
        ModelParameterSetVectorN sets = model.getModelParameterSets();

        // if we don't have one, create one
        if (sets.size() == 0)
        {
            CModelParameterSet newSet = new CModelParameterSet("Current State", model);
            newSet.createFromModel();
            printParameterSet(newSet);
            sets.add(newSet);
        }

        // interrogate the exiting parameter sets
        printExistingParametersets(model.getModelParameterSets());
    }
    public static void Main(String[] args)
    {
        // create a new datamodel
        CDataModel dataModel = CRootContainer.addDatamodel();

        if (args.Length != 1)
        {
            Console.WriteLine("Need one argument: SBML | CPS filename.");
            Environment.Exit(1);
        }

        String filename = args[0];

        try
        {
            String ext = System.IO.Path.GetExtension(filename);
            if (ext.Trim().ToLowerInvariant().EndsWith("xml"))
            {
                // load the model without progress report
                dataModel.importSBML(filename);
            }
            else
            {
                // load the model without progress report
                dataModel.loadModel(filename);
            }
        }
        catch
        {
            Console.WriteLine("Error while loading the model from file named \"" + filename + "\".");
            Environment.Exit(1);
        }
        try
        {
            CModel model          = dataModel.getModel();
            int    numAnnotations = model.getNumUnsupportedAnnotations();
            Console.WriteLine("The model has: " + numAnnotations + " unsupported annotations.");

            if (numAnnotations == 0)
            {
                Console.WriteLine("adding custom annotation");
                // we don't have an annotation, so lets add one
                if (!model.addUnsupportedAnnotation("http://myannotation.org", "<test xmlns='http://myannotation.org' value='blaaaahaaa'/>"))
                {
                    Console.WriteLine("couldn't set annotation: ");
                    Console.WriteLine(CCopasiMessage.getAllMessageText());
                }
            }
            Console.WriteLine("The name of the first is: " + model.getUnsupportedAnnotationName(0));
            Console.WriteLine("The raw xml of the first is: " + model.getUnsupportedAnnotation(0));
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }
    }
Ejemplo n.º 4
0
    public static void Main(String[] args)
    {
        // create a new datamodel
        CDataModel dataModel = CRootContainer.addDatamodel();

        if (args.Length != 2)
        {
            Console.WriteLine("Need two arguments: filename and filter.");
            Environment.Exit(1);
        }

        String filename = args[0];

        try
        {
            String ext = System.IO.Path.GetExtension(filename);
            if (ext.Trim().ToLowerInvariant() == "xml")
            {
                // load the model without progress report
                dataModel.importSBML(filename);
            }
            else
            {
                // load the model without progress report
                dataModel.loadModel(filename);
            }
        }
        catch
        {
            Console.WriteLine("Error while loading the model from file named \"" + filename + "\".");
            Environment.Exit(1);
        }
        try
        {
            // clear warnings / error messages
            CCopasiMessage.clearDeque();

            // convert
            String translation = dataModel.exportMathModelToString(args[1]);

            // if conversion failed print message
            if (string.IsNullOrEmpty(translation))
            {
                Console.WriteLine("Translation failed: ");
                Console.WriteLine(CCopasiMessage.getAllMessageText());
            }

            // print translation
            Console.WriteLine(translation);
        }
        catch
        {
            Console.WriteLine("Error. Exporting the model to math failed.");
        }
    }
Ejemplo n.º 5
0
    public override void Init()
    {
        instance    = this;
        models      = new List <CModelBase>();
        updateList  = new List <CModelBase.UpdateHandler>();
        msgRegister = new Dictionary <Type, List <Callback> >();

        AddModel <CModelScene>(out scene);
        AddModel <CModelPlayer>(out player);
        AddModel <CModelConnection>(out connection);
        AddModel <CModelInputEvent>(out inputEvent);
        AddModel <CModelGameState>(out gameState);
        AddModel <CModelCMD>(out cmdBuffer);
        AddModel <CModelGameSimulate>(out gameSimulate);
        AddModel <CModelGameBot>(out gameBot);

        needUpdate = true;
    }
Ejemplo n.º 6
0
    public override void Dispose()
    {
        int len = models.Count;

        for (int i = 0; i < len; i++)
        {
            models[i].Dispose();
        }

        var iterator = msgRegister.GetEnumerator();

        while (iterator.MoveNext())
        {
            iterator.Current.Value.Clear();
        }
        msgRegister.Clear();
        updateList.Clear();
        instance = null;
    }
Ejemplo n.º 7
0
    static void Main(string[] args)
    {
        Debug.Assert(CRootContainer.getRoot() != null);
        // create a new datamodel
        CDataModel dataModel = CRootContainer.addDatamodel();

        Debug.Assert(CRootContainer.getDatamodelList().size() == 1);
        // the only argument to the main routine should be the name of an SBML file
        if (args.Length == 1)
        {
            string filename = args[0];
            try
            {
                // load the model
                dataModel.importSBML(filename);
            }
            catch
            {
                System.Console.Error.WriteLine("Error while importing the model from file named \"" + filename + "\".");
                System.Environment.Exit(1);
            }
            CModel model = dataModel.getModel();
            Debug.Assert(model != null);
            // create a report with the correct filename and all the species against
            // time.
            CReportDefinitionVector reports = dataModel.getReportDefinitionList();
            // create a new report definition object
            CReportDefinition report = reports.createReportDefinition("Report", "Output for timecourse");
            // set the task type for the report definition to timecourse
            report.setTaskType(CTaskEnum.Task_timeCourse);
            // we don't want a table
            report.setIsTable(false);
            // the entries in the output should be seperated by a ", "
            report.setSeparator(new CCopasiReportSeparator(", "));

            // we need a handle to the header and the body
            // the header will display the ids of the metabolites and "time" for
            // the first column
            // the body will contain the actual timecourse data
            ReportItemVector header = report.getHeaderAddr();
            ReportItemVector body   = report.getBodyAddr();

            body.Add(new CRegisteredCommonName(model.getObject(new CCommonName("Reference=Time")).getCN().getString()));
            body.Add(new CRegisteredCommonName(report.getSeparator().getCN().getString()));
            header.Add(new CRegisteredCommonName(new CDataString("time").getCN().getString()));
            header.Add(new CRegisteredCommonName(report.getSeparator().getCN().getString()));

            uint i, iMax = (uint)model.getMetabolites().size();
            for (i = 0; i < iMax; ++i)
            {
                CMetab metab = model.getMetabolite(i);
                Debug.Assert(metab != null);
                // we don't want output for FIXED metabolites right now
                if (metab.getStatus() != CModelEntity.Status_FIXED)
                {
                    // we want the concentration oin the output
                    // alternatively, we could use "Reference=Amount" to get the
                    // particle number
                    body.Add(new CRegisteredCommonName(metab.getObject(new CCommonName("Reference=Concentration")).getCN().getString()));
                    // add the corresponding id to the header
                    header.Add(new CRegisteredCommonName(new CDataString(metab.getSBMLId()).getCN().getString()));
                    // after each entry, we need a seperator
                    if (i != iMax - 1)
                    {
                        body.Add(new CRegisteredCommonName(report.getSeparator().getCN().getString()));
                        header.Add(new CRegisteredCommonName(report.getSeparator().getCN().getString()));
                    }
                }
            }


            // get the trajectory task object
            CTrajectoryTask trajectoryTask = (CTrajectoryTask)dataModel.getTask("Time-Course");

            // run a deterministic time course
            trajectoryTask.setMethodType(CTaskEnum.Method_deterministic);

            // pass a pointer of the model to the problem
            trajectoryTask.getProblem().setModel(dataModel.getModel());

            // actiavate the task so that it will be run when the model is saved
            // and passed to CopasiSE
            trajectoryTask.setScheduled(true);

            // set the report for the task
            trajectoryTask.getReport().setReportDefinition(report);
            // set the output filename
            trajectoryTask.getReport().setTarget("example3.txt");
            // don't append output if the file exists, but overwrite the file
            trajectoryTask.getReport().setAppend(false);

            // get the problem for the task to set some parameters
            CTrajectoryProblem problem = (CTrajectoryProblem)trajectoryTask.getProblem();

            // simulate 100 steps
            problem.setStepNumber(100);
            // start at time 0
            dataModel.getModel().setInitialTime(0.0);
            // simulate a duration of 10 time units
            problem.setDuration(10);
            // tell the problem to actually generate time series data
            problem.setTimeSeriesRequested(true);

            // set some parameters for the LSODA method through the method
            CTrajectoryMethod method = (CTrajectoryMethod)trajectoryTask.getMethod();

            CCopasiParameter parameter = method.getParameter("Absolute Tolerance");
            Debug.Assert(parameter != null);
            Debug.Assert(parameter.getType() == CCopasiParameter.Type_DOUBLE);
            parameter.setDblValue(1.0e-12);

            bool result = true;
            try
            {
                // now we run the actual trajectory
                result = trajectoryTask.processWithOutputFlags(true, (int)CCopasiTask.ONLY_TIME_SERIES);
            }
            catch
            {
                System.Console.Error.WriteLine("Error. Running the time course simulation failed.");
                String lastErrors = trajectoryTask.getProcessError();
                // check if there are additional error messages
                if (!string.IsNullOrEmpty(lastErrors))
                {
                    // print the messages in chronological order
                    System.Console.Error.WriteLine(lastErrors);
                }

                System.Environment.Exit(1);
            }
            if (result == false)
            {
                System.Console.Error.WriteLine("An error occured while running the time course simulation.");
                String lastErrors = trajectoryTask.getProcessError();
                // check if there are additional error messages
                if (!string.IsNullOrEmpty(lastErrors))
                {
                    // print the messages in chronological order
                    System.Console.Error.WriteLine(lastErrors);
                }

                System.Environment.Exit(1);
            }

            // look at the timeseries
            CTimeSeries timeSeries = trajectoryTask.getTimeSeries();
            // we simulated 100 steps, including the initial state, this should be
            // 101 step in the timeseries
            Debug.Assert(timeSeries.getRecordedSteps() == 101);
            System.Console.WriteLine("The time series consists of " + System.Convert.ToString(timeSeries.getRecordedSteps()) + ".");
            System.Console.WriteLine("Each step contains " + System.Convert.ToString(timeSeries.getNumVariables()) + " variables.");
            System.Console.WriteLine("The final state is: ");
            iMax = (uint)timeSeries.getNumVariables();
            uint lastIndex = (uint)timeSeries.getRecordedSteps() - 1;
            for (i = 0; i < iMax; ++i)
            {
                // here we get the particle number (at least for the species)
                // the unit of the other variables may not be particle numbers
                // the concentration data can be acquired with getConcentrationData
                System.Console.WriteLine(timeSeries.getTitle(i) + ": " + System.Convert.ToString(timeSeries.getData(lastIndex, i)));
            }
        }
        else
        {
            System.Console.Error.WriteLine("Usage: example3 SBMLFILE");
            System.Environment.Exit(1);
        }
    }
Ejemplo n.º 8
0
    static void Main(string[] args)
    {
        Debug.Assert(CRootContainer.getRoot() != null);
        // create a new datamodel
        CDataModel dataModel = CRootContainer.addDatamodel();

        Debug.Assert(CRootContainer.getDatamodelList().size() == 1);
        // first we load a simple model
        try
        {
            // load the model
            dataModel.importSBMLFromString(MODEL_STRING);
        }
        catch
        {
            System.Console.Error.WriteLine("Error while importing the model.");
            System.Environment.Exit(1);
        }

        // now we need to run some time course simulation to get data to fit
        // against

        // get the trajectory task object
        CTrajectoryTask trajectoryTask = (CTrajectoryTask)dataModel.getTask("Time-Course");

        // run a deterministic time course
        trajectoryTask.setMethodType(CTaskEnum.Method_deterministic);

        // pass a pointer of the model to the problem
        trajectoryTask.getProblem().setModel(dataModel.getModel());

        // activate the task so that it will be run when the model is saved
        // and passed to CopasiSE
        trajectoryTask.setScheduled(true);

        // get the problem for the task to set some parameters
        CTrajectoryProblem problem = (CTrajectoryProblem)trajectoryTask.getProblem();

        // simulate 4000 steps
        problem.setStepNumber(4000);
        // start at time 0
        dataModel.getModel().setInitialTime(0.0);
        // simulate a duration of 400 time units
        problem.setDuration(400);
        // tell the problem to actually generate time series data
        problem.setTimeSeriesRequested(true);

        // set some parameters for the LSODA method through the method
        // Currently we don't use the method to set anything
        //CTrajectoryMethod method = (CTrajectoryMethod)trajectoryTask.getMethod();

        bool result = true;

        try
        {
            // now we run the actual trajectory
            result = trajectoryTask.processWithOutputFlags(true, (int)CCopasiTask.ONLY_TIME_SERIES);
        }
        catch
        {
            System.Console.Error.WriteLine("Error. Running the time course simulation failed.");
            String lastErrors = trajectoryTask.getProcessError();
            // check if there are additional error messages
            if (!string.IsNullOrEmpty(lastErrors))
            {
                // print the messages in chronological order
                System.Console.Error.WriteLine(lastErrors);
            }

            System.Environment.Exit(1);
        }
        if (result == false)
        {
            System.Console.Error.WriteLine("An error occured while running the time course simulation.");
            String lastErrors = trajectoryTask.getProcessError();
            // check if there are additional error messages
            if (!string.IsNullOrEmpty(lastErrors))
            {
                // print the messages in chronological order
                System.Console.Error.WriteLine(lastErrors);
            }
            System.Environment.Exit(1);
        }

        // we write the data to a file and add some noise to it
        // This is necessary since COPASI can only read experimental data from
        // file.
        CTimeSeries timeSeries = trajectoryTask.getTimeSeries();

        // we simulated 100 steps, including the initial state, this should be
        // 101 step in the timeseries
        Debug.Assert(timeSeries.getRecordedSteps() == 4001);
        uint i;
        uint iMax = (uint)timeSeries.getNumVariables();

        // there should be four variables, the three metabolites and time
        Debug.Assert(iMax == 5);
        uint lastIndex = (uint)timeSeries.getRecordedSteps() - 1;
        // open the file
        // we need to remember in which order the variables are written to file
        // since we need to specify this later in the parameter fitting task
        List <uint>   indexSet    = new List <uint>();
        List <CMetab> metabVector = new List <CMetab>();

        // write the header
        // the first variable in a time series is a always time, for the rest
        // of the variables, we use the SBML id in the header
        double random = 0.0;

        System.Random rand_gen = new System.Random();
        try
        {
            System.IO.StreamWriter os = new System.IO.StreamWriter("fakedata_example6.txt");
            os.Write("# time ");
            CKeyFactory keyFactory = CRootContainer.getKeyFactory();
            Debug.Assert(keyFactory != null);
            for (i = 1; i < iMax; ++i)
            {
                string      key = timeSeries.getKey(i);
                CDataObject obj = keyFactory.get(key);
                Debug.Assert(obj != null);
                // only write header data or metabolites
                System.Type type = obj.GetType();
                if (type.FullName.Equals("org.COPASI.CMetab"))
                {
                    os.Write(", ");
                    os.Write(timeSeries.getSBMLId(i, dataModel));
                    CMetab m = (CMetab)obj;
                    indexSet.Add(i);
                    metabVector.Add(m);
                }
            }
            os.Write("\n");
            double data = 0.0;
            for (i = 0; i < lastIndex; ++i)
            {
                uint   j;
                string s = "";
                for (j = 0; j < iMax; ++j)
                {
                    // we only want to  write the data for metabolites
                    // the compartment does not interest us here
                    if (j == 0 || indexSet.Contains(j))
                    {
                        // write the data with some noise (+-5% max)
                        random = rand_gen.NextDouble();
                        data   = timeSeries.getConcentrationData(i, j);
                        // don't add noise to the time
                        if (j != 0)
                        {
                            data += data * (random * 0.1 - 0.05);
                        }
                        s = s + (System.Convert.ToString(data));
                        s = s + ", ";
                    }
                }
                // remove the last two characters again
                os.Write(s.Substring(0, s.Length - 2));
                os.Write("\n");
            }
            os.Close();
        }
        catch (System.ApplicationException e)
        {
            System.Console.Error.WriteLine("Error. Could not write time course data to file.");
            System.Console.WriteLine(e.Message);
            System.Environment.Exit(1);
        }

        // now we change the parameter values to see if the parameter fitting
        // can really find the original values
        random = rand_gen.NextDouble() * 10;
        CReaction reaction = dataModel.getModel().getReaction(0);

        // we know that it is an irreversible mass action, so there is one
        // parameter
        Debug.Assert(reaction.getParameters().size() == 1);
        Debug.Assert(reaction.isLocalParameter(0));
        // the parameter of a irreversible mass action is called k1
        reaction.setParameterValue("k1", random);

        reaction = dataModel.getModel().getReaction(1);
        // we know that it is an irreversible mass action, so there is one
        // parameter
        Debug.Assert(reaction.getParameters().size() == 1);
        Debug.Assert(reaction.isLocalParameter(0));
        reaction.setParameterValue("k1", random);

        CFitTask fitTask = (CFitTask)dataModel.addTask(CTaskEnum.Task_parameterFitting);

        Debug.Assert(fitTask != null);
        // the method in a fit task is an instance of COptMethod or a subclass of
        // it.
        COptMethod fitMethod = (COptMethod)fitTask.getMethod();

        Debug.Assert(fitMethod != null);
        // the object must be an instance of COptMethod or a subclass thereof
        // (CFitMethod)
        CFitProblem fitProblem = (CFitProblem)fitTask.getProblem();

        Debug.Assert(fitProblem != null);

        CExperimentSet experimentSet = (CExperimentSet)fitProblem.getParameter("Experiment Set");

        Debug.Assert(experimentSet != null);

        // first experiment (we only have one here)
        CExperiment experiment = new CExperiment(dataModel);

        Debug.Assert(experiment != null);
        // tell COPASI where to find the data
        // reading data from string is not possible with the current C++ API
        experiment.setFileName("fakedata_example6.txt");
        // we have to tell COPASI that the data for the experiment is a komma
        // separated list (the default is TAB separated)
        experiment.setSeparator(",");
        // the data start in row 1 and goes to row 4001
        experiment.setFirstRow(1);
        Debug.Assert(experiment.getFirstRow() == 1);
        experiment.setLastRow(4001);
        Debug.Assert(experiment.getLastRow() == 4001);
        experiment.setHeaderRow(1);
        Debug.Assert(experiment.getHeaderRow() == 1);
        experiment.setExperimentType(CTaskEnum.Task_timeCourse);
        Debug.Assert(experiment.getExperimentType() == CTaskEnum.Task_timeCourse);
        experiment.setNumColumns(4);
        Debug.Assert(experiment.getNumColumns() == 4);
        CExperimentObjectMap objectMap = experiment.getObjectMap();

        Debug.Assert(objectMap != null);
        result = objectMap.setNumCols(4);
        Debug.Assert(result == true);
        result = objectMap.setRole(0, CExperiment.time);
        Debug.Assert(result == true);
        Debug.Assert(objectMap.getRole(0) == CExperiment.time);

        CModel model = dataModel.getModel();

        Debug.Assert(model != null);
        CDataObject timeReference = model.getValueReference();

        Debug.Assert(timeReference != null);
        objectMap.setObjectCN(0, timeReference.getCN().getString());

        // now we tell COPASI which column contain the concentrations of
        // metabolites and belong to dependent variables
        objectMap.setRole(1, CExperiment.dependent);
        CMetab metab = metabVector[0];

        Debug.Assert(metab != null);
        CDataObject particleReference = metab.getConcentrationReference();

        Debug.Assert(particleReference != null);
        objectMap.setObjectCN(1, particleReference.getCN().getString());

        objectMap.setRole(2, CExperiment.dependent);
        metab = metabVector[1];
        Debug.Assert(metab != null);
        particleReference = metab.getConcentrationReference();
        Debug.Assert(particleReference != null);
        objectMap.setObjectCN(2, particleReference.getCN().getString());

        objectMap.setRole(3, CExperiment.dependent);
        metab = metabVector[2];
        Debug.Assert(metab != null);
        particleReference = metab.getConcentrationReference();
        Debug.Assert(particleReference != null);
        objectMap.setObjectCN(3, particleReference.getCN().getString());

        experimentSet.addExperiment(experiment);
        Debug.Assert(experimentSet.getExperimentCount() == 1);
        // addExperiment makes a copy, so we need to get the added experiment
        // again
        experiment = experimentSet.getExperiment(0);
        Debug.Assert(experiment != null);

        // now we have to define the two fit items for the two local parameters
        // of the two reactions
        reaction = model.getReaction(0);
        Debug.Assert(reaction != null);
        Debug.Assert(reaction.isLocalParameter(0) == true);
        CCopasiParameter parameter = reaction.getParameters().getParameter(0);

        Debug.Assert(parameter != null);

        // define a CFitItem
        CDataObject parameterReference = parameter.getValueReference();

        Debug.Assert(parameterReference != null);
        CFitItem fitItem1 = new CFitItem(dataModel);

        Debug.Assert(fitItem1 != null);
        fitItem1.setObjectCN(parameterReference.getCN());
        fitItem1.setStartValue(4.0);
        fitItem1.setLowerBound(new CCommonName("0.00001"));
        fitItem1.setUpperBound(new CCommonName("10"));
        // add the fit item to the correct parameter group
        CCopasiParameterGroup optimizationItemGroup = (CCopasiParameterGroup)fitProblem.getParameter("OptimizationItemList");

        Debug.Assert(optimizationItemGroup != null);
        optimizationItemGroup.addParameter(fitItem1);

        reaction = model.getReaction(1);
        Debug.Assert(reaction != null);
        Debug.Assert(reaction.isLocalParameter(0) == true);
        parameter = reaction.getParameters().getParameter(0);
        Debug.Assert(parameter != null);

        // define a CFitItem
        parameterReference = parameter.getValueReference();
        Debug.Assert(parameterReference != null);
        CFitItem fitItem2 = new CFitItem(dataModel);

        Debug.Assert(fitItem2 != null);
        fitItem2.setObjectCN(parameterReference.getCN());
        fitItem2.setStartValue(4.0);
        fitItem2.setLowerBound(new CCommonName("0.00001"));
        fitItem2.setUpperBound(new CCommonName("10"));
        // add the fit item to the correct parameter group
        optimizationItemGroup.addParameter(fitItem2);

        result = true;
        try
        {
            // running the task for this example will probably take some time
            System.Console.WriteLine("This can take some time...");
            result = fitTask.processWithOutputFlags(true, (int)CCopasiTask.ONLY_TIME_SERIES);
        }
        catch
        {
            System.Console.Error.WriteLine("Error. Parameter fitting failed.");
            String lastErrors = fitTask.getProcessError();
            // check if there are additional error messages
            if (!string.IsNullOrEmpty(lastErrors))
            {
                // print the messages in chronological order
                System.Console.Error.WriteLine(lastErrors);
            }

            System.Environment.Exit(1);
        }

        Debug.Assert(result == true);
        // assert that there are two optimization items
        Debug.Assert(fitProblem.getOptItemList().Count == 2);
        // the order should be the order in whih we added the items above
        COptItem optItem1 = fitProblem.getOptItemList()[0];
        COptItem optItem2 = fitProblem.getOptItemList()[1];

        // the actual results are stored in the fit problem
        Debug.Assert(fitProblem.getSolutionVariables().size() == 2);
        System.Console.WriteLine("value for " + optItem1.getObject().getCN().getString() + ": " + fitProblem.getSolutionVariables().get(0));
        System.Console.WriteLine("value for " + optItem2.getObject().getCN().getString() + ": " + fitProblem.getSolutionVariables().get(1));
        // depending on the noise, the fit can be quite bad, so we are a litle
        // relaxed here (we should be within 3% of the original values)
        Debug.Assert((System.Math.Abs(fitProblem.getSolutionVariables().get(0) - 0.03) / 0.03) < 3e-2);
        Debug.Assert((System.Math.Abs(fitProblem.getSolutionVariables().get(1) - 0.004) / 0.004) < 3e-2);
    }
Ejemplo n.º 9
0
    static void Main()
    {
        Debug.Assert(CRootContainer.getRoot() != null);
        // create a new datamodel
        CDataModel dataModel = CRootContainer.addDatamodel();

        Debug.Assert(CRootContainer.getDatamodelList().size() == 1);
        // the only argument to the main routine should be the name of an SBML file
        try
        {
            // load the model
            dataModel.importSBMLFromString(MODEL_STRING);
        }
        catch
        {
            System.Console.Error.WriteLine("Error while importing the model from the given String.");
            System.Environment.Exit(1);
        }
        CModel model = dataModel.getModel();

        Debug.Assert(model != null);
        // create a report with the correct filename and all the species against
        // time.
        CReportDefinitionVector reports = dataModel.getReportDefinitionList();
        // create a new report definition object
        CReportDefinition report = reports.createReportDefinition("Report", "Output for timecourse");

        // set the task type for the report definition to timecourse
        report.setTaskType(CTaskEnum.Task_timeCourse);
        // we don't want a table
        report.setIsTable(false);
        // the entries in the output should be seperated by a ", "
        report.setSeparator(new CCopasiReportSeparator(", "));

        // we need a handle to the header and the body
        // the header will display the ids of the metabolites and "time" for
        // the first column
        // the body will contain the actual timecourse data
        ReportItemVector header = report.getHeaderAddr();
        ReportItemVector body   = report.getBodyAddr();

        body.Add(new CRegisteredCommonName(new CCommonName(dataModel.getModel().getCN().getString() + ",Reference=Time").getString()));
        body.Add(new CRegisteredCommonName(report.getSeparator().getCN().getString()));
        header.Add(new CRegisteredCommonName(new CDataString("time").getCN().getString()));
        header.Add(new CRegisteredCommonName(report.getSeparator().getCN().getString()));

        uint i, iMax = (uint)model.getMetabolites().size();

        for (i = 0; i < iMax; ++i)
        {
            CMetab metab = model.getMetabolite(i);
            Debug.Assert(metab != null);
            // we don't want output for FIXED metabolites right now
            if (metab.getStatus() != CModelEntity.Status_FIXED)
            {
                // we want the concentration oin the output
                // alternatively, we could use "Reference=Amount" to get the
                // particle number
                body.Add(new CRegisteredCommonName(metab.getObject(new CCommonName("Reference=Concentration")).getCN().getString()));
                // add the corresponding id to the header
                header.Add(new CRegisteredCommonName(new CDataString(metab.getSBMLId()).getCN().getString()));

                if (i != iMax - 1)
                {
                    // after each entry, we need a seperator
                    body.Add(new CRegisteredCommonName(report.getSeparator().getCN().getString()));

                    // and a seperator
                    header.Add(new CRegisteredCommonName(report.getSeparator().getCN().getString()));
                }
            }
        }

        // get the trajectory task object
        CTrajectoryTask trajectoryTask = (CTrajectoryTask)dataModel.getTask("Time-Course");

        // run a stochastic time course
        trajectoryTask.setMethodType(CTaskEnum.Method_stochastic);

        // pass a pointer of the model to the problem
        trajectoryTask.getProblem().setModel(dataModel.getModel());

        // we don't want the trajectory task to run by itself, but we want to
        // run it from a scan, so we deactivate the standalone trajectory task
        trajectoryTask.setScheduled(false);

        // get the problem for the task to set some parameters
        CTrajectoryProblem problem = (CTrajectoryProblem)trajectoryTask.getProblem();

        // simulate 100 steps
        problem.setStepNumber(100);
        // start at time 0
        dataModel.getModel().setInitialTime(0.0);
        // simulate a duration of 10 time units
        problem.setDuration(10);
        // tell the problem to actually generate time series data
        problem.setTimeSeriesRequested(true);

        // now we set up the scan
        CScanTask scanTask = (CScanTask)dataModel.getTask("Scan");

        // get the problem
        CScanProblem scanProblem = (CScanProblem)scanTask.getProblem();

        Debug.Assert(scanProblem != null);

        // set the model for the problem
        scanProblem.setModel(dataModel.getModel());

        // activate the task so that is is run
        // if the model is saved and passed to CopasiSE
        scanTask.setScheduled(true);

        // set the report for the task
        scanTask.getReport().setReportDefinition(report);

        // set the output file for the report
        scanTask.getReport().setTarget("example4.txt");
        // don't append to an existing file, but overwrite
        scanTask.getReport().setAppend(false);

        // tell the scan that we want to make a scan over a trajectory task
        scanProblem.setSubtask(CTaskEnum.Task_timeCourse);

        // we just want to run the timecourse task a number of times, so we
        // create a repeat item with 100 repeats
        scanProblem.addScanItem(CScanProblem.SCAN_REPEAT, 100);

        // we want the output from the trajectory task
        scanProblem.setOutputInSubtask(true);

        // we don't want to set the initial conditions of the model to the end
        // state of the last run
        scanProblem.setContinueFromCurrentState(false);

        try
        {
            // now we run the actual trajectory
            scanTask.processWithOutputFlags(true, (int)CCopasiTask.ONLY_TIME_SERIES);
        }
        catch
        {
            System.Console.Error.WriteLine("Error. Running the scan failed.");
            String lastErrors = scanTask.getProcessError();
            // check if there are additional error messages
            if (!string.IsNullOrEmpty(lastErrors))
            {
                // print the messages in chronological order
                System.Console.Error.WriteLine(lastErrors);
            }

            System.Environment.Exit(1);
        }
    }
Ejemplo n.º 10
0
    static void Main()
    {
        Debug.Assert(CRootContainer.getRoot() != null);
        // create a new datamodel
        CDataModel dataModel = CRootContainer.addDatamodel();

        Debug.Assert(CRootContainer.getDatamodelList().size() == 1);
        // get the model from the datamodel
        CModel model = dataModel.getModel();

        Debug.Assert(model != null);
        // set the units for the model
        // we want seconds as the time unit
        // microliter as the volume units
        // and nanomole as the substance units
        model.setTimeUnit(CUnit.s);
        model.setVolumeUnit(CUnit.microl);
        model.setQuantityUnit(CUnit.nMol);

        // we have to keep a set of all the initial values that are changed during
        // the model building process
        // They are needed after the model has been built to make sure all initial
        // values are set to the correct initial value
        ObjectStdVector changedObjects = new ObjectStdVector();

        // create a compartment with the name cell and an initial volume of 5.0
        // microliter
        CCompartment compartment = model.createCompartment("cell", 5.0);
        CDataObject  obj         = compartment.getInitialValueReference();

        Debug.Assert(obj != null);
        changedObjects.Add(obj);
        Debug.Assert(compartment != null);
        Debug.Assert(model.getCompartments().size() == 1);
        // create a new metabolite with the name glucose and an inital
        // concentration of 10 nanomol
        // the metabolite belongs to the compartment we created and is is to be
        // fixed
        CMetab glucose = model.createMetabolite("glucose", compartment.getObjectName(), 10.0, CModelEntity.Status_FIXED);

        obj = glucose.getInitialValueReference();
        Debug.Assert(obj != null);
        changedObjects.Add(obj);
        Debug.Assert(glucose != null);
        Debug.Assert(model.getMetabolites().size() == 1);
        // create a second metabolite called glucose-6-phosphate with an initial
        // concentration of 0. This metabolite is to be changed by reactions
        CMetab g6p = model.createMetabolite("glucose-6-phosphate", compartment.getObjectName(), 0.0, CModelEntity.Status_REACTIONS);

        Debug.Assert(g6p != null);
        obj = g6p.getInitialValueReference();
        Debug.Assert(obj != null);
        changedObjects.Add(obj);
        Debug.Assert(model.getMetabolites().size() == 2);
        // another metabolite for ATP, also fixed
        CMetab atp = model.createMetabolite("ATP", compartment.getObjectName(), 10.0, CModelEntity.Status_FIXED);

        Debug.Assert(atp != null);
        obj = atp.getInitialValueReference();
        Debug.Assert(obj != null);
        changedObjects.Add(obj);
        Debug.Assert(model.getMetabolites().size() == 3);
        // and one for ADP
        CMetab adp = model.createMetabolite("ADP", compartment.getObjectName(), 0.0, CModelEntity.Status_REACTIONS);

        Debug.Assert(adp != null);
        obj = adp.getInitialValueReference();
        Debug.Assert(obj != null);
        changedObjects.Add(obj);
        Debug.Assert(model.getMetabolites().size() == 4);
        // now we create a reaction
        CReaction reaction = model.createReaction("hexokinase");

        Debug.Assert(reaction != null);
        Debug.Assert(model.getReactions().size() == 1);
        // hexokinase converts glucose and ATP to glucose-6-phosphate and ADP
        // we can set these on the chemical equation of the reaction
        CChemEq chemEq = reaction.getChemEq();

        // glucose is a substrate with stoichiometry 1
        chemEq.addMetabolite(glucose.getKey(), 1.0, CChemEq.SUBSTRATE);
        // ATP is a substrate with stoichiometry 1
        chemEq.addMetabolite(atp.getKey(), 1.0, CChemEq.SUBSTRATE);
        // glucose-6-phosphate is a product with stoichiometry 1
        chemEq.addMetabolite(g6p.getKey(), 1.0, CChemEq.PRODUCT);
        // ADP is a product with stoichiometry 1
        chemEq.addMetabolite(adp.getKey(), 1.0, CChemEq.PRODUCT);
        Debug.Assert(chemEq.getSubstrates().size() == 2);
        Debug.Assert(chemEq.getProducts().size() == 2);
        // this reaction is to be irreversible
        reaction.setReversible(false);
        Debug.Assert(reaction.isReversible() == false);
        // now we ned to set a kinetic law on the reaction
        // maybe constant flux would be OK
        // we need to get the function from the function database
        CFunctionDB funDB = CRootContainer.getFunctionList();

        Debug.Assert(funDB != null);
        // it should be in the list of suitable functions
        // lets get all suitable functions for an irreversible reaction with  2 substrates
        // and 2 products
        CFunctionStdVector suitableFunctions = funDB.suitableFunctions(2, 2, COPASI.TriFalse);

        Debug.Assert((suitableFunctions.Count > 0));
        int i, iMax = (int)suitableFunctions.Count;

        for (i = 0; i < iMax; ++i)
        {
            // we just assume that the only suitable function with Constant in
            // it's name is the one we want
            if (suitableFunctions[i].getObjectName().IndexOf("Constant") != -1)
            {
                break;
            }
        }
        if (i != iMax)
        {
            // we set the function
            // the method should be smart enough to associate the reaction entities
            // with the correct function parameters
            reaction.setFunction(suitableFunctions[i]);
            Debug.Assert(reaction.getFunction() != null);
            // constant flux has only one function parameter
            Debug.Assert(reaction.getFunctionParameters().size() == 1);
            // so there should be only one entry in the parameter mapping as well
            Debug.Assert(reaction.getParameterCNs().Count == 1);
            CCopasiParameterGroup parameterGroup = reaction.getParameters();
            Debug.Assert(parameterGroup.size() == 1);
            CCopasiParameter parameter = parameterGroup.getParameter(0);
            // make sure the parameter is a local parameter
            Debug.Assert(reaction.isLocalParameter(parameter.getObjectName()));
            // now we set the value of the parameter to 0.5
            Debug.Assert(parameter.getType() == CCopasiParameter.Type_DOUBLE);
            parameter.setDblValue(0.5);
            obj = parameter.getValueReference();
            Debug.Assert(obj != null);
            changedObjects.Add(obj);
        }
        else
        {
            System.Console.Error.WriteLine("Error. Could not find a kinetic law that conatins the term \"Constant\".");
            System.Environment.Exit(1);
        }
        // now we also create a separate reaction for the backwards reaction and
        // set the kinetic law to irreversible mass action
        // now we create a reaction
        reaction = model.createReaction("hexokinase-backwards");
        Debug.Assert(reaction != null);
        Debug.Assert(model.getReactions().size() == 2);
        chemEq = reaction.getChemEq();
        // glucose is a product with stoichiometry 1
        chemEq.addMetabolite(glucose.getKey(), 1.0, CChemEq.PRODUCT);
        // ATP is a product with stoichiometry 1
        chemEq.addMetabolite(atp.getKey(), 1.0, CChemEq.PRODUCT);
        // glucose-6-phosphate is a substrate with stoichiometry 1
        chemEq.addMetabolite(g6p.getKey(), 1.0, CChemEq.SUBSTRATE);
        // ADP is a substrate with stoichiometry 1
        chemEq.addMetabolite(adp.getKey(), 1.0, CChemEq.SUBSTRATE);
        Debug.Assert(chemEq.getSubstrates().size() == 2);
        Debug.Assert(chemEq.getProducts().size() == 2);
        // this reaction is to be irreversible
        reaction.setReversible(false);
        Debug.Assert(reaction.isReversible() == false);
        // now we ned to set a kinetic law on the reaction
        CFunction massAction = (CFunction)funDB.findFunction("Mass action (irreversible)");

        Debug.Assert(massAction != null);
        // we set the function
        // the method should be smart enough to associate the reaction entities
        // with the correct function parameters
        reaction.setFunction(massAction);
        Debug.Assert(reaction.getFunction() != null);

        Debug.Assert(reaction.getFunctionParameters().size() == 2);
        // so there should be two entries in the parameter mapping as well
        Debug.Assert(reaction.getParameterCNs().Count == 2);
        // mass action is a special case since the parameter mappings for the
        // substrates (and products) are in a vector

        // Let us create a global parameter that is determined by an assignment
        // and that is used as the rate constant of the mass action kinetics
        // it gets the name rateConstant and an initial value of 1.56
        CModelValue modelValue = model.createModelValue("rateConstant", 1.56);

        Debug.Assert(modelValue != null);
        obj = modelValue.getInitialValueReference();
        Debug.Assert(obj != null);
        changedObjects.Add(obj);
        Debug.Assert(model.getModelValues().size() == 1);
        // set the status to assignment
        modelValue.setStatus(CModelEntity.Status_ASSIGNMENT);
        // the assignment does not have to make sense
        modelValue.setExpression("1.0 / 4.0 + 2.0");

        // now we have to adjust the parameter mapping in the reaction so
        // that the kinetic law uses the global parameter we just created instead
        // of the local one that is created by default
        // The first parameter is the one for the rate constant, so we point it to
        // the key of out model value
        reaction.setParameterObject(0, modelValue);
        // now we have to set the parameter mapping for the substrates
        reaction.addParameterObject("substrate", g6p);
        reaction.addParameterObject("substrate", adp);

        // finally compile the model
        // compile needs to be done before updating all initial values for
        // the model with the refresh sequence
        model.compileIfNecessary();

        // now that we are done building the model, we have to make sure all
        // initial values are updated according to their dependencies
        model.updateInitialValues(changedObjects);

        // save the model to a COPASI file
        // we save to a file named example1.cps
        // and we want to overwrite any existing file with the same name
        // Default tasks are automatically generated and will always appear in cps
        // file unless they are explicitley deleted before saving.
        dataModel.saveModel("example1.cps", true);

        // export the model to an SBML file
        // we save to a file named example1.xml, we want to overwrite any
        // existing file with the same name and we want SBML L2V3
        try
        {
            dataModel.exportSBML("example1.xml", true, 2, 3);
        }
        catch
        {
            System.Console.Error.WriteLine("Error. Exporting the model to SBML failed.");
        }
    }
Ejemplo n.º 11
0
    static void Main()
    {
        Debug.Assert((CRootContainer.getRoot() != null));
        // create a new datamodel
        CDataModel dataModel = CRootContainer.addDatamodel();

        Debug.Assert((dataModel != null));
        Debug.Assert((CRootContainer.getDatamodelList().size() == 1));
        // next we import a simple SBML model from a string

        // clear the message queue so that we only have error messages from the import in the queue
        CCopasiMessage.clearDeque();
        bool result = true;

        try
        {
            result = dataModel.importSBMLFromString(MODEL_STRING);
        }
        catch
        {
            System.Console.Error.WriteLine("Import of model failed miserably.");
            System.Environment.Exit(1);
        }
        // check if the import was successful
        int mostSevere = CCopasiMessage.getHighestSeverity();

        // if it was a filtered error, we convert it to an unfiltered type
        // the filtered error messages have the same value as the unfiltered, but they
        // have the 7th bit set which basically adds 128 to the value
        mostSevere = mostSevere & 127;

        // we assume that the import succeeded if the return value is true and
        // the most severe error message is not an error or an exception
        if (result != true && mostSevere < CCopasiMessage.ERROR)
        {
            System.Console.Error.WriteLine("Sorry. Model could not be imported.");
            System.Environment.Exit(1);
        }

        //
        // now we tell the model object to calculate the jacobian
        //
        CModel model = dataModel.getModel();

        Debug.Assert((model != null));

        if (model != null)
        {
            // running a task, e.g. a trajectory will automatically make sure that
            // the initial values are transferred to the current state before the calculation begins.
            // If we use low level calculation methods like the one to calculate the jacobian, we
            // have to make sure the the initial values are applied to the state
            model.applyInitialValues();
            // we need an array that stores the result
            // the size of the matrix does not really matter because
            // the calculateJacobian autoamtically resizes it to the correct
            // size
            FloatMatrix jacobian = new FloatMatrix();
            // the first parameter to the calculation function is a reference to
            // the matrix where the result is to be stored
            // the second parameter is the derivationFactor for the calculation
            // it basically represents a relative delta value for the calculation of the derivatives
            // the third parameter is a boolean indicating whether the jacobian should
            // be calculated from the reduced (true) or full (false) system
            model.getMathContainer().calculateJacobian(jacobian, 1e-12, false);
            // now we print the result
            // the jacobian stores the values in the order they are
            // given in the user order in the state template so it is not really straight
            // forward to find out which column/row corresponds to which species
            CStateTemplate stateTemplate = model.getStateTemplate();
            // and we need the user order
            SizeTVector userOrder = stateTemplate.getUserOrder();
            // from those two, we can construct an new vector that contains
            // the names of the entities in the jacobian in the order in which they appear in
            // the jacobian
            System.Collections.Generic.List <string> nameVector = new System.Collections.Generic.List <string>();
            CModelEntity entity = null;
            int          status;

            for (uint i = 0; i < userOrder.size(); ++i)
            {
                entity = stateTemplate.getEntity(userOrder.get(i));
                Debug.Assert((entity != null));
                // now we need to check if the entity is actually
                // determined by an ODE or a reaction
                status = entity.getStatus();

                if (status == CModelEntity.Status_ODE ||
                    (status == CModelEntity.Status_REACTIONS && entity.isUsed()))
                {
                    nameVector.Add(entity.getObjectName());
                }
            }

            Debug.Assert((nameVector.Count == jacobian.numRows()));
            // now we print the matrix, for this we assume that no
            // entity name is longer then 5 character which is a save bet since
            // we know the model
            System.Console.Out.NewLine = "";
            System.Console.WriteLine(System.String.Format("Jacobian Matrix:{0}", System.Environment.NewLine));
            System.Console.WriteLine(System.String.Format("size:{0}x{1}{2}", jacobian.numRows(), jacobian.numCols(), System.Environment.NewLine));
            System.Console.WriteLine(System.String.Format("{0}", System.Environment.NewLine));
            System.Console.Out.WriteLine(System.String.Format("{0,7}", " "));

            for (int i = 0; i < nameVector.Count; ++i)
            {
                System.Console.Out.WriteLine(System.String.Format("{0,7}", nameVector[i]));
            }

            System.Console.WriteLine(System.String.Format("{0}", System.Environment.NewLine));

            for (uint i = 0; i < nameVector.Count; ++i)
            {
                System.Console.Out.WriteLine(System.String.Format("{0,7}", nameVector[(int)i]));

                for (uint j = 0; j < nameVector.Count; ++j)
                {
                    System.Console.Out.WriteLine(System.String.Format("{0,7:0.###}", jacobian.get(i, j)));
                }

                System.Console.WriteLine(System.String.Format("{0}", System.Environment.NewLine));
            }

            // we can also calculate the jacobian of the reduced system
            // in a similar way
            model.getMathContainer().calculateJacobian(jacobian, 1e-12, true);
            // this time generating the output is actually simpler because the rows
            // and columns are ordered in the same way as the independent variables of the state temple
            System.Console.WriteLine(System.String.Format("{0}{0}", System.Environment.NewLine));
            System.Console.WriteLine(System.String.Format("Reduced Jacobian Matrix:{0}{0}", System.Environment.NewLine));
            System.Console.Out.WriteLine(System.String.Format("{0:6}", " "));

            uint iMax = stateTemplate.getNumIndependent();

            for (uint i = 0; i < iMax; ++i)
            {
                System.Console.Out.WriteLine(System.String.Format("\t{0:7}", stateTemplate.getIndependent(i).getObjectName()));
            }

            System.Console.WriteLine(System.String.Format("{0}", System.Environment.NewLine));

            for (uint i = 0; i < iMax; ++i)
            {
                System.Console.Out.WriteLine(System.String.Format("{0:7}", stateTemplate.getIndependent(i).getObjectName()));

                for (uint j = 0; j < iMax; ++j)
                {
                    System.Console.Out.WriteLine(System.String.Format("{0,7:0.###}", jacobian.get(i, j)));
                }

                System.Console.WriteLine(System.String.Format("{0}", System.Environment.NewLine));
            }
        }
    }
Ejemplo n.º 12
0
    static void Main()
    {
        Debug.Assert(CRootContainer.getRoot() != null);
        // create a new datamodel
        CDataModel dataModel = CRootContainer.addDatamodel();

        Debug.Assert(CRootContainer.getDatamodelList().size() == 1);
        // get the model from the datamodel
        CModel model = dataModel.getModel();

        Debug.Assert(model != null);
        // set the units for the model
        // we want seconds as the time unit
        // microliter as the volume units
        // and nanomole as the substance units
        model.setTimeUnit(CUnit.s);
        model.setVolumeUnit(CUnit.microl);
        model.setQuantityUnit(CUnit.nMol);

        // we have to keep a set of all the initial values that are changed during
        // the model building process
        // They are needed after the model has been built to make sure all initial
        // values are set to the correct initial value
        ObjectStdVector changedObjects = new ObjectStdVector();

        // create a compartment with the name cell and an initial volume of 5.0
        // microliter
        CCompartment compartment = model.createCompartment("cell", 5.0);
        CDataObject  obj         = compartment.getValueReference();

        Debug.Assert(obj != null);
        changedObjects.Add(obj);
        Debug.Assert(compartment != null);
        Debug.Assert(model.getCompartments().size() == 1);
        // create a new metabolite with the name S and an inital
        // concentration of 10 nanomol
        // the metabolite belongs to the compartment we created and is is to be
        // fixed
        CMetab S = model.createMetabolite("S", compartment.getObjectName(), 10.0, CModelEntity.Status_FIXED);

        obj = S.getInitialConcentrationReference();
        Debug.Assert((obj != null));
        changedObjects.Add(obj);
        Debug.Assert((compartment != null));
        Debug.Assert(S != null);
        Debug.Assert(model.getMetabolites().size() == 1);
        // create a second metabolite called P with an initial
        // concentration of 0. This metabolite is to be changed by reactions
        CMetab P = model.createMetabolite("P", compartment.getObjectName(), 0.0, CModelEntity.Status_REACTIONS);

        Debug.Assert(P != null);
        obj = P.getInitialConcentrationReference();
        Debug.Assert(obj != null);
        changedObjects.Add(obj);
        Debug.Assert(model.getMetabolites().size() == 2);

        // now we create a reaction
        CReaction reaction = model.createReaction("reaction");

        Debug.Assert(reaction != null);
        Debug.Assert(model.getReactions().size() == 1);
        // reaction converts S to P
        // we can set these on the chemical equation of the reaction
        CChemEq chemEq = reaction.getChemEq();

        // S is a substrate with stoichiometry 1
        chemEq.addMetabolite(S.getKey(), 1.0, CChemEq.SUBSTRATE);
        // P is a product with stoichiometry 1
        chemEq.addMetabolite(P.getKey(), 1.0, CChemEq.PRODUCT);
        Debug.Assert(chemEq.getSubstrates().size() == 1);
        Debug.Assert(chemEq.getProducts().size() == 1);
        // this reaction is to be irreversible
        reaction.setReversible(false);
        Debug.Assert(reaction.isReversible() == false);

        CModelValue MV = model.createModelValue("K", 42.0);

        // set the status to FIXED
        MV.setStatus(CModelEntity.Status_FIXED);
        Debug.Assert(MV != null);
        obj = MV.getInitialValueReference();
        Debug.Assert(obj != null);
        changedObjects.Add(obj);
        Debug.Assert(model.getModelValues().size() == 1);

        // now we ned to set a kinetic law on the reaction
        // for this we create a user defined function
        CFunctionDB funDB = CRootContainer.getFunctionList();

        Debug.Assert(funDB != null);

        CFunction function = (CFunction)funDB.createFunction("My Rate Law", CEvaluationTree.UserDefined);

        CFunction rateLaw = (CFunction)funDB.findFunction("My Rate Law");

        Debug.Assert(rateLaw != null);

        // now we create the formula for the function and set it on the function
        string formula = "(1-0.4/(EXPONENTIALE^(temp-37)))*0.00001448471257*1.4^(temp-37)*substrate";

        var result = function.setInfix(formula);

        Debug.Assert(result.isSuccess());
        // make the function irreversible
        function.setReversible(COPASI.TriFalse);
        // the formula string should have been parsed now
        // and COPASI should have determined that the formula string contained 2 parameters (temp and substrate)
        CFunctionParameters variables = function.getVariables();
        // per default the usage of those parameters will be set to VARIABLE
        uint index = function.getVariableIndex("temp");
        CFunctionParameter param = variables.getParameter(index);

        Debug.Assert(param.getUsage() == CFunctionParameter.VARIABLE);
        // This is correct for temp, but substrate should get the usage SUBSTRATE in order
        // for us to use the function with the reaction created above
        // So we need to set the usage for "substrate" manually
        index = function.getVariableIndex("substrate");
        param = variables.getParameter(index);
        param.setUsage(CFunctionParameter.SUBSTRATE);

        // set the rate law for the reaction
        reaction.setFunction(function);
        Debug.Assert(reaction.getFunction() != null);

        // COPASI also needs to know what object it has to assocuiate with the individual function parameters
        // In our case we need to tell COPASI that substrate is to be replaced by the substrate of the reaction
        // and temp is to be replaced by the global parameter K
        reaction.setParameterMapping("substrate", S.getKey());
        reaction.setParameterMapping("temp", MV.getKey());

        // finally compile the model
        // compile needs to be done before updating all initial values for
        // the model with the refresh sequence
        model.compileIfNecessary();

        // now that we are done building the model, we have to make sure all
        // initial values are updated according to their dependencies
        model.updateInitialValues(changedObjects);

        // save the model to a COPASI file
        // we save to a file named example1.cps
        // and we want to overwrite any existing file with the same name
        // Default tasks are automatically generated and will always appear in cps
        // file unless they are explicitley deleted before saving.
        dataModel.saveModel("example7.cps", true);

        // export the model to an SBML file
        // we save to a file named example1.xml, we want to overwrite any
        // existing file with the same name and we want SBML L2V3
        try
        {
            dataModel.exportSBML("example7.xml", true, 2, 3);
        }
        catch
        {
            System.Console.Error.WriteLine("Error. Exporting the model to SBML failed.");
        }
    }
Ejemplo n.º 13
0
    static void Main(string[] args)
    {
        Debug.Assert(CRootContainer.getRoot() != null);
        // create a new datamodel
        CDataModel dataModel = CRootContainer.addDatamodel();

        Debug.Assert(CRootContainer.getDatamodelList().size() == 1);
        // the only argument to the main routine should be the name of a CPS file
        if (args.Length == 1)
        {
            string filename = args[0];
            try
            {
                // load the model without progress report
                dataModel.loadModel(filename);
            }
            catch
            {
                System.Console.Error.WriteLine("Error while loading the model from file named \"" + filename + "\".");
                System.Environment.Exit(1);
            }
            CModel model = dataModel.getModel();
            Debug.Assert(model != null);
            System.Console.WriteLine("Model statistics for model \"" + model.getObjectName() + "\".");

            // output number and names of all compartments
            uint i, iMax = (uint)model.getCompartments().size();
            System.Console.WriteLine("Number of Compartments: " + System.Convert.ToString(iMax));
            System.Console.WriteLine("Compartments: ");
            for (i = 0; i < iMax; ++i)
            {
                CCompartment compartment = model.getCompartment(i);
                Debug.Assert(compartment != null);
                System.Console.WriteLine("\t" + compartment.getObjectName());
            }

            // output number and names of all metabolites
            iMax = (uint)model.getMetabolites().size();
            System.Console.WriteLine("Number of Metabolites: " + System.Convert.ToString(iMax));
            System.Console.WriteLine("Metabolites: ");
            for (i = 0; i < iMax; ++i)
            {
                CMetab metab = model.getMetabolite(i);
                Debug.Assert(metab != null);
                System.Console.WriteLine("\t" + metab.getObjectName());
            }

            // output number and names of all reactions
            iMax = (uint)model.getReactions().size();
            System.Console.WriteLine("Number of Reactions: " + System.Convert.ToString(iMax));
            System.Console.WriteLine("Reactions: ");
            for (i = 0; i < iMax; ++i)
            {
                CReaction reaction = model.getReaction(i);
                Debug.Assert(reaction != null);
                System.Console.WriteLine("\t" + reaction.getObjectName());
            }
        }
        else
        {
            System.Console.Error.WriteLine("Usage: example2 CPSFILE");
            System.Environment.Exit(1);
        }
    }
Ejemplo n.º 14
0
    static void Main()
    {
        // initialize the backend library
        // since we are not interested in the arguments
        // that are passed to main, we pass 0 and NULL to
        // init
        Debug.Assert(CRootContainer.getRoot() != null);
        // create a new datamodel
        CDataModel dataModel = CRootContainer.addDatamodel();

        Debug.Assert((dataModel != null));
        Debug.Assert((CRootContainer.getDatamodelList().size() == 1));
        // next we import a simple SBML model from a string

        // clear the message queue so that we only have error messages from the import in the queue
        CCopasiMessage.clearDeque();
        bool result = true;

        try
        {
            result = dataModel.importSBMLFromString(MODEL_STRING);
        }
        catch
        {
            System.Console.Error.WriteLine("An exception has occured during the import of the SBML model");
            System.Environment.Exit(1);
        }
        // check if the import was successful
        int mostSevere = CCopasiMessage.getHighestSeverity();

        // if it was a filtered error, we convert it to an unfiltered type
        // the filtered error messages have the same value as the unfiltered, but they
        // have the 7th bit set which basically adds 128 to the value
        mostSevere = mostSevere & 127;

        // we assume that the import succeeded if the return value is true and
        // the most severe error message is not an error or an exception
        if (result != true && mostSevere < CCopasiMessage.ERROR)
        {
            System.Console.Error.WriteLine("Sorry. Model could not be imported.");
            System.Environment.Exit(1);
        }

        // get the trajectory task object
        CSteadyStateTask task = (CSteadyStateTask)dataModel.getTask("Steady-State");

        CCopasiMessage.clearDeque();

        try
        {
            // now we run the actual trajectory
            task.processWithOutputFlags(true, (int)CCopasiTask.ONLY_TIME_SERIES);
        }
        catch
        {
            System.Console.Error.WriteLine("Error. Running the scan failed.");

            String lastErrors = task.getProcessError();
            // check if there are additional error messages
            if (!string.IsNullOrEmpty(lastErrors))
            {
                // print the messages in chronological order
                System.Console.Error.WriteLine(lastErrors);
            }

            System.Environment.Exit(1);
        }

        // now we can get the result of the steady state calculation, e.g. the jacobian
        // matrix of the model at the steady state
        // here we can either get the jacobian as we did in example 8 as a matrix with
        // getJacobian, or we can use getJacobianAnnotated to get an annotated matrix
        // Corresponding methods for the reduced jacobian are getJacobianX and getJacobianXAnnotated
        CDataArray aj = task.getJacobianAnnotated();

        Debug.Assert((aj != null));

        if (aj != null)
        {
            // we do the output, but as in contrast to the jacobian in example 8,
            // we now have all the information for the output in one place

            // first the array annotation can tell us how many dimensions it has.
            // Since the matrix is a 2D array, it should have 2 dimensions
            Debug.Assert((aj.dimensionality() == 2));
            // since the matrix has a dimensionality of 2, the inde for the underlaying abstract array
            // object is a vector with two unsigned int elements
            // First element is the index for the outer dimension and the second element is the index
            // for the inner dimension
            SizeTStdVector index = new SizeTStdVector();
            // The constructor does not seem to interpret an integer argument
            // as the size
            // I though that in C# we might be able to achieve this using the Capacity property
            // but that didn't work. Maybe I was using it incorrectly since I don't really know C#
            // So for now, we just add two elements to the vector which seems to do the trick.
            index.Add(0);
            index.Add(0);
            // since the rows and columns have the same annotation for the jacobian, it doesn't matter
            // for which dimension we get the annotations
            StringStdVector annotations = aj.getAnnotationsString(1);
            System.Console.Out.NewLine = "";
            System.Console.WriteLine(System.String.Format("Jacobian Matrix:{0}{0}", System.Environment.NewLine));
            System.Console.Out.WriteLine(System.String.Format("{0,7}", " "));

            for (int i = 0; i < annotations.Count; ++i)
            {
                Console.Out.WriteLine(System.String.Format("{0,7}", annotations[i]));
            }

            Console.WriteLine(System.String.Format("{0}", System.Environment.NewLine));

            for (int i = 0; i < annotations.Count; ++i)
            {
                System.Console.Out.WriteLine(System.String.Format("{0,7} ", annotations[i]));
                index[0] = (uint)i;

                for (int j = 0; j < annotations.Count; ++j)
                {
                    index[1] = (uint)j;
                    System.Console.Out.WriteLine(System.String.Format("{0,7:G2} ", aj.array().get(index)));
                }
                System.Console.WriteLine(System.String.Format("{0}", System.Environment.NewLine));
            }
        }
        System.Environment.Exit(0);
    }
Ejemplo n.º 15
0
    static void Main()
    {
        Debug.Assert(CRootContainer.getRoot() != null);
        // create a new datamodel
        CDataModel dataModel = CRootContainer.addDatamodel();

        Debug.Assert(CRootContainer.getDatamodelList().size() == 1);
        // get the model from the datamodel
        CModel model = dataModel.getModel();

        Debug.Assert(model != null);
        model.setVolumeUnit(CUnit.fl);
        model.setTimeUnit(CUnit.s);
        model.setQuantityUnit(CUnit.fMol);
        CModelValue fixedModelValue = model.createModelValue("F");

        Debug.Assert(fixedModelValue != null);
        fixedModelValue.setStatus(CModelEntity.Status_FIXED);
        fixedModelValue.setInitialValue(3.0);
        CModelValue variableModelValue = model.createModelValue("V");

        Debug.Assert(variableModelValue != null);
        variableModelValue.setStatus(CModelEntity.Status_ASSIGNMENT);
        // we create a very simple assignment that is easy on the optimization
        // a parabole with the minimum at x=6 should do just fine
        string s = fixedModelValue.getValueReference().getCN().getString();

        s = "(<" + s + "> - 6.0)^2";
        variableModelValue.setExpression(s);
        // now we compile the model and tell COPASI which values have changed so
        // that COPASI can update the values that depend on those
        model.compileIfNecessary();
        ObjectStdVector changedObjects = new ObjectStdVector();

        changedObjects.Add(fixedModelValue.getInitialValueReference());
        changedObjects.Add(variableModelValue.getInitialValueReference());
        model.updateInitialValues(changedObjects);

        // now we set up the optimization

        // we want to do an optimization for the time course
        // so we have to set up the time course task first
        CTrajectoryTask timeCourseTask = (CTrajectoryTask)dataModel.getTask("Time-Course");

        Debug.Assert(timeCourseTask != null);
        // since for this example it really doesn't matter how long we run the time course
        // we run for 1 second and calculate 10 steps
        // run a deterministic time course
        timeCourseTask.setMethodType(CTaskEnum.Method_deterministic);

        // pass a pointer of the model to the problem
        timeCourseTask.getProblem().setModel(dataModel.getModel());

        // get the problem for the task to set some parameters
        CTrajectoryProblem problem = (CTrajectoryProblem)timeCourseTask.getProblem();

        Debug.Assert(problem != null);

        // simulate 10 steps
        problem.setStepNumber(10);
        // start at time 0
        dataModel.getModel().setInitialTime(0.0);
        // simulate a duration of 1 time units
        problem.setDuration(1);
        // tell the problem to actually generate time series data
        problem.setTimeSeriesRequested(true);

        // get the optimization task
        COptTask optTask = (COptTask)dataModel.getTask("Optimization");

        Debug.Assert(optTask != null);
        // we want to use Levenberg-Marquardt as the optimization method
        optTask.setMethodType(CTaskEnum.Method_LevenbergMarquardt);

        // next we need to set subtask type on the problem
        COptProblem optProblem = (COptProblem)optTask.getProblem();

        Debug.Assert(optProblem != null);
        optProblem.setSubtaskType(CTaskEnum.Task_timeCourse);

        // we create the objective function
        // we want to minimize the value of the variable model value at the end of
        // the simulation
        // the objective function is normally minimized
        string objectiveFunction = variableModelValue.getObject(new CCommonName("Reference=Value")).getCN().getString();

        // we need to put the angled brackets around the common name of the object
        objectiveFunction = "<" + objectiveFunction + ">";
        // now we set the objective function in the problem
        optProblem.setObjectiveFunction(objectiveFunction);

        // now we create the optimization items
        // i.e. the model elements that have to be changed during the optimization
        // in order to get to the optimal solution
        COptItem optItem = optProblem.addOptItem(new CCommonName(fixedModelValue.getObject(new CCommonName("Reference=InitialValue")).getCN()));

        // we want to change the fixed model value from -100 to +100 with a start
        // value of 50
        optItem.setStartValue(50.0);
        optItem.setLowerBound(new CCommonName("-100"));
        optItem.setUpperBound(new CCommonName("100"));

        // now we set some parameters on the method
        // these parameters are specific to the method type we set above
        // (in this case Levenberg-Marquardt)
        COptMethod optMethod = (COptMethod)optTask.getMethod();

        Debug.Assert(optMethod != null);

        // now we set some method parameters for the optimization method
        // iteration limit
        CCopasiParameter parameter = optMethod.getParameter("Iteration Limit");

        Debug.Assert(parameter != null);
        parameter.setIntValue(2000);
        // tolerance
        parameter = optMethod.getParameter("Tolerance");
        Debug.Assert(parameter != null);
        parameter.setDblValue(1.0e-5);

        // create a report with the correct filename and all the species against
        // time.
        CReportDefinitionVector reports = dataModel.getReportDefinitionList();
        // create a new report definition object
        CReportDefinition report = reports.createReportDefinition("Report", "Output for optimization");

        // set the task type for the report definition to timecourse
        report.setTaskType(CTaskEnum.Task_optimization);
        // we don't want a table
        report.setIsTable(false);
        // the entries in the output should be seperated by a ", "
        report.setSeparator(new CCopasiReportSeparator(", "));

        // we need a handle to the header and the body
        // the header will display the ids of the metabolites and "time" for
        // the first column
        // the body will contain the actual timecourse data
        ReportItemVector header = report.getHeaderAddr();
        ReportItemVector body   = report.getBodyAddr();

        // in the report header we write two strings and a separator
        header.Add(new CRegisteredCommonName(new CDataString("best value of objective function").getCN().getString()));
        header.Add(new CRegisteredCommonName(report.getSeparator().getCN().getString()));
        header.Add(new CRegisteredCommonName(new CDataString("initial value of F").getCN().getString()));
        // in the report body we write the best value of the objective function and
        // the initial value of the fixed parameter separated by a komma
        body.Add(new CRegisteredCommonName(optProblem.getObject(new CCommonName("Reference=Best Value")).getCN().getString()));
        body.Add(new CRegisteredCommonName(report.getSeparator().getCN().getString()));
        body.Add(new CRegisteredCommonName(fixedModelValue.getObject(new CCommonName("Reference=InitialValue")).getCN().getString()));


        // set the report for the task
        optTask.getReport().setReportDefinition(report);
        // set the output filename
        optTask.getReport().setTarget("example5.txt");
        // don't append output if the file exists, but overwrite the file
        optTask.getReport().setAppend(false);


        bool result = false;

        try
        {
            result = optTask.processWithOutputFlags(true, (int)CCopasiTask.ONLY_TIME_SERIES);
        }
        catch (System.ApplicationException e)
        {
            System.Console.Error.WriteLine("ERROR: " + e.Message);
            String lastErrors = optTask.getProcessError();
            // check if there are additional error messages
            if (!string.IsNullOrEmpty(lastErrors))
            {
                // print the messages in chronological order
                System.Console.Error.WriteLine(lastErrors);
            }

            System.Environment.Exit(1);
        }
        if (!result)
        {
            System.Console.Error.WriteLine("Running the optimization failed.");
            String lastErrors = optTask.getProcessError();
            // check if there are additional error messages
            if (!string.IsNullOrEmpty(lastErrors))
            {
                // print the messages in chronological order
                System.Console.Error.WriteLine(lastErrors);
            }

            System.Environment.Exit(1);
        }
        // now we check if the optimization actually got the correct result
        // the best value it should have is 0 and the best parameter value for
        // that result should be 6 for the initial value of the fixed parameter
        double bestValue = optProblem.getSolutionValue();

        Debug.Assert(System.Math.Abs(bestValue) < 1e-3);
        // we should only have one solution variable since we only have one
        // optimization item
        Debug.Assert(optProblem.getSolutionVariables().size() == 1);
        double solution = optProblem.getSolutionVariables().get(0);

        Debug.Assert(System.Math.Abs((solution - 6.0) / 6.0) < 1e-3);
    }