COPASI API  4.16.103
SEDMLImporter.cpp
Go to the documentation of this file.
1 // Copyright (C) 2013 - 2014 by Pedro Mendes, Virginia Tech Intellectual
2 // Properties, Inc., University of Heidelberg, and The University
3 // of Manchester.
4 // All rights reserved.
5 
6 /**
7  * SEDMLImporter.cpp
8  * $Rev: $: Revision of last commit
9  * $Author: $: Author of last commit
10  * $Date: $: Date of last commit
11  * $HeadURL: $
12  * $Id: $
13  */
14 
15 #include <iostream>
16 #include <vector>
17 #include <string>
18 #include <sstream>
19 #include <map>
20 #include <limits>
21 #include <cmath>
22 #include <algorithm>
23 
24 #include <sedml/SedTypes.h>
25 #include <sbml/math/FormulaFormatter.h>
26 
27 #include "copasi.h"
28 
29 #include "report/CKeyFactory.h"
30 #include "model/CModel.h"
31 #include "model/CCompartment.h"
32 #include "model/CMetab.h"
33 #include "model/CReaction.h"
34 #include "model/CModelValue.h"
35 #include "model/CEvent.h"
36 #include "function/CNodeK.h"
37 #include "function/CFunctionDB.h"
39 #include "function/CExpression.h"
42 #include "utilities/CCopasiTree.h"
49 #include "commandline/COptions.h"
50 
53 
55 
56 //TODO SEDML
59 #include "sbml/SBMLImporter.h"
60 #include "utilities/CDirEntry.h"
62 #include "utilities/CCopasiTask.h"
65 
67 
69 #include <scan/CScanTask.h>
70 
71 #include "SEDMLImporter.h"
72 #include "SEDMLUtils.h"
73 
74 // static
76 {
77  return
78  x < 0.0 ? -floor(-x + 0.5) : floor(x + 0.5);
79 }
80 
82 {mpImportHandler = pHandler;}
83 
85 {return mpImportHandler;}
86 
88 {return mArchiveFileName;}
89 
90 /**
91  * Creates and returns a COPASI CTrajectoryTask from the SEDML simulation
92  * given as argument.
93  */
94 void SEDMLImporter::updateCopasiTaskForSimulation(SedSimulation* sedmlsim,
95  std::map<CCopasiObject*, SedBase*>& copasi2sedmlmap)
96 {
97 
98  switch (sedmlsim->getTypeCode())
99  {
100  case SEDML_SIMULATION_UNIFORMTIMECOURSE:
101  {
102 
103  CTrajectoryTask *tTask = static_cast<CTrajectoryTask*>((*mpDataModel->getTaskList())["Time-Course"]);
104  tTask->setScheduled(true);
105 
106  CTrajectoryProblem* tProblem = static_cast<CTrajectoryProblem*>(tTask->getProblem());
107  SedUniformTimeCourse* tc = static_cast<SedUniformTimeCourse*>(sedmlsim);
108  tProblem->setOutputStartTime(tc->getOutputStartTime());
109  tProblem->setDuration(tc->getOutputEndTime() - tc->getOutputStartTime());
110  tProblem->setStepNumber(tc->getNumberOfPoints());
111  tProblem->setContinueSimultaneousEvents(true);
112 
113  // TODO read kisao terms
114  if (tc->isSetAlgorithm())
115  {
116  const SedAlgorithm* alg = tc->getAlgorithm();
117 
118  if (alg->isSetKisaoID())
119  {
120  if (alg->getKisaoID() == SEDML_KISAO_STOCHASTIC)
121  {
123  }
124  }
125  }
126 
127  break;
128  }
129 
130  case SEDML_SIMULATION_ONESTEP:
131  {
132 
133  CTrajectoryTask *tTask = static_cast<CTrajectoryTask*>((*mpDataModel->getTaskList())["Time-Course"]);
134  tTask->setScheduled(true);
135 
136  CTrajectoryProblem* tProblem = static_cast<CTrajectoryProblem*>(tTask->getProblem());
137  SedOneStep* step = static_cast<SedOneStep*>(sedmlsim);
138  tProblem->setOutputStartTime(0);
139  tProblem->setDuration(step->getStep());
140  tProblem->setStepNumber(1);
141 
142  // TODO read kisao terms
143 
144  break;
145  }
146 
147  case SEDML_SIMULATION_STEADYSTATE:
148  {
149  // nothing to be done for this one
150  CSteadyStateTask *tTask = static_cast<CSteadyStateTask*>((*mpDataModel->getTaskList())["Steady-State"]);
151  tTask->setScheduled(true);
152 
153  // TODO read kisao terms
154  //CCopasiProblem* tProblem = static_cast<CCopasiProblem*>(tTask->getProblem());
155  //SedSteadyState* tc = static_cast<SedSteadyState*>(sedmlsim);
156 
157  break;
158  }
159 
160  default:
161  CCopasiMessage(CCopasiMessage::EXCEPTION, "SEDMLImporter Error: encountered unknown simulation.");
162  break;
163  }
164 }
165 
166 bool isTC(const SedTask* task)
167 {
168  if (task == NULL || task->getSedDocument() == NULL) return false;
169 
170  const SedDocument* doc = task->getSedDocument();
171 
172  if (task->isSetSimulationReference())
173  {
174  const SedSimulation* sim = doc->getSimulation(task->getSimulationReference());
175 
176  if (sim != NULL && (
177  sim->getTypeCode() == SEDML_SIMULATION_UNIFORMTIMECOURSE))
178  return true;
179  }
180 
181  return false;
182 }
183 
184 bool isScan(const SedTask* task)
185 {
186 
187  if (task == NULL || task->getSedDocument() == NULL) return false;
188 
189  const SedDocument* doc = task->getSedDocument();
190 
191  if (task->isSetSimulationReference())
192  {
193  const SedSimulation* sim = doc->getSimulation(task->getSimulationReference());
194 
195  if (sim != NULL && (
196  sim->getTypeCode() == SEDML_SIMULATION_STEADYSTATE ||
197  sim->getTypeCode() == SEDML_SIMULATION_ONESTEP ||
198  sim->getTypeCode() == SEDML_SIMULATION_UNIFORMTIMECOURSE))
199  return true;
200  }
201 
202  return false;
203 }
204 
205 bool isScan(const SedRepeatedTask* task)
206 {
207  if (task == NULL || task->getSedDocument() == NULL) return false;
208 
209  const SedDocument* doc = task->getSedDocument();
210 
211  if (task->isSetSimulationReference())
212  {
213  const SedSimulation* sim = doc->getSimulation(task->getSimulationReference());
214 
215  if (sim != NULL && (
216  sim->getTypeCode() == SEDML_SIMULATION_STEADYSTATE ||
217  sim->getTypeCode() == SEDML_SIMULATION_ONESTEP ||
218  sim->getTypeCode() == SEDML_SIMULATION_UNIFORMTIMECOURSE))
219  return true;
220  }
221 
222  for (size_t i = 0; i < task->getNumSubTasks(); ++i)
223  {
224  const SedSubTask* subTask = task->getSubTask(i);
225  const SedTask* t = doc->getTask(subTask->getTask());
226 
227  if (isScan(t)) return true;
228  }
229 
230  return false;
231 }
232 
234  COutputDefinitionVector *pLotList, CModel* pModel,
235  SedDocument *pSEDMLDocument,
236  std::map<CCopasiObject*, SedBase*>& copasi2sedmlmap)
237 {
238  size_t i, numOutput = pSEDMLDocument->getNumOutputs();
239 
240  std::map<CCopasiObject*, SBase*>& copasiMap = pModel->getObjectDataModel()->getCopasi2SBMLMap();
241 
243 
244  for (i = 0; i < numOutput; ++i)
245  {
246  SedOutput* current = pSEDMLDocument->getOutput(i);
247 
248  switch (current->getTypeCode())
249  {
250  case SEDML_OUTPUT_REPORT:
251  {
252  SedReport* r = static_cast<SedReport*>(current);
253  std::string name = current->isSetName() ? current->getName() : current->getId();
254  CReportDefinition* def = new CReportDefinition(name);
255  int count = 0;
256 
257  // creation fails on duplicated name!
258  while (def == NULL)
259  {
260  def = new CReportDefinition(SEDMLUtils::getNextId(name + " ", ++count));
261  }
262 
263  def->setComment("Import from SED-ML");
264 
265  def->setIsTable(false);
267 
268  std::vector<CRegisteredObjectName>* pHeader = def->getHeaderAddr();
269  std::vector<CRegisteredObjectName>* pBody = def->getBodyAddr();
270 
271  bool isTimeCourse = false;
272  bool isScanTask = false;
273 
274  for (size_t i = 0; i < r->getNumDataSets(); ++i)
275  {
276  SedDataSet* ds = r->getDataSet(i);
277  const SedDataGenerator* generator = pSEDMLDocument->getDataGenerator(ds->getDataReference());
278  const CCopasiObject * tmp = SEDMLUtils::resolveDatagenerator(pModel, generator);
279 
280  if (generator == NULL || tmp == NULL) continue;
281 
282  std::string title = ds->isSetLabel() ? ds->getLabel() : generator->isSetName() ? generator->getName() : ds->getId();
283 
284  pHeader->push_back(CCopasiStaticString(title).getCN());
285  pHeader->push_back(def->getSeparator().getCN());
286 
287  pBody->push_back(tmp->getCN());
288  pBody->push_back(def->getSeparator().getCN());
289 
290  if (!isTimeCourse && !isScanTask)
291  for (size_t j = 0; j < generator->getNumVariables(); ++j)
292  {
293  const SedTask* t = mpSEDMLDocument->getTask(generator->getVariable(j)->getTaskReference());
294 
295  if (t == NULL) continue;
296 
297  isScanTask = t->getTypeCode() == SEDML_TASK_REPEATEDTASK && isScan((const SedRepeatedTask*)t);
298  isTimeCourse = isTC(t);
299  }
300  }
301 
302  // assign report to scan task
303  if (isScanTask)
304  {
305  mReportMap[def] = "Scan";
306  }
307 
308  // assign report to Timecourse task
309  if (isTimeCourse)
310  {
311  mReportMap[def] = "Time-Course";
312  }
313 
314  break;
315  }
316 
317  case SEDML_OUTPUT_PLOT2D: //get the curves data
318  {
319  SedPlot2D* p = static_cast<SedPlot2D*>(current);
320  std::string name = current->isSetName() ? current->getName() :
321  current->getId();
322  CPlotSpecification* pPl = pLotList->createPlotSpec(
323  name, CPlotItem::plot2d);
324 
325  int count = 0;
326 
327  while (pPl == NULL)
328  {
329  // creation fails on duplicated name!
330  pPl = pLotList->createPlotSpec(
331  SEDMLUtils::getNextId(name + " ", ++count), CPlotItem::plot2d);
332  }
333 
334  bool logX = false;
335  bool logY = false;
336 
337  for (unsigned int ic = 0; ic < p->getNumCurves(); ++ic)
338  {
339  SedCurve *curve = p->getCurve(ic);
340 
341  std::string xDataReference = curve->getXDataReference();
342  std::string yDataReference = curve->getYDataReference();
343 
344  const SedDataGenerator* xGenerator = pSEDMLDocument->getDataGenerator(xDataReference);
345  const SedDataGenerator* yGenerator = pSEDMLDocument->getDataGenerator(yDataReference);
346 
347  //create the curves
348  const CCopasiObject * tmpX = SEDMLUtils::resolveDatagenerator(pModel, xGenerator);
349  const CCopasiObject * tmpY = SEDMLUtils::resolveDatagenerator(pModel, yGenerator);
350 
351  if (tmpX != NULL && tmpY != NULL)
352  {
353 
354  std::string itemTitle;
355 
356  if (curve->isSetName())
357  itemTitle = curve->getName();
358  else if (yGenerator != NULL && yGenerator->isSetName())
359  itemTitle = yGenerator->getName();
360  else
361  itemTitle = tmpY->getObjectDisplayName();
362 
363  CPlotItem * plItem = pPl->createItem(itemTitle, CPlotItem::curve2d);
364  plItem->setValue("Line width", 2.0);
365  plItem->addChannel(tmpX->getCN());
366  plItem->addChannel(tmpY->getCN());
367  }
368 
369  logX = logX || (curve->isSetLogX() && curve->getLogX());
370  logY = logY || (curve->isSetLogY() && curve->getLogY());
371  }
372 
373  pPl->setLogX(logX);
374  pPl->setLogY(logY);
375  break;
376  }
377 
378  default:
379  CCopasiMessage(CCopasiMessage::EXCEPTION, "SEDMLImporter Error: No support for this plot: typecode = %d", current->getTypeCode());
380  break;
381  }
382  }
383 }
384 
385 /**
386  * Function reads an SEDML file with libsedml and converts it to a Copasi CModel
387  */
388 CModel* SEDMLImporter::readSEDML(std::string filename,
389  CProcessReport* pImportHandler,
390  SBMLDocument *& pSBMLDocument,
391  SedDocument*& pSedDocument,
392  std::map<CCopasiObject*, SedBase*>& copasi2sedmlmap,
393  std::map<CCopasiObject*, SBase*>& copasi2sbmlmap,
394  CListOfLayouts *& prLol,
395  COutputDefinitionVector * &plotList,
396  CCopasiDataModel* pDataModel)
397 {
398  // convert filename to the locale encoding
399  std::ifstream file(CLocaleString::fromUtf8(filename).c_str());
400 
401  if (!file)
402  {
403  CCopasiMessage(CCopasiMessage::EXCEPTION, MCSEDML + 5, filename.c_str());
404  }
405 
406  std::ostringstream stringStream;
407  char c;
408 
409  while (file.get(c))
410  {
411  stringStream << c;
412  }
413 
414  file.clear();
415  file.close();
416 
417  //using libzip to read SEDML file
418  /* SEDMLUtils utils;
419  std::string SEDMLFileName, fileContent("");
420  SEDMLFileName = "sedml.xml";
421 
422  int success = utils.processArchive(filename, SEDMLFileName, fileContent);*/
423 
424  pDataModel->setSEDMLFileName(filename);
425 
426  return this->parseSEDML(stringStream.str(), pImportHandler,
427  pSBMLDocument, pSedDocument, copasi2sedmlmap, copasi2sbmlmap, prLol, plotList, pDataModel);
428 }
429 /**
430  * Function parses an SEDML document with libsedml and converts it to a COPASI CModel
431  * object which is returned. Deletion of the returned pointer is up to the
432  * caller.
433  */
434 CModel*
435 SEDMLImporter::parseSEDML(const std::string& sedmlDocumentText,
436  CProcessReport* pImportHandler,
437  SBMLDocument *& pSBMLDocument,
438  SedDocument *& pSEDMLDocument,
439  std::map<CCopasiObject*, SedBase*>& copasi2sedmlmap,
440  std::map<CCopasiObject*, SBase*>& copasi2sbmlmap,
441  CListOfLayouts *& prLol,
442  COutputDefinitionVector * & pPlotList,
443  CCopasiDataModel* pDataModel)
444 {
445  mReportMap.clear();
446  this->mUsedSEDMLIdsPopulated = false;
447 
448  mpDataModel = pDataModel;
449  assert(mpDataModel != NULL);
450 
451  this->mpCopasiModel = NULL;
452 
453  SedReader reader;
454 
455  mImportStep = 0;
456 
457  if (mpImportHandler)
458  {
459  mpImportHandler->setName("Importing SED-ML file...");
460  mTotalSteps = 11;
462  &mTotalSteps);
463  }
464 
465  unsigned C_INT32 step = 0, totalSteps = 0;
466  size_t hStep = C_INVALID_INDEX;
467 
468  if (this->mpImportHandler != 0)
469  {
470  step = 0;
471  totalSteps = 1;
472  hStep = mpImportHandler->addItem("Reading SED-ML file...", step,
473  &totalSteps);
474  }
475 
476  mpSEDMLDocument = reader.readSedMLFromString(sedmlDocumentText);
477 
478  assert(mpSEDMLDocument != NULL);
479 
480  if (mpImportHandler)
481  mpImportHandler->finishItem(hStep);
482 
483  if (this->mpImportHandler != 0)
484  {
485  step = 0;
486  totalSteps = 1;
487  hStep = mpImportHandler->addItem("Checking consistency...", step,
488  &totalSteps);
489  }
490 
491  if (mpImportHandler)
492  mpImportHandler->finishItem(hStep);
493 
494  int fatal = -1;
495  unsigned int i, iMax = mpSEDMLDocument->getNumErrors();
496 
497  for (i = 0; (i < iMax) && (fatal == -1); ++i)
498  {
499  const SedError* pSEDMLError = mpSEDMLDocument->getError(i);
500 
502 
503  switch (pSEDMLError->getSeverity())
504  {
505 
506  case LIBSEDML_SEV_WARNING:
507 
508  // if issued as warning, this message is to be disregarded,
509  // it was a bug in earlier versions of libSEDML
510  if (pSEDMLError->getErrorId() == SedInvalidNamespaceOnSed)
511  continue;
512 
513  if (mIgnoredSEDMLMessages.find(pSEDMLError->getErrorId())
514  != mIgnoredSEDMLMessages.end())
515  {
516  messageType = CCopasiMessage::WARNING_FILTERED;
517  }
518  else
519  {
520  messageType = CCopasiMessage::WARNING;
521  }
522 
523  CCopasiMessage(messageType, MCSEDML + 6, "WARNING",
524  pSEDMLError->getErrorId(), pSEDMLError->getLine(),
525  pSEDMLError->getColumn(),
526  pSEDMLError->getMessage().c_str());
527  break;
528 
529  case LIBSEDML_SEV_ERROR:
530 
531  if (mIgnoredSEDMLMessages.find(pSEDMLError->getErrorId())
532  != mIgnoredSEDMLMessages.end())
533  {
534  messageType = CCopasiMessage::ERROR_FILTERED;
535  }
536 
537  CCopasiMessage(messageType, MCSEDML + 6, "ERROR",
538  pSEDMLError->getErrorId(), pSEDMLError->getLine(),
539  pSEDMLError->getColumn(),
540  pSEDMLError->getMessage().c_str());
541  break;
542 
543  case LIBSEDML_SEV_FATAL:
544 
545  // treat unknown as fatal
546  default:
547 
548  if (pSEDMLError->getErrorId() == 10804)
549  {
550  // this error indicates a problem with a notes element
551  // although libsedml flags this as fatal, we would still
552  // like to read the model
553  CCopasiMessage(messageType, MCSEDML + 6, "ERROR",
554  pSEDMLError->getErrorId(), pSEDMLError->getLine(),
555  pSEDMLError->getColumn(),
556  pSEDMLError->getMessage().c_str());
557  }
558  else
559  {
560  fatal = i;
561  }
562 
563  break;
564  }
565  }
566 
567  if (fatal != -1)
568  {
569  const XMLError* pSEDMLError = mpSEDMLDocument->getError(fatal);
571  pSEDMLError->getLine(), pSEDMLError->getColumn(),
572  pSEDMLError->getMessage().c_str());
573 
574  if (mpImportHandler)
576 
577  return NULL;
578  }
579 
580  if (mpSEDMLDocument->getListOfModels() == NULL)
581  {
583 
584  if (mpImportHandler)
586 
587  return NULL;
588  }
589 
590  //delete reader;
591  pSEDMLDocument = mpSEDMLDocument;
592  this->mLevel = pSEDMLDocument->getLevel();
593 
594  this->mOriginalLevel = this->mLevel;
595  this->mVersion = pSEDMLDocument->getVersion();
596 
597  importFirstSBMLModel(pImportHandler, pSBMLDocument, copasi2sbmlmap, prLol, pDataModel);
598 
599  pPlotList = new COutputDefinitionVector("OutputDefinitions", mpDataModel);
600  readListOfPlotsFromSedMLOutput(pPlotList, mpCopasiModel, pSEDMLDocument, copasi2sedmlmap);
601 
602  importTasks(copasi2sedmlmap);
603 
604  if (mpImportHandler)
606 
607  return mpCopasiModel;
608 
609  return NULL;
610 }
611 
612 void
613 SEDMLImporter::importTasks(std::map<CCopasiObject*, SedBase*>& copasi2sedmlmap)
614 {
615 
616  for (unsigned int i = 0; i < mpSEDMLDocument->getNumTasks(); ++i)
617  {
618  SedTask * current = mpSEDMLDocument->getTask(i);
619 
620  // skip taks for models we did not import
621  if (current->isSetModelReference() && current->getModelReference() != this->mImportedModel)
622  continue;
623 
624  switch (current->getTypeCode())
625  {
626  case SEDML_TASK:
627  {
628  SedSimulation* sedmlsim =
629  mpSEDMLDocument->getSimulation(current->getSimulationReference());
630  updateCopasiTaskForSimulation(sedmlsim, copasi2sedmlmap);
631  break;
632  }
633 
634  case SEDML_TASK_REPEATEDTASK:
635  {
636  SedRepeatedTask *repeat = static_cast<SedRepeatedTask*>(current);
637  SedRange* range = repeat->getRange(repeat->getRangeId());
638 
639  if (range == NULL || range->getTypeCode() != SEDML_RANGE_UNIFORMRANGE)
640  {
641  CCopasiMessage(CCopasiMessage::WARNING, "This version of COPASI only supports uniform ranges.");
642  continue;
643  }
644 
645  SedUniformRange* urange = static_cast<SedUniformRange*>(range);
646  CScanTask *tTask = static_cast<CScanTask*>((*mpDataModel->getTaskList())["Scan"]);
647  tTask->setScheduled(true);
648  CScanProblem *pProblem = static_cast<CScanProblem*>(tTask->getProblem());
649 
650  if (urange != NULL && repeat->getNumTaskChanges() == 0)
651  {
652  pProblem->addScanItem(CScanProblem::SCAN_REPEAT, urange->getNumberOfPoints());
653  }
654  else
655  {
656  for (unsigned int j = 0; j < repeat->getNumTaskChanges(); ++j)
657  {
658  SedSetValue* sv = repeat->getTaskChange(j);
659 
660  if (SBML_formulaToString(sv->getMath()) != sv->getRange())
661  {
663  "This version of COPASI only supports setValue elements that apply range values.");
664  }
665 
666  std::string target = sv->getTarget();
667  const CCopasiObject * obj = SEDMLUtils::resolveXPath(mpCopasiModel, target, true);
668 
669  if (obj == NULL)
670  {
671  CCopasiMessage(CCopasiMessage::WARNING, "This version of COPASI only supports modifications of initial values.");
672  continue;
673  }
674 
675  CCopasiParameterGroup*group = pProblem->addScanItem(CScanProblem::SCAN_LINEAR, urange->getNumberOfPoints(), obj);
676  *group->getParameter("Minimum")->getValue().pDOUBLE = urange->getStart();
677  *group->getParameter("Maximum")->getValue().pDOUBLE = urange->getEnd();
678  *group->getParameter("log")->getValue().pBOOL =
679  (!urange->isSetType() || urange->getType().empty() || urange->getType() == "linear") ? false
680  : true;
681  }
682  }
683 
684  if (repeat->getNumSubTasks() != 1)
685  {
686  CCopasiMessage(CCopasiMessage::WARNING, "This version of COPASI only supports repeatedTasks with one subtask.");
687  continue;
688  }
689 
690  pProblem->setContinueFromCurrentState(!repeat->getResetModel());
691 
692  SedSubTask* subTask = repeat->getSubTask(0);
693 
694  if (!subTask->isSetTask())
695  {
696  CCopasiMessage(CCopasiMessage::WARNING, "This version of COPASI only supports repeatedTasks with one subtask that has a valid task reference.");
697  continue;
698  }
699 
700  SedTask* actualSubTask = mpSEDMLDocument->getTask(subTask->getTask());
701 
702  if (actualSubTask == NULL || !actualSubTask->isSetSimulationReference())
703  {
704  CCopasiMessage(CCopasiMessage::WARNING, "This version of COPASI only supports repeatedTasks with one subtask that itself is a task with simulation reference.");
705  continue;
706  }
707 
708  int code = mpSEDMLDocument->getSimulation(actualSubTask->getSimulationReference())->getTypeCode();
709 
710  if (code == SEDML_SIMULATION_STEADYSTATE)
711  {
713  pProblem->setOutputInSubtask(false);
714  }
715  else if (code == SEDML_SIMULATION_ONESTEP || code == SEDML_SIMULATION_UNIFORMTIMECOURSE)
716  {
718  }
719 
720  break;
721  }
722 
723  default:
724  {
725  const char* name = SedTypeCode_toString(current->getTypeCode());
727  "Encountered unsupported Task type '%s'. This task cannot be imported in COPASI",
728  name != NULL ? name : "unknown");
729  }
730  }
731  }
732 
733  std::map<CReportDefinition*, std::string>::const_iterator it = mReportMap.begin();
734 
735  for (; it != mReportMap.end(); ++it)
736  {
737  mpDataModel->getReportDefinitionList()->add(it->first);
738  CReport& report = ((*mpDataModel->getTaskList())[it->second])->getReport();
739  report.setReportDefinition(it->first);
740  report.setTarget(it->second + ".txt");
741  report.setConfirmOverwrite(false);
742  report.setAppend(false);
743  }
744 }
745 
746 bool applyValueToModelParameter(CModelParameter* modelParameter, CCopasiObject *obj, double newValue)
747 {
748  if (modelParameter == NULL || obj == NULL) return false;
749 
750  size_t numChilren = modelParameter->getNumChildren();
751 
752  const CCopasiObjectName& cn = modelParameter->getCN();
753  const CCopasiObjectName& targetCN = obj->getCN();
754 
755  if (cn == targetCN)
756  {
757  modelParameter->setValue(newValue, CModelParameter::Concentration);
758  return true;
759  }
760 
761  for (unsigned int i = 0; i < numChilren; ++i)
762  {
763  CModelParameter* current = const_cast<CModelParameter* >(modelParameter->getChild(i));
764 
765  if (applyValueToModelParameter(current, obj, newValue))
766  return true;
767  }
768 
769  return false;
770 }
771 
773 {
775 
776  while (it != set.end())
777  {
778  if (applyValueToModelParameter(*it, obj, newValue))
779  return true;
780 
781  ++it;
782  }
783 
784  return false;
785 }
786 
787 bool applyAttributeChange(CModel* pCopasiModel, CModelParameterSet& set, const std::string& target, const std::string& newValue)
788 {
789  CCopasiObject *obj = const_cast<CCopasiObject*>(SEDMLUtils::resolveXPath(pCopasiModel, target, true));
790 
791  if (obj == NULL)
792  return false;
793 
794  // convert the string to double
795  std::stringstream str;
796  str << newValue;
797  double result;
798  str >> result;
799 
800  // set the value
801  applyValueToParameterSet(set, obj->getObjectParent(), result);
802  return true;
803 }
804 
806  SBMLDocument *& pSBMLDocument,
807  std::map<CCopasiObject*, SBase*>& copasi2sbmlmap,
808  CListOfLayouts *& prLol,
809  CCopasiDataModel* pDataModel)
810 {
811  std::string SBMLFileName, fileContent;
812 
813  unsigned int ii, iiMax = mpSEDMLDocument->getListOfModels()->size();
814 
815  if (iiMax < 1)
816  {
818  }
819 
820  if (iiMax > 1)
821  {
822  CCopasiMessage(CCopasiMessage::WARNING, "COAPSI currently only supports the import of SED-ML models, that involve one model only. Only the simulations for the first model will be imported");
823  }
824 
825  std::string modelSource = ""; //must be taken from SEDML document.
826  std::string modelId = ""; // to ensure only one model is imported since only one model in SEDML file is supported
827  SedModel* sedmlModel = NULL;
828 
829  for (ii = 0; ii < iiMax; ++ii)
830  {
831  sedmlModel = mpSEDMLDocument->getModel(ii);
832 
833  // need to also allow for the specific urns like
834  // urn:sedml:language:sbml.level-3.version-1
835  if (sedmlModel->getLanguage().find("urn:sedml:language:sbml") == std::string::npos)
837  "Sorry currently, only SBML models are supported.");
838 
839  if (sedmlModel->getSource() != modelId)
840  {
841  modelId = sedmlModel->getId();
842 
843  if ((sedmlModel->getListOfChanges()->size()) > 0)
844  CCopasiMessage(CCopasiMessage::WARNING, "Currently there is only limited support for "
845  "changing model entities. Only value changes are imported into the model.");
846 
847  modelSource = sedmlModel->getSource();
848  break;
849  }
850  }
851 
852  assert(modelSource != "");
853 
854  //process the archive file and get the SBML model file
855  //SEDMLUtils utils;
856  //int success = utils.processArchive(pDataModel->getSEDMLFileName(), SBMLFileName, fileContent);
857 
858  std::string FileName;
859 
860  if (CDirEntry::exist(modelSource))
861  FileName = modelSource;
862  else
863  FileName = CDirEntry::dirName(pDataModel->getSEDMLFileName())
864  + CDirEntry::Separator + modelSource;
865 
866  std::ifstream file(CLocaleString::fromUtf8(FileName).c_str());
867 
868  if (!file)
869  {
871  FileName.c_str());
872  }
873 
874  //set the SBML file name for later use
875  pDataModel->setSBMLFileName(FileName);
876  std::ostringstream sbmlStringStream;
877  char c;
878 
879  while (file.get(c))
880  {
881  sbmlStringStream << c;
882  }
883 
884  file.clear();
885  file.close();
886 
887  std::ifstream File(CLocaleString::fromUtf8(FileName).c_str());
888 
889  SBMLImporter importer;
890  // Right now we always import the COPASI MIRIAM annotation if it is there.
891  // Later this will be settable by the user in the preferences dialog
892  importer.setImportCOPASIMIRIAM(true);
893  importer.setImportHandler(pImportHandler);
894 
895  mpCopasiModel = NULL;
896 
897  std::map<CCopasiObject*, SBase*> Copasi2SBMLMap;
898 
899  try
900  {
901  mpCopasiModel = importer.parseSBML(sbmlStringStream.str(),
902  CCopasiRootContainer::getFunctionList(), pSBMLDocument,
903  Copasi2SBMLMap, prLol, mpDataModel);
904  }
905 
906  catch (CCopasiException & except)
907  {
908  importer.restoreFunctionDB();
909  importer.deleteCopasiModel();
910  // popData();
911 
912  throw except;
913  }
914 
915  if (mpCopasiModel == NULL)
916  {
917  importer.restoreFunctionDB();
918  importer.deleteCopasiModel();
919  // popData();
920  return NULL;
921  }
922 
923  mImportedModel = modelId;
924 
925  // apply possible changes to the model
926  if (sedmlModel != NULL && sedmlModel->getNumChanges() > 0)
927  {
929  bool valueChanged = false;
930 
931  for (unsigned int i = 0; i < sedmlModel->getNumChanges(); ++i)
932  {
933  SedChangeAttribute* change = dynamic_cast<SedChangeAttribute*>(sedmlModel->getChange(i));
934 
935  if (change == NULL) continue;
936 
937  const std::string& target = change->getTarget();
938  const std::string& newValue = change->getNewValue();
939 
940  if (!applyAttributeChange(mpCopasiModel, set, target, newValue))
941  {
942  CCopasiMessage(CCopasiMessage::WARNING, "Could not apply change for target: '%s'", target.c_str());
943  }
944  }
945  }
946 
947  return mpCopasiModel;
948 }
949 
950 /**
951  * Constructor that initializes speciesMap and the FunctionDB object
952  */
954  mIgnoredSEDMLMessages(),
955  mIncompleteModel(false),
956  mLevel(0),
957  mOriginalLevel(0),
958  mVersion(0),
959  mpDataModel(NULL),
960  mpCopasiModel(NULL),
961  mpSEDMLDocument(NULL),
962  mpImportHandler(NULL),
963  mImportStep(0),
964  mhImportStep(C_INVALID_INDEX),
965  mTotalSteps(0),
966  mUsedSEDMLIds(),
967  mUsedSEDMLIdsPopulated(false),
968  mImportedModel(),
969  mReportMap()
970 {
971 
972  this->mIgnoredSEDMLMessages.insert(10501);
973 }
974 
976 {
977 }
978 
979 /**
980  * Destructor that does nothing.
981  */
983 {
984  mReportMap.clear();
985 }
986 
988 {
989  if (this->mpCopasiModel != NULL)
990  {
991  delete this->mpCopasiModel;
992  this->mpCopasiModel = NULL;
993  }
994 }
void setSubtask(CCopasiTask::Type type)
Header file of class CExpression.
CCopasiDataModel * getObjectDataModel()
void setImportCOPASIMIRIAM(bool import)
std::set< unsigned int > mIgnoredSEDMLMessages
Definition: SEDMLImporter.h:49
const CModelParameterSet & getModelParameterSet() const
Definition: CModel.cpp:1072
virtual std::string getObjectDisplayName(bool regular=true, bool richtext=false) const
bool setSBMLFileName(const std::string &fileName)
Header file of class CModelEntity and CModelValue.
std::string mArchiveFileName
Definition: SEDMLImporter.h:48
void restoreFunctionDB()
void setScheduled(const bool &scheduled)
std::vector< CModelParameter * >::iterator iterator
bool mUsedSEDMLIdsPopulated
Definition: SEDMLImporter.h:66
void readListOfPlotsFromSedMLOutput(COutputDefinitionVector *pPlotList, CModel *pModel, SedDocument *pSedDocument, std::map< CCopasiObject *, SedBase * > &copasi2sedmlmap)
CCopasiProblem * getProblem()
CModel * readSEDML(std::string filename, CProcessReport *pImportHandler, SBMLDocument *&pSBMLDocument, SedDocument *&pSedDocument, std::map< CCopasiObject *, SedBase * > &copasi2sedmlmap, std::map< CCopasiObject *, SBase * > &copasi2sbmlmap, CListOfLayouts *&prLol, COutputDefinitionVector *&plotList, CCopasiDataModel *pDataModel)
virtual CCopasiObjectName getCN() const
void setContinueSimultaneousEvents(const bool &continueSimultaneousEvents)
virtual const CModelParameter * getChild(const size_t &index) const
virtual bool setName(const std::string &name)
void deleteCopasiModel()
const CCopasiReportSeparator & getSeparator() const
void setImportHandler(CProcessReport *pHandler)
void addChannel(const CPlotDataChannelSpec &channel)
Definition: CPlotItem.cpp:223
void deleteCopasiModel()
#define MCXML
void updateCopasiTaskForSimulation(SedSimulation *sedmlsim, std::map< CCopasiObject *, SedBase * > &copasi2sedmlmap)
CModel * importFirstSBMLModel(CProcessReport *pImportHandler, SBMLDocument *&pSBMLDocument, std::map< CCopasiObject *, SBase * > &copasi2sbmlmap, CListOfLayouts *&prLol, CCopasiDataModel *pDataModel)
#define C_INVALID_INDEX
Definition: copasi.h:222
void setDuration(const C_FLOAT64 &duration)
const std::string getArchiveFileName()
void setSeparator(const CCopasiReportSeparator &Separator)
void setAppend(const bool &append)
Definition: CReport.cpp:98
void setConfirmOverwrite(const bool &confirmOverwrite)
Definition: CReport.cpp:104
CModel * parseSEDML(const std::string &sedmlDocumentText, CProcessReport *pImportHandler, SBMLDocument *&pSBMLDocument, SedDocument *&pSEDMLDocument, std::map< CCopasiObject *, SedBase * > &copasi2sedmlmap, std::map< CCopasiObject *, SBase * > &copasi2sbmlmap, CListOfLayouts *&prLol, COutputDefinitionVector *&plotList, CCopasiDataModel *pDataModel)
static const CCopasiObject * resolveDatagenerator(const CModel *model, const SedDataGenerator *dataReference)
Definition: SEDMLUtils.cpp:203
#define C_INT32
Definition: copasi.h:90
const CCopasiObjectName & getCN() const
unsigned int mLevel
Definition: SEDMLImporter.h:51
CPlotItem * createItem(const std::string &name, CPlotItem::Type type)
void setIsTable(bool table)
static std::string dirName(const std::string &path)
Definition: CDirEntry.cpp:135
CCopasiParameterGroup * addScanItem(CScanProblem::Type type, size_t steps=5, const CCopasiObject *obj=NULL)
bool applyValueToModelParameter(CModelParameter *modelParameter, CCopasiObject *obj, double newValue)
const CReportDefinitionVector * getReportDefinitionList() const
bool isScan(const SedTask *task)
virtual void setValue(const double &value, const Framework &framework)
virtual bool add(const CType &src)
void setComment(const std::string &comment)
CProcessReport * mpImportHandler
Definition: SEDMLImporter.h:60
size_t addItem(const std::string &name, const std::string &value, const std::string *pEndValue=NULL)
bool applyValueToParameterSet(CModelParameterSet &set, CCopasiObject *obj, double newValue)
static bool exist(const std::string &path)
Definition: CDirEntry.cpp:78
static const std::string Separator
Definition: CDirEntry.h:34
struct MESSAGES Message
CModel * parseSBML(const std::string &sbmlDocumentText, CFunctionDB *funDB, SBMLDocument *&pSBMLDocument, std::map< CCopasiObject *, SBase * > &copasi2sbmlmap, CListOfLayouts *&prLol, CCopasiDataModel *pDataModel)
std::map< CReportDefinition *, std::string > mReportMap
Definition: SEDMLImporter.h:70
virtual size_t getNumChildren() const
const Value & getValue() const
CCopasiVectorN< CCopasiTask > * getTaskList()
void setStepNumber(const unsigned C_INT32 &stepNumber)
bool setValue(const std::string &name, const CType &value)
unsigned int mVersion
Definition: SEDMLImporter.h:53
virtual bool finishItem(const size_t &handle)
CPlotSpecification * createPlotSpec(const std::string &name, CPlotItem::Type type=CPlotItem::plot2d)
CCopasiParameter * getParameter(const std::string &name)
static CFunctionDB * getFunctionList()
CModel * mpCopasiModel
Definition: SEDMLImporter.h:56
static C_FLOAT64 round(const C_FLOAT64 &x)
void setTarget(const std::string &target)
Definition: CReport.cpp:92
void setContinueFromCurrentState(bool aic)
void setOutputInSubtask(bool ois)
#define MCSEDML
void setImportHandler(CProcessReport *pHandler)
std::string mImportedModel
Definition: SEDMLImporter.h:68
SedDocument * mpSEDMLDocument
Definition: SEDMLImporter.h:58
unsigned int mOriginalLevel
Definition: SEDMLImporter.h:52
static const CCopasiObject * resolveXPath(const CModel *model, const std::string &xpath, bool initial=false)
Definition: SEDMLUtils.cpp:242
#define C_FLOAT64
Definition: copasi.h:92
bool isTC(const SedTask *task)
std::vector< CRegisteredObjectName > * getBodyAddr()
unsigned C_INT32 mTotalSteps
Definition: SEDMLImporter.h:63
CProcessReport * getImportHandlerAddr()
static std::string getNextId(const std::string &base, int count)
Definition: SEDMLUtils.cpp:294
size_t mhImportStep
Definition: SEDMLImporter.h:62
void setOutputStartTime(const C_FLOAT64 &endTime)
Definition: CModel.h:50
Header file of class CEvent.
static CLocaleString fromUtf8(const std::string &utf8)
void setReportDefinition(CReportDefinition *reportDef)
Definition: CReport.cpp:86
unsigned C_INT32 mImportStep
Definition: SEDMLImporter.h:61
CCopasiDataModel * mpDataModel
Definition: SEDMLImporter.h:55
std::map< CCopasiObject *, SBase * > & getCopasi2SBMLMap()
virtual bool setMethodType(const int &type)
std::vector< CRegisteredObjectName > * getHeaderAddr()
#define SEDML_KISAO_STOCHASTIC
Definition: SEDMLUtils.h:22
void importTasks(std::map< CCopasiObject *, SedBase * > &copasi2sedmlmap)
void restoreFunctionDB()
CCopasiContainer * getObjectParent() const
bool applyAttributeChange(CModel *pCopasiModel, CModelParameterSet &set, const std::string &target, const std::string &newValue)