static void Main() { Debug.Assert(CCopasiRootContainer.getRoot() != null); // create a new datamodel CCopasiDataModel dataModel = CCopasiRootContainer.addDatamodel(); Debug.Assert(CCopasiRootContainer.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.FIXED); fixedModelValue.setInitialValue(3.0); CModelValue variableModelValue = model.createModelValue("V"); Debug.Assert(variableModelValue != null); variableModelValue.setStatus(CModelEntity.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.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.LevenbergMarquardt); // next we need to set subtask type on the problem COptProblem optProblem = (COptProblem)optTask.getProblem(); Debug.Assert(optProblem != null); optProblem.setSubtaskType(CTaskEnum.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 CCopasiObjectName("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 CCopasiObjectName(fixedModelValue.getObject(new CCopasiObjectName("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 CCopasiObjectName("-100")); optItem.setUpperBound(new CCopasiObjectName("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.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 CRegisteredObjectName(new CCopasiStaticString("best value of objective function").getCN().getString())); header.Add(new CRegisteredObjectName(report.getSeparator().getCN().getString())); header.Add(new CRegisteredObjectName(new CCopasiStaticString("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 CRegisteredObjectName(optProblem.getObject(new CCopasiObjectName("Reference=Best Value")).getCN().getString())); body.Add(new CRegisteredObjectName(report.getSeparator().getCN().getString())); body.Add(new CRegisteredObjectName(fixedModelValue.getObject(new CCopasiObjectName("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); }
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); } }
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); } }