示例#1
0
void CMoietiesProblem::printResult(std::ostream * pOstream) const
{
  const CModel & Model = mpContainer->getModel();

  // Print all Moieties
  *pOstream << "Dependent Species" << "\t";
  *pOstream << "Total Amount" << "\t";
  *pOstream << "Expression" << std::endl;

  CCopasiVector< CMoiety >::const_iterator it = Model.getMoieties().begin();
  CCopasiVector< CMoiety >::const_iterator end = Model.getMoieties().end();

  for (; it != end; ++it)
    {
      *pOstream << it->getObjectName() << "\t";
      *pOstream << it->getNumber() << "\t";
      *pOstream << it->getDescription(&Model) << std::endl;
    }

  *pOstream << std::endl;

  // Print Reordered Stoichiometry Matrix
  *pOstream << *dynamic_cast<const CArrayAnnotation *>(Model.getObject(CCopasiObjectName("Array=Stoichiometry(ann)"))) << std::endl;

  // Print Link Matrix
  *pOstream << *dynamic_cast<const CArrayAnnotation *>(Model.getObject(CCopasiObjectName("Array=Link matrix(ann)"))) << std::endl;

  // Print Reduced Stoichiometry Matrix
  *pOstream << *dynamic_cast<const CArrayAnnotation *>(Model.getObject(CCopasiObjectName("Array=Reduced stoichiometry(ann)"))) << std::endl;

  return;
}
示例#2
0
//static
void CSensProblem::createParametersInGroup(CCopasiParameterGroup *pg)
{
  if (!pg) return;

  pg->addParameter("SingleObject", CCopasiParameter::CN, CCopasiObjectName(""));
  pg->addParameter("ObjectListType", CCopasiParameter::UINT, (unsigned C_INT32) 0);
}
示例#3
0
// virtual
CCopasiObjectName CMathObject::getCN() const
{
  if (mpDataObject == NULL)
    return CCopasiObjectName("");

  return mpDataObject->getCN();
}
示例#4
0
void CFitProblem::initializeParameter()
{
  removeParameter("Subtask");
  mpParmSubtaskCN = NULL;
  removeParameter("ObjectiveExpression");
  mpParmObjectiveExpression = NULL;
  *mpParmMaximize = false;

  mpParmSteadyStateCN =
    assertParameter("Steady-State", CCopasiParameter::CN, CCopasiObjectName(""))->getValue().pCN;
  mpParmTimeCourseCN =
    assertParameter("Time-Course", CCopasiParameter::CN, CCopasiObjectName(""))->getValue().pCN;

  assertGroup("Experiment Set");


  elevateChildren();
}
示例#5
0
bool HistoWidget::SaveToCurveSpec(CPlotItem * curve, const CPlotItem *original /*= NULL*/) const
{

  C_INT32 Activity = 0;

  if (mpCheckBefore->isChecked()) Activity += COutputInterface::BEFORE;

  if (mpCheckDuring->isChecked()) Activity += COutputInterface::DURING;

  if (mpCheckAfter->isChecked()) Activity += COutputInterface::AFTER;

  std::string title = TO_UTF8(mpEditTitle->text());
  CCopasiObjectName name = mpObjectX ? mpObjectX->getCN() : CCopasiObjectName("");
  C_FLOAT64 increment = mpEditIncrement->text().toDouble();

  bool thingsChanged = false;

  if (original != NULL)
    {
      if (original->getType() != CPlotItem::histoItem1d)
        thingsChanged = true;

      if (thingsChanged || original->getTitle() != title)
        thingsChanged = true;

      if (thingsChanged || original->getValue< C_FLOAT64 >("increment") != increment)
        thingsChanged = true;

      if (thingsChanged || original->getActivity() != Activity)
        thingsChanged = true;

      if (thingsChanged || original->getChannels().size() != 1)
        thingsChanged = true;

      if (thingsChanged || original->getChannels()[0] != name)
        thingsChanged = true;
    }
  else thingsChanged = true;

  if (!thingsChanged)
    return false;

  //title
  curve->setTitle(title);

  //channels
  curve->getChannels().clear();
  curve->getChannels().push_back(CPlotDataChannelSpec(name));

  //other parameters: TODO
  curve->setValue("increment", increment);

  curve->setActivity((COutputInterface::Activity) Activity);

  return true;
}
示例#6
0
void CQMathMatrixWidget::loadMatrices()
{

  assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
  const CModel* pModel = CCopasiRootContainer::getDatamodelList()->operator[](0).getModel();

  const CArrayAnnotation * tmp;

  tmp = dynamic_cast<const CArrayAnnotation *>
        (pModel->getObject(CCopasiObjectName("Array=Stoichiometry(ann)")));
  mpArrayWidget1->setArrayAnnotation(tmp);

  tmp = dynamic_cast<const CArrayAnnotation *>
        (pModel->getObject(CCopasiObjectName("Array=Reduced stoichiometry(ann)")));
  mpArrayWidget2->setArrayAnnotation(tmp);

  tmp = dynamic_cast<const CArrayAnnotation *>
        (pModel->getObject(CCopasiObjectName("Array=Link matrix(ann)")));
  mpArrayWidget3->setArrayAnnotation(tmp);
}
示例#7
0
const CCopasiObject*
SEDMLUtils::resolveDatagenerator(const CModel *model, const SedDataGenerator* dataReference)
{
  // for now one variable only
  if (dataReference == NULL || dataReference->getNumVariables() < 1) return NULL;

  const SedVariable* var = dataReference->getVariable(0);

  if (var->isSetSymbol() && var->getSymbol() == SEDML_TIME_URN)
    {
      return static_cast<const CCopasiObject *>(model->getObject(CCopasiObjectName("Reference=Time")));
    }

  return resolveXPath(model, var->getTarget());
}
示例#8
0
void CArrayAnnotation::autoAnnotation(const size_t & d)
{
  resizeOneDimension(d);

  size_t i;

  for (i = 0; i < mAnnotationsCN[d].size(); ++i)
    {
      std::stringstream I;
      I << i;

      mAnnotationsCN[d][i] = CCopasiObjectName("String=" + I.str());
      mAnnotationsString[d][i] = createDisplayName(mAnnotationsCN[d][i]);
    }
}
CEvaluationNode* CEvaluationNodeObject::createNodeFromASTTree(const ASTNode& node)
{
  CEvaluationNodeObject* pNode = NULL;
  ASTNodeType_t type = node.getType();

  switch (type)
    {
      case AST_NAME_TIME:
      case AST_NAME:
        pNode = new CEvaluationNodeObject(CN, CCopasiObjectName(std::string("<") + node.getName() + std::string(">")));
        break;
      default:
        break;
    }

  return pNode;
}
示例#10
0
void CAnalyticsProblem::initializeParameter()
{
  mpFlagLimitCrossings = assertParameter("LimitCrossings", CCopasiParameter::BOOL, false);
  mpCrossingsLimit = assertParameter("NumCrossingsLimit", CCopasiParameter::UINT, (unsigned C_INT32)0);
  mpFlagLimitOutTime = assertParameter("LimitOutTime", CCopasiParameter::BOOL, false);
  mpFlagLimitOutCrossings = assertParameter("LimitOutCrossings", CCopasiParameter::BOOL, false);
  mpFlagPositiveDirection = assertParameter("PositiveDirection", CCopasiParameter::BOOL, true);
  mpOutCrossingsLimit = assertParameter("NumOutCrossingsLimit", CCopasiParameter::UINT, (unsigned C_INT32)0);
  mpFlagLimitConvergence = assertParameter("LimitUntilConvergence", CCopasiParameter::BOOL, false);
  mpConvergenceTolerance = assertParameter("ConvergenceTolerance", CCopasiParameter::DOUBLE, (C_FLOAT64)1E-6);
  mpThreshold = assertParameter("Threshold", CCopasiParameter::DOUBLE, (C_FLOAT64)0);
  mpFlagLimitOutConvergence = assertParameter("DelayOutputUntilConvergence", CCopasiParameter::BOOL, false);
  mpConvergenceOutTolerance = assertParameter("OutputConvergenceTolerance", CCopasiParameter::DOUBLE, (C_FLOAT64)1E-6);
  mpTriggerExpression = assertParameter("TriggerExpression", CCopasiParameter::EXPRESSION, std::string(""));
  mpSingleObjectCN = assertParameter("SingleVariable", CCopasiParameter::CN, CCopasiObjectName(""));
  setOutputEvent(false);
}
示例#11
0
void CQExperimentData::slotTypeChanged(int row, int index)
{
  CExperiment::Type NewType = static_cast<CExperiment::Type>(index);
  CExperiment::Type OldType = static_cast<CExperiment::Type>(mpTable->item(row, COL_TYPE_HIDDEN)->data(Qt::DisplayRole).asInt());

  if (OldType == NewType) return;

  bool BtnEnabled = true;
  C_INT32 i, imax = mpTable->rowCount();

  CCopasiObjectName CN = CCopasiObjectName(TO_UTF8(mpTable->item(row, COL_OBJECT_HIDDEN)->text()));
  assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
  CCopasiDataModel* pDataModel = (*CCopasiRootContainer::getDatamodelList())[0];
  assert(pDataModel != NULL);

  switch (NewType)
    {
      case CExperiment::ignore:
        BtnEnabled = false;
        break;

      case CExperiment::independent:

        if (!CQSimpleSelectionTree::filter(CQSimpleSelectionTree::InitialTime |
                                           CQSimpleSelectionTree::Parameters,
                                           pDataModel->getDataObject(CN)))
          {
            mModelObjectRow = row;
            QTimer::singleShot(10, this, SLOT(slotModelObjectDelayed()));
          }

        BtnEnabled = true;
        break;

      case CExperiment::dependent:

        if (!CQSimpleSelectionTree::filter(CQSimpleSelectionTree::Variables |
                                           CQSimpleSelectionTree::ObservedValues,
                                           pDataModel->getDataObject(CN)))
          {
            mModelObjectRow = row;
            QTimer::singleShot(10, this, SLOT(slotModelObjectDelayed()));
          }

        BtnEnabled = true;
        break;

      case CExperiment::time:
        BtnEnabled = false;
        setTypeItems(row);

        break;
    }

  QTableWidgetItem * pItem = mpTable->item(row, COL_BTN);

  if (BtnEnabled)
    {
      pItem->setFlags(pItem->flags() | Qt::ItemIsEditable | Qt::ItemIsEnabled);
      mpTable->openPersistentEditor(pItem);
    }
  else
    {
      pItem->setFlags(pItem->flags() & ~Qt::ItemIsEditable & ~Qt::ItemIsEnabled);
      mpTable->closePersistentEditor(pItem);
    }

  switch (OldType)
    {
      case CExperiment::ignore:
      case CExperiment::independent:
      case CExperiment::dependent:
        break;

      case CExperiment::time:
        setTypeItems(-1);
        break;
    }

  mpTable->item(row, COL_TYPE)->setText(FROM_UTF8(CExperiment::TypeName[NewType]));
  mpTable->item(row, COL_TYPE_HIDDEN)->setText(QString::number(NewType));

  // The default weights need to be recalculated and the table updated if the type change
  // involves dependent values.
  if (OldType == CExperiment::dependent ||
      NewType == CExperiment::dependent)
    {
      saveExperiment(mpExperiment, true);

      // Since the interpretation of the data has changed we need read the file again
      std::ifstream File;
      File.open(CLocaleString::fromUtf8(mpExperiment->getFileName()).c_str());

      size_t CurrentLine = 1;
      mpExperiment->read(File, CurrentLine);
      mpExperiment->compile();

      // We can not simply use loadTable as this would destroy the two signal maps
      // for the buttons and comboboxes leading to crashes in Qt.
      CExperimentObjectMap & ObjectMap = mpExperiment->getObjectMap();

      for (i = 0; i < imax; i++)
        {
          QTableWidgetItem * pItem = mpTable->item(i, COL_SCALE);

          // COL_SCALE
          if (ObjectMap.getRole(i) != CExperiment::dependent)
            {
              pItem->setText("");
              pItem->setFlags(pItem->flags() & ~Qt::ItemIsEditable);
            }
          else
            {
              QString ScaleText = pItem->text();

              // Keep non default values
              if (ScaleText == "" || ScaleText[0] == '(')
                {

                  C_FLOAT64 DefaultWeight = ObjectMap.getDefaultScale(i);

                  ScaleText = "(" + QString::number(DefaultWeight) + ")";
                  pItem->setText(ScaleText);
                }

              pItem->setFlags(pItem->flags() | Qt::ItemIsEditable);
            }
        }
    }

  return;
}
示例#12
0
bool
CQSpectogramWidget::SaveToCurveSpec(CPlotItem * curve, const CPlotItem *original /*= NULL*/) const
{
  curve->setType(CPlotItem::spectogram);

  std::string title = TO_UTF8(mpEditTitle->text());

  CCopasiObjectName xName = mpObjectX ? mpObjectX->getCN() : CCopasiObjectName("");
  CCopasiObjectName yName = mpObjectY ? mpObjectY->getCN() : CCopasiObjectName("");
  CCopasiObjectName zName = mpObjectZ ? mpObjectZ->getCN() : CCopasiObjectName("");

  C_INT32 Activity = 0;

  if (mpCheckBefore->isChecked()) Activity += COutputInterface::BEFORE;

  if (mpCheckDuring->isChecked()) Activity += COutputInterface::DURING;

  if (mpCheckAfter->isChecked()) Activity += COutputInterface::AFTER;

  bool thingsChanged = false;

  if (original != NULL)
    {
      // compare whether things changed
      if (original->getTitle() != title)
        thingsChanged = true;

      if (thingsChanged || original->getType() != CPlotItem::spectogram)
        thingsChanged = true;

      if (thingsChanged || original->getActivity() != Activity)
        thingsChanged = true;

      if (thingsChanged || original->getChannels().size() != 3)
        thingsChanged = true;

      if (thingsChanged || original->getChannels()[0] != xName)
        thingsChanged = true;

      if (thingsChanged || original->getChannels()[1] != yName)
        thingsChanged = true;

      if (thingsChanged || original->getChannels()[2] != zName)
        thingsChanged = true;

      if (thingsChanged || *curve->assertParameter("contours", CCopasiParameter::STRING, std::string("")) != TO_UTF8(mpContours->text()))
        thingsChanged = true;

      if (thingsChanged || *curve->assertParameter("maxZ", CCopasiParameter::STRING, std::string("")) != TO_UTF8(mpMaxZ->text()))
        thingsChanged = true;

      if (thingsChanged || *curve->assertParameter("colorMap", CCopasiParameter::STRING, std::string("")) != TO_UTF8(mpColorMap->currentText()))
        thingsChanged = true;

      if (thingsChanged || *curve->assertParameter("logZ", CCopasiParameter::BOOL, false) != mpLogZ->isChecked())
        thingsChanged = true;

      if (thingsChanged || *curve->assertParameter("bilinear", CCopasiParameter::BOOL, true) != mpBilinear->isChecked())
        thingsChanged = true;
    }
  else thingsChanged = true;

  if (!thingsChanged)
    return false;

  //title
  curve->setTitle(title);

  //channels
  curve->getChannels().clear();
  curve->getChannels().push_back(CPlotDataChannelSpec(xName));
  curve->getChannels().push_back(CPlotDataChannelSpec(yName));
  curve->getChannels().push_back(CPlotDataChannelSpec(zName));

  curve->setActivity((COutputInterface::Activity) Activity);

  bool* pLogZ = curve->assertParameter("logZ", CCopasiParameter::BOOL, false);
  bool* pBilinear = curve->assertParameter("bilinear", CCopasiParameter::BOOL, true);
  std::string* pContours = curve->assertParameter("contours", CCopasiParameter::STRING, std::string(""));
  std::string* pMaxZ = curve->assertParameter("maxZ", CCopasiParameter::STRING, std::string(""));
  std::string* pColorMap = curve->assertParameter("colorMap", CCopasiParameter::STRING, std::string("Default"));

  *pLogZ = mpLogZ->isChecked();
  *pBilinear = mpBilinear->isChecked();

  *pContours = TO_UTF8(mpContours->text());
  *pMaxZ = TO_UTF8(mpMaxZ->text());
  *pColorMap = TO_UTF8(mpColorMap->currentText());

  return true;
}
示例#13
0
int main(int argc, char** argv)
{
  // initialize the backend library
  CCopasiRootContainer::init(argc, argv);
  assert(CCopasiRootContainer::getRoot() != NULL);
  // create a new datamodel
  CCopasiDataModel* pDataModel = CCopasiRootContainer::addDatamodel();
  assert(CCopasiRootContainer::getDatamodelList()->size() == 1);

  // the only argument to the main routine should be the name of an SBML file
  if (argc == 2)
    {
      std::string filename = argv[1];

      try
        {
          // load the model without progress report
          pDataModel->importSBML(filename, NULL);
        }
      catch (...)
        {
          std::cerr << "Error while importing the model from file named \"" << filename << "\"." << std::endl;
          CCopasiRootContainer::destroy();
          return 1;
        }

      CModel* pModel = pDataModel->getModel();
      assert(pModel != NULL);
      // create a report with the correct filename and all the species against
      // time.
      CReportDefinitionVector* pReports = pDataModel->getReportDefinitionList();
      // create a new report definition object
      CReportDefinition* pReport = pReports->createReportDefinition("Report", "Output for timecourse");
      // set the task type for the report definition to timecourse
      pReport->setTaskType(CTaskEnum::timeCourse);
      // we don't want a table
      pReport->setIsTable(false);
      // the entries in the output should be seperated by a ", "
      pReport->setSeparator(", ");

      // 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
      std::vector<CRegisteredObjectName>* pHeader = pReport->getHeaderAddr();
      std::vector<CRegisteredObjectName>* pBody = pReport->getBodyAddr();
      pBody->push_back(CCopasiObjectName(pDataModel->getModel()->getCN() + ",Reference=Time"));
      pBody->push_back(CRegisteredObjectName(pReport->getSeparator().getCN()));
      pHeader->push_back(CCopasiStaticString("time").getCN());
      pHeader->push_back(pReport->getSeparator().getCN());

      size_t i, iMax = pModel->getMetabolites().size();

      for (i = 0; i < iMax; ++i)
        {
          CMetab* pMetab = &pModel->getMetabolites()[i];
          assert(pMetab != NULL);

          // we don't want output for FIXED metabolites right now
          if (pMetab->getStatus() != CModelEntity::FIXED)
            {
              // we want the concentration oin the output
              // alternatively, we could use "Reference=Amount" to get the
              // particle number
              pBody->push_back(pMetab->getObject(CCopasiObjectName("Reference=Concentration"))->getCN());
              // after each entry, we need a seperator
              pBody->push_back(pReport->getSeparator().getCN());

              // add the corresponding id to the header
              pHeader->push_back(CCopasiStaticString(pMetab->getSBMLId()).getCN());
              // and a seperator
              pHeader->push_back(pReport->getSeparator().getCN());
            }
        }

      if (iMax > 0)
        {
          // delete the last separator
          // since we don't need one after the last element on each line
          if ((*pBody->rbegin()) == pReport->getSeparator().getCN())
            {
              pBody->erase(--pBody->end());
            }

          if ((*pHeader->rbegin()) == pReport->getSeparator().getCN())
            {
              pHeader->erase(--pHeader->end());
            }
        }

      // get the task list
      CCopasiVectorN< CCopasiTask > & TaskList = * pDataModel->getTaskList();

      // get the trajectory task object
      CTrajectoryTask* pTrajectoryTask = dynamic_cast<CTrajectoryTask*>(&TaskList["Time-Course"]);

      // if there isn't one
      if (pTrajectoryTask == NULL)
        {
          // remove any existing trajectory task just to be sure since in
          // theory only the cast might have failed above
          TaskList.remove("Time-Course");

          // create a new one
          pTrajectoryTask = new CTrajectoryTask(& TaskList);

          // add the new time course task to the task list
          TaskList.add(pTrajectoryTask, true);
        }

      // run a deterministic time course
      pTrajectoryTask->setMethodType(CTaskEnum::deterministic);

      // Activate the task so that it will be run when the model is saved
      // and passed to CopasiSE
      pTrajectoryTask->setScheduled(true);

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

      // get the problem for the task to set some parameters
      CTrajectoryProblem* pProblem = dynamic_cast<CTrajectoryProblem*>(pTrajectoryTask->getProblem());

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

      // set some parameters for the LSODA method through the method
      CTrajectoryMethod* pMethod = dynamic_cast<CTrajectoryMethod*>(pTrajectoryTask->getMethod());

      CCopasiParameter* pParameter = pMethod->getParameter("Absolute Tolerance");
      assert(pParameter != NULL);
      pParameter->setValue(1.0e-12);

      try
        {
          // initialize the trajectory task
          // we want complete output (HEADER, BODY and FOOTER)
          //
          // The output has to be set to OUTPUT_UI, otherwise the time series will not be
          // kept in memory and some of the assert further down will fail
          // If it is OK that the output is only written to file, the output type can
          // be set to OUTPUT_SE
          pTrajectoryTask->initialize(CCopasiTask::OUTPUT_UI, pDataModel, NULL);
          // now we run the actual trajectory
          pTrajectoryTask->process(true);
        }
      catch (...)
        {
          std::cerr << "Error. Running the time course simulation failed." << std::endl;

          // check if there are additional error messages
          if (CCopasiMessage::size() > 0)
            {
              // print the messages in chronological order
              std::cerr << CCopasiMessage::getAllMessageText(true);
            }

          CCopasiRootContainer::destroy();
          return 1;
        }

      // restore the state of the trajectory
      pTrajectoryTask->restore();

      // look at the timeseries
      const CTimeSeries* pTimeSeries = &pTrajectoryTask->getTimeSeries();
      // we simulated 100 steps, including the initial state, this should be
      // 101 step in the timeseries
      assert(pTimeSeries->getRecordedSteps() == 101);
      std::cout << "The time series consists of " << pTimeSeries->getRecordedSteps() << "." << std::endl;
      std::cout << "Each step contains " << pTimeSeries->getNumVariables() << " variables." << std::endl;
      std::cout << "The final state is: " << std::endl;
      iMax = pTimeSeries->getNumVariables();
      size_t lastIndex = pTimeSeries->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
          std::cout << pTimeSeries->getTitle(i) << ": " << pTimeSeries->getData(lastIndex, i) << std::endl;
        }
    }
  else
    {
      std::cerr << "Usage: example3 SBMLFILE" << std::endl;
      CCopasiRootContainer::destroy();
      return 1;
    }

  // clean up the library
  CCopasiRootContainer::destroy();
}
示例#14
0
int main(int argc, char *argv[])
{
  // Parse the commandline options
  // first argument is the SBML filename
  // second argument is the endtime
  // third argument is the step number
  // fourth argument is the filename where the results are to be written
  // fifth argument is the tmp directory (this is not needed)
  // the rest of the arguments are species names for the result
  try
    {
      // Create the root container.
      CCopasiRootContainer::init(0, NULL, false);
    }

  catch (copasi::autoexcept &e)
    {}

  catch (copasi::option_error &e)
    {}

  if (argc < 5)
    {
      std::cout << "Usage: semantic-test-suite SBMLFILENAME ENDTIME STEPNUMBER OUTFILENAME TMPDIR SPECIESID1 SPECIESID2 ..." << std::endl;
      exit(1);
    }

  char* pSBMLFilename = argv[1];
  const char* pEndTime = argv[2];
  const char* pStepNumber = argv[3];
  char* pOutputFilename = argv[4];
  //char* pTmpDirectory=argv[5];
  char** pSBMLSpeciesIds = new char * [argc - 6];
  unsigned int i, iMax = argc;
  CTrajectoryTask* pTrajectoryTask = NULL;

  std::string CWD = COptions::getPWD();
  double endTime = strToDouble(pEndTime, &pEndTime);
  double stepNumber = strToDouble(pStepNumber, &pStepNumber);

  if (endTime == 0.0)
    {
      std::cerr << "Invalid endtime " << pEndTime << std::endl;
      exit(1);
    }

  if (stepNumber == 0.0)
    {
      std::cerr << "Invalid step number " << pStepNumber << std::endl;
      exit(1);
    }

  for (i = 6; i < iMax; ++i)
    {
      pSBMLSpeciesIds[i - 6] = argv[i];
      //std::cout << "Copying pointer to " <<  argv[i]  << "." << std::endl;
    }

  try
    {
      // Create the global data model.
      CCopasiDataModel* pDataModel = CCopasiRootContainer::addDatamodel();

      // Import the SBML File
      pDataModel->importSBML(pSBMLFilename);

      //pDataModel->getModel()->forceCompile();

      // create a report with the correct filename and all the species against
      // time.
      CReportDefinitionVector* pReports = pDataModel->getReportDefinitionList();
      CReportDefinition* pReport = pReports->createReportDefinition("Report", "Output for SBML testsuite run");
      pReport->setTaskType(CCopasiTask::timeCourse);
      pReport->setIsTable(true);

      std::vector<CRegisteredObjectName>* pTable = pReport->getTableAddr();
      pTable->push_back(CCopasiObjectName(pDataModel->getModel()->getCN() + ",Reference=Time"));
      iMax = iMax - 6;
      const CCopasiVector<CMetab>& metabolites = pDataModel->getModel()->getMetabolites();

      for (i = 0; i < iMax; ++i)
        {
          unsigned int j, jMax = metabolites.size();

          for (j = 0; j < jMax; ++j)
            {
              if (metabolites[j]->getSBMLId() == pSBMLSpeciesIds[i])
                {
                  pTable->push_back(metabolites[j]->getObject(CCopasiObjectName("Reference=Concentration"))->getCN());
                  //std::cout << "adding metabolite " << metabolites[j]->getObjectName() << " to report." << std::endl;
                  break;
                }
            }

          if (j == jMax)
            {
              std::cerr << "Could not find a metabolite for the SBML id " << pSBMLSpeciesIds[i] << std::endl;
              exit(1);
            }
        }

      // create a trajectory task
      pTrajectoryTask = new CTrajectoryTask();
      pTrajectoryTask->getProblem()->setModel(pDataModel->getModel());

      pTrajectoryTask->setScheduled(true);

      pTrajectoryTask->getReport().setReportDefinition(pReport);
      pTrajectoryTask->getReport().setTarget(CWD + "/" + pOutputFilename);
      pTrajectoryTask->getReport().setAppend(false);

      CTrajectoryProblem* pProblem = dynamic_cast<CTrajectoryProblem*>(pTrajectoryTask->getProblem());

      pProblem->setStepNumber((const unsigned C_INT32)stepNumber);
      pProblem->setDuration((const C_FLOAT64)endTime);
      pProblem->setTimeSeriesRequested(true);
      //pProblem->setInitialState(pDataModel->getModel()->getInitialState());

      CTrajectoryMethod* pMethod = dynamic_cast<CTrajectoryMethod*>(pTrajectoryTask->getMethod());

      pMethod->getParameter("Absolute Tolerance")->setValue(1.0e-20);

      CCopasiVectorN< CCopasiTask > & TaskList = * pDataModel->getTaskList();

      TaskList.remove("Time-Course");
      TaskList.add(pTrajectoryTask, true);

      // save the file for control purposes
      std::string saveFilename = pSBMLFilename;
      saveFilename = saveFilename.substr(0, saveFilename.length() - 4) + ".cps";
      pDataModel->saveModel(saveFilename, NULL, true);

      // Run the trajectory task

      pTrajectoryTask->initialize(CCopasiTask::OUTPUT_UI, pDataModel, NULL);
      pTrajectoryTask->process(true);
      pTrajectoryTask->restore();

      // create another report that will write to the directory where the input file came from
      // this can be used for debugging
      // create a trajectory task
      pTrajectoryTask->getReport().setTarget(pOutputFilename);

      pTrajectoryTask->initialize(CCopasiTask::OUTPUT_UI, pDataModel, NULL);
      pTrajectoryTask->process(true);
      pTrajectoryTask->restore();
    }
  catch (CCopasiException Exception)
    {
      std::cerr << Exception.getMessage().getText() << std::endl;
    }

  CCopasiRootContainer::destroy();

  return 0;
}
示例#15
0
const CCopasiObject *
SEDMLUtils::getObjectForSbmlId(const CModel* pModel, const std::string& id, const std::string& SBMLType, bool initial/* = false*/)
{
  if (SBMLType == "Time")
    return static_cast<const CCopasiObject *>(pModel->getObject(CCopasiObjectName("Reference=Time")));

  if (SBMLType == "species")
    {
      size_t iMet, imax = pModel->getMetabolites().size();

      for (iMet = 0; iMet < imax; ++iMet)
        {
          // the importer should not need to change the initial concentration
          // pModel->getMetabolites()[iMet]->setInitialConcentration(0.896901);

          if (pModel->getMetabolites()[iMet]->getSBMLId() == id)
            {
              if (initial)
                return pModel->getMetabolites()[iMet]->getInitialConcentrationReference();

              return pModel->getMetabolites()[iMet]->getConcentrationReference();
            }
        }
    }
  else if (SBMLType == "reaction")
    {
      size_t iMet, imax = pModel->getReactions().size();

      for (iMet = 0; iMet < imax; ++iMet)
        {
          if (pModel->getReactions()[iMet]->getSBMLId() == id)
            {
              if (initial)
                return NULL;

              return pModel->getReactions()[iMet]->getFluxReference();
            }
        }
    }
  else if (SBMLType == "parameter")
    {
      size_t iMet, imax = pModel->getModelValues().size();

      for (iMet = 0; iMet < imax; ++iMet)
        {
          if (pModel->getModelValues()[iMet]->getSBMLId() == id)
            {
              if (initial)
                return pModel->getModelValues()[iMet]->getInitialValueReference();

              return pModel->getModelValues()[iMet]->getValueReference();
            }
        }
    }

  else if (SBMLType == "compartment")
    {
      size_t iComp, imax = pModel->getCompartments().size();

      for (iComp = 0; iComp < imax; ++iComp)
        {
          if (pModel->getCompartments()[iComp]->getSBMLId() == id)
            {
              if (initial)
                return pModel->getCompartments()[iComp]->getInitialValueReference();

              return pModel->getCompartments()[iComp]->getValueReference();
            }
        }
    }

  return NULL;
}
示例#16
0
bool CFitProblem::elevateChildren()
{
  // This call is necessary since CFitProblem is derived from COptProblem.
  if (!COptProblem::elevateChildren()) return false;

  // Due to a naming conflict the following parameters may have been overwritten during
  // the load of a CopasiML file we replace them with default values if that was the case.
  mpParmSteadyStateCN =
    assertParameter("Steady-State", CCopasiParameter::CN, CCopasiObjectName(""))->getValue().pCN;
  mpParmTimeCourseCN =
    assertParameter("Time-Course", CCopasiParameter::CN, CCopasiObjectName(""))->getValue().pCN;

  CCopasiVectorN< CCopasiTask > * pTasks = NULL;
  CCopasiDataModel* pDataModel = getObjectDataModel();

  if (pDataModel)
    pTasks = pDataModel->getTaskList();

  if (pTasks == NULL)
    pTasks = dynamic_cast<CCopasiVectorN< CCopasiTask > *>(getObjectAncestor("Vector"));

  if (pTasks)
    {
      unsigned C_INT32 i, imax = pTasks->size();

      if (!mpParmSteadyStateCN->compare(0, 5 , "Task_") ||
          *mpParmSteadyStateCN == "")
        for (i = 0; i < imax; i++)
          if ((*pTasks)[i]->getType() == CCopasiTask::steadyState)
            {
              *mpParmSteadyStateCN = (*pTasks)[i]->getCN();
              break;
            }

      if (!mpParmTimeCourseCN->compare(0, 5 , "Task_") ||
          *mpParmTimeCourseCN == "")
        for (i = 0; i < imax; i++)
          if ((*pTasks)[i]->getType() == CCopasiTask::timeCourse)
            {
              *mpParmTimeCourseCN = (*pTasks)[i]->getCN();
              break;
            }
    }

  std::map<std::string, std::string> ExperimentMap;
  CCopasiParameterGroup * pGroup;
  CExperiment * pExperiment;

  std::vector<CCopasiParameter *> * pExperiments =
    getGroup("Experiment Set")->CCopasiParameter::getValue().pGROUP;
  std::vector<CCopasiParameter *>::iterator itExp;
  std::vector<CCopasiParameter *>::iterator endExp;

  for (itExp = pExperiments->begin(), endExp = pExperiments->end(); itExp != endExp; ++itExp)
    if ((pGroup = dynamic_cast< CCopasiParameterGroup * >(*itExp)) != NULL &&
        pGroup->getParameter("Key") != NULL)
      ExperimentMap[*pGroup->getValue("Key").pKEY] = (*itExp)->getObjectName();

  mpExperimentSet =
    elevate<CExperimentSet, CCopasiParameterGroup>(getGroup("Experiment Set"));

  if (!mpExperimentSet) return false;

  std::map<std::string, std::string>::iterator itMap;
  std::map<std::string, std::string>::iterator endMap;

  for (itMap = ExperimentMap.begin(), endMap = ExperimentMap.end(); itMap != endMap; ++itMap)
    {
      pExperiment = mpExperimentSet->getExperiment(itMap->second);
      itMap->second = pExperiment->CCopasiParameter::getKey();
      pExperiment->setValue("Key", itMap->second);
    }


  std::vector<COptItem * >::iterator it = mpOptItems->begin();
  std::vector<COptItem * >::iterator end = mpOptItems->end();

  for (; it != end; ++it)
    {
      if (!((*it) = elevate<CFitItem, COptItem>(*it)))
        return false;

      pExperiments =
        (*it)->getParameter("Affected Experiments")->getValue().pGROUP;

      for (itExp = pExperiments->begin(), endExp = pExperiments->end(); itExp != endExp; ++itExp)
        (*itExp)->setValue(ExperimentMap[*(*itExp)->getValue().pKEY]);

    }

  it = mpConstraintItems->begin();
  end = mpConstraintItems->end();

  for (; it != end; ++it)
    {
      if (!((*it) = elevate<CFitConstraint, COptItem>(*it)))
        return false;

      pExperiments =
        (*it)->getParameter("Affected Experiments")->getValue().pGROUP;

      for (itExp = pExperiments->begin(), endExp = pExperiments->end(); itExp != endExp; ++itExp)
        (*itExp)->setValue(ExperimentMap[*(*itExp)->getValue().pKEY]);

    }

  return true;
}
示例#17
0
void DataModelGUI::buildChangedObjects()
{
  assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
  CModel * pModel = (*CCopasiRootContainer::getDatamodelList())[0]->getModel();
  pModel->compileIfNecessary(NULL);

  mChangedObjects.clear();

  CModelEntity ** ppEntity = pModel->getStateTemplate().getEntities();
  CModelEntity ** ppEntityEnd = pModel->getStateTemplate().endFixed();

  CMetab * pMetab;
  std::set< const CCopasiObject * > Objects;

  // The objects which are changed are all initial values of of all model entities including
  // fixed and unused once. Additionally, all kinetic parameters are possibly changed.
  // This is basically all the parameters in the parameter overview whose value is editable.

  // :TODO: Theoretically, it is possible that also task parameters influence the initial
  // state of a model but that is currently not handled.

  for (; ppEntity != ppEntityEnd; ++ppEntity)
    {
      // If we have an initial expression we have no initial values
      if ((*ppEntity)->getInitialExpression() != "" ||
          (*ppEntity)->getStatus() == CModelEntity::ASSIGNMENT)
        continue;

      // Metabolites have two initial values
      if (mFramework == 0 &&
          (pMetab = dynamic_cast< CMetab * >(*ppEntity)) != NULL)
        {
          // The concentration is assumed to be fix accept when this would lead to circular dependencies,
          // for the parent's compartment's initial volume.
          if (pMetab->isInitialConcentrationChangeAllowed() &&
              !isnan(pMetab->getInitialConcentration()))
            mChangedObjects.insert(pMetab->getInitialConcentrationReference());
          else
            mChangedObjects.insert(pMetab->getInitialValueReference());
        }
      else
        mChangedObjects.insert((*ppEntity)->getInitialValueReference());
    }

  // The reaction parameters
  CCopasiVector< CReaction >::const_iterator itReaction = pModel->getReactions().begin();
  CCopasiVector< CReaction >::const_iterator endReaction = pModel->getReactions().end();
  size_t i, imax;

  for (; itReaction != endReaction; ++itReaction)
    {
      const CCopasiParameterGroup & Group = (*itReaction)->getParameters();

      for (i = 0, imax = Group.size(); i < imax; i++)
        mChangedObjects.insert(static_cast< const CCopasiObject * >(Group.getParameter(i)->getObject(CCopasiObjectName("Reference=Value"))));
    }

  // Fix for Issue 1170: We need to add elements of the stoichiometry, reduced stoichiometry,
  // and link matrices.
  const CArrayAnnotation * pMatrix = NULL;
  pMatrix = dynamic_cast<const CArrayAnnotation *>(pModel->getObject(std::string("Array=Stoichiometry(ann)")));

  if (pMatrix != NULL)
    pMatrix->appendElementReferences(mChangedObjects);

  pMatrix = dynamic_cast<const CArrayAnnotation *>(pModel->getObject(std::string("Array=Reduced stoichiometry(ann)")));

  if (pMatrix != NULL)
    pMatrix->appendElementReferences(mChangedObjects);

  pMatrix = dynamic_cast<const CArrayAnnotation *>(pModel->getObject(std::string("Array=Link matrix(ann)")));

  if (pMatrix != NULL)
    pMatrix->appendElementReferences(mChangedObjects);

  try
    {
      mUpdateVector = pModel->buildInitialRefreshSequence(mChangedObjects);
    }

  catch (...)
    {
      QString Message = "Error while updating the initial values!\n\n";
      Message += FROM_UTF8(CCopasiMessage::getLastMessage().getText());

      CQMessageBox::critical(NULL, QString("COPASI Error"), Message,
                             QMessageBox::Ok, QMessageBox::Ok);
      CCopasiMessage::clearDeque();

      mUpdateVector.clear();
      return;
    }
}
示例#18
0
void test000087::test_simulate_reaction_flux_reference_1()
{
  try
    {
      bool result = pCOPASIDATAMODEL->importSBMLFromString(test000087::MODEL_STRING5);
      CPPUNIT_ASSERT(result = true);
    }
  catch (...)
    {
      // there should be no exception
      CPPUNIT_ASSERT(false);
    }

  CModel* pModel = pCOPASIDATAMODEL->getModel();
  CPPUNIT_ASSERT(pModel != NULL);
  CPPUNIT_ASSERT(pModel->getCompartments().size() == 1);
  CPPUNIT_ASSERT(pModel->getMetabolites().size() == 2);
  CPPUNIT_ASSERT(pModel->getModelValues().size() == 2);
  CPPUNIT_ASSERT(pModel->getReactions().size() == 1);
  const CReaction* pReaction = pModel->getReactions()[0];
  CPPUNIT_ASSERT(pReaction != NULL);
  CModelValue* pConstParameter = NULL;
  CModelValue* pNonConstParameter = NULL;
  unsigned int i, iMax = pModel->getModelValues().size();

  for (i = 0; i < iMax; ++i)
    {
      if (pModel->getModelValues()[i]->getStatus() == CModelEntity::FIXED)
        {
          pConstParameter = pModel->getModelValues()[i];
        }

      if (pModel->getModelValues()[i]->getStatus() == CModelEntity::ASSIGNMENT)
        {
          pNonConstParameter = pModel->getModelValues()[i];
        }
    }

  CPPUNIT_ASSERT(pConstParameter != NULL);
  CPPUNIT_ASSERT(pNonConstParameter != NULL);
  // check if the kinetic law is mass action with const global parameter as the kinetic constant
  CPPUNIT_ASSERT(pReaction->getChemEq().getSubstrates().size() == 1);
  CPPUNIT_ASSERT(pReaction->getChemEq().getProducts().size() == 1);
  CPPUNIT_ASSERT(pReaction->getChemEq().getModifiers().size() == 0);
  CPPUNIT_ASSERT(pReaction->isReversible() == false);
  const CFunction* pKineticLaw = pReaction->getFunction();
  CPPUNIT_ASSERT(pKineticLaw != NULL);
  CPPUNIT_ASSERT(pKineticLaw->getType() == CEvaluationTree::MassAction);
  const std::vector< std::vector<std::string> > & parameterMappings = pReaction->getParameterMappings();
  CPPUNIT_ASSERT(parameterMappings.size() == 2);
  CPPUNIT_ASSERT(parameterMappings[0].size() == 1);
  CPPUNIT_ASSERT(parameterMappings[0][0] == pConstParameter->getKey());
  CPPUNIT_ASSERT(parameterMappings[1].size() == 1);
  std::string substrateKey = parameterMappings[1][0];
  const CCopasiObject* pTempObject = CCopasiRootContainer::getKeyFactory()->get(substrateKey);
  CPPUNIT_ASSERT(pTempObject != NULL);
  const CMetab* pSubstrate = dynamic_cast<const CMetab*>(pTempObject);
  CPPUNIT_ASSERT(pSubstrate != NULL);
  // check that the assignment consists of only one object node that is a reference to the reaction flux
  const CExpression* pExpression = pNonConstParameter->getExpressionPtr();
  CPPUNIT_ASSERT(pExpression != NULL);
  const CEvaluationNode* pRoot = pExpression->getRoot();
  CPPUNIT_ASSERT(pRoot != NULL);
  CPPUNIT_ASSERT(CEvaluationNode::type(pRoot->getType()) == CEvaluationNode::OBJECT);
  const CEvaluationNodeObject* pObjectNode = dynamic_cast<const CEvaluationNodeObject*>(pRoot);
  CPPUNIT_ASSERT(pObjectNode != NULL);
  const CRegisteredObjectName cn = pObjectNode->getObjectCN();
  std::vector<CCopasiContainer*> listOfContainers;
  listOfContainers.push_back(pCOPASIDATAMODEL->getModel());
  const CCopasiObject* pObject = pCOPASIDATAMODEL->ObjectFromName(listOfContainers, cn);
  CPPUNIT_ASSERT(pObject != NULL);
  CPPUNIT_ASSERT(pObject->isReference() == true);
  CPPUNIT_ASSERT(pObject->getObjectName() == "Flux");
  CPPUNIT_ASSERT(pObject->getObjectParent() == pReaction);
  // Simulate the model (5 steps, stepsize 1 and check that at each step, the value of the variable parameter
  // is the same as the flux through the reaction.
  std::ostringstream result;
  // create a report with the correct filename and all the species against
  // time.
  CReportDefinitionVector* pReports = pCOPASIDATAMODEL->getReportDefinitionList();
  CReportDefinition* pReport = pReports->createReportDefinition("Report", "Output for simulation");
  pReport->setTaskType(CCopasiTask::timeCourse);
  pReport->setIsTable(false);
  pReport->setSeparator(CCopasiReportSeparator(", "));

  std::vector<CRegisteredObjectName>* pHeader = pReport->getHeaderAddr();
  std::vector<CRegisteredObjectName>* pBody = pReport->getBodyAddr();
  pHeader->push_back(CCopasiStaticString("time").getCN());
  pHeader->push_back(pReport->getSeparator().getCN());
  pHeader->push_back(CCopasiStaticString("substrate").getCN());
  pHeader->push_back(pReport->getSeparator().getCN());
  pHeader->push_back(CCopasiStaticString("reaction flux").getCN());
  pHeader->push_back(pReport->getSeparator().getCN());
  pHeader->push_back(CCopasiStaticString("variable model value").getCN());
  pBody->push_back(CCopasiObjectName(pCOPASIDATAMODEL->getModel()->getCN() + ",Reference=Time"));
  pBody->push_back(CRegisteredObjectName(pReport->getSeparator().getCN()));
  pBody->push_back(CCopasiObjectName(pSubstrate->getCN() + ",Reference=Concentration"));
  pBody->push_back(CRegisteredObjectName(pReport->getSeparator().getCN()));
  pBody->push_back(CCopasiObjectName(pReaction->getCN() + ",Reference=Flux"));
  pBody->push_back(CRegisteredObjectName(pReport->getSeparator().getCN()));
  pBody->push_back(CCopasiObjectName(pNonConstParameter->getCN() + ",Reference=Value"));
  //
  // create a trajectory task
  CTrajectoryTask* pTrajectoryTask = new CTrajectoryTask();
  // use LSODAR from now on since we will have events pretty soon
  pTrajectoryTask->setMethodType(CCopasiMethod::LSODAR);
  pTrajectoryTask->getProblem()->setModel(pCOPASIDATAMODEL->getModel());

  pTrajectoryTask->setScheduled(true);
  pTrajectoryTask->getReport().setReportDefinition(pReport);
  // the target needs to be set in order to get output on the stream
  // object passed to the task in the call to initialize below
  pTrajectoryTask->getReport().setTarget("test.tmp");

  CTrajectoryProblem* pProblem = dynamic_cast<CTrajectoryProblem*>(pTrajectoryTask->getProblem());

  pProblem->setStepNumber((const unsigned C_INT32)30);
  pCOPASIDATAMODEL->getModel()->setInitialTime((const C_FLOAT64)0.0);
  pProblem->setDuration((const C_FLOAT64)30);
  pProblem->setTimeSeriesRequested(true);

  CTrajectoryMethod* pMethod = dynamic_cast<CTrajectoryMethod*>(pTrajectoryTask->getMethod());

  pMethod->getParameter("Absolute Tolerance")->setValue(1.0e-12);

  CCopasiVectorN< CCopasiTask > & TaskList = * pCOPASIDATAMODEL->getTaskList();

  TaskList.remove("Time-Course");
  TaskList.add(pTrajectoryTask, true);

  try
    {
      pTrajectoryTask->initialize(CCopasiTask::OUTPUT_UI, pCOPASIDATAMODEL, &result);
      pTrajectoryTask->process(true);
      pTrajectoryTask->restore();
    }
  catch (...)
    {
      // there should be no exception
      CPPUNIT_ASSERT(false);
    }

  // analyse the result
  CPPUNIT_ASSERT(!result.str().empty());
  std::string result_string = result.str();
  std::string delimiter = "\n";
  std::string delimiter2 = ",";
  std::size_t lastPos = result_string.find_first_not_of(delimiter);
  std::size_t pos;
  std::string line, number_string;
  unsigned int index = 0;
  unsigned int index2;
  std::size_t lastPos2;
  std::size_t pos2;
  double last = std::numeric_limits<double>::max(), current = std::numeric_limits<double>::max();

  while (lastPos != std::string::npos)
    {
      pos = result_string.find_first_of(delimiter, lastPos);
      line = result_string.substr(lastPos, pos - lastPos);
      lastPos = result_string.find_first_not_of(delimiter, pos);
      lastPos2 = line.find_first_not_of(delimiter2);

      // skip the header line
      if (index != 0)
        {
          index2 = 0;

          while (lastPos2 != std::string::npos)
            {
              pos2 = line.find_first_of(delimiter2, lastPos2);
              number_string = line.substr(lastPos2, pos2 - lastPos2);
              lastPos2 = line.find_first_not_of(delimiter2, pos2);

              // skip the time column
              if (index2 != 0)
                {
                  //check that all values in the row (besides the time)
                  // are always the same
                  if (index2 == 1)
                    {
                      last = strToDouble(number_string.c_str(), NULL);

                      if (index == 1)
                        {
                          // just make sure that we don't compare all zeros
                          // The initial value of the substrate hould be higher than 1
                          CPPUNIT_ASSERT(fabs(pSubstrate->getInitialValue()) > 1);
                          // the first rwo should correspond the the initial value of the substrate
                          // We check this to make sure that the whole timeseries does not consist of zeros
                          CPPUNIT_ASSERT(fabs((last - pSubstrate->getInitialConcentration()) / pSubstrate->getInitialConcentration()) < 1e-20);
                        }
                    }
                  else
                    {
                      current = strToDouble(number_string.c_str(), NULL);
                      CPPUNIT_ASSERT(fabs((current - last) / last) < 1e-20);
                      last = current;
                    }
                }

              ++index2;
            }
        }

      ++index;
    }

  // make sure there actually were datapoints
  CPPUNIT_ASSERT(index > 1);
  // the simulation is set to run until all substrate is depleted, so in the end
  // last should be below the absolute tolerance for the simulation
  CPPUNIT_ASSERT(last < *pMethod->getParameter("Absolute Tolerance")->getValue().pDOUBLE);
}
/*
 * build the population tree
 */
void CCopasiSimpleSelectionTree::populateTree(const CModel * pModel,
    const ObjectClasses & classes)
{
  if (!pModel) return;

  const CCopasiObject * pObject;
  Q3ListViewItem * pItem;

  // find all kinds of time
  pObject = pModel->getObject(CCopasiObjectName("Reference=Time"));

  if (filter(classes, pObject))
    {
      pItem = new Q3ListViewItem(mpTimeSubtree, "Model Time");
      treeItems[pItem] = pObject;
    }

  pObject = pModel->getObject(CCopasiObjectName("Reference=Initial Time"));

  if (filter(classes, pObject))
    {
      pItem = new Q3ListViewItem(mpTimeSubtree, "Model Initial Time");
      treeItems[pItem] = pObject;
    }

  pObject = pModel->getObjectDataModel()->getObject(CCopasiObjectName("Timer=CPU Time"));

  if (filter(classes, pObject))
    {
      pItem = new Q3ListViewItem(mpTimeSubtree, "CPU time");
      treeItems[pItem] = pObject;
    }

  pObject = pModel->getObjectDataModel()->getObject(CCopasiObjectName("Timer=Wall Clock Time"));

  if (filter(classes, pObject))
    {
      pItem = new Q3ListViewItem(mpTimeSubtree, "real time");
      treeItems[pItem] = pObject;
    }

  removeEmptySubTree(&mpTimeSubtree);

  // find all species (aka metabolites) and create items in the metabolite subtree
  const CCopasiVector<CMetab>& metabolites = pModel->getMetabolites();
  unsigned int counter;
  unsigned int maxCount = metabolites.size();

  for (counter = maxCount; counter != 0; --counter)
    {
      const CMetab* metab = metabolites[counter - 1];
      std::string name = metab->getObjectName();
      bool unique = isMetaboliteNameUnique(name, metabolites);

      if (!unique)
        {
          const CCompartment* comp = metab->getCompartment();

          if (comp)
            {
              name = name + "(" + comp->getObjectName() + ")";
            }
        }

      pObject = metab->getObject(CCopasiObjectName("Reference=InitialParticleNumber"));

      if (filter(classes, pObject))
        {
          pItem = new Q3ListViewItem(mpMetaboliteInitialNumberSubtree, FROM_UTF8(name + "(t=0)"));
          treeItems[pItem] = pObject;
        }

      pObject = metab->getObject(CCopasiObjectName("Reference=ParticleNumber"));

      if (filter(classes, pObject))
        {
          pItem = new Q3ListViewItem(mpMetaboliteTransientNumberSubtree, FROM_UTF8(name + "(t)"));
          treeItems[pItem] = pObject;
        }

      if (metab->getStatus() != CModelEntity::ASSIGNMENT)
        {
          pObject = metab->getObject(CCopasiObjectName("Reference=ParticleNumberRate"));

          if (filter(classes, pObject))
            {
              pItem = new Q3ListViewItem(mpMetaboliteRateNumberSubtree, FROM_UTF8("d(" + name + ")/dt"));
              treeItems[pItem] = pObject;
            }
        }

      name = "[" + name + "]"; // Concentration
      pObject = metab->getObject(CCopasiObjectName("Reference=InitialConcentration"));

      if (filter(classes, pObject))
        {
          pItem = new Q3ListViewItem(mpMetaboliteInitialConcentrationSubtree, FROM_UTF8(name + "(t=0)"));
          treeItems[pItem] = pObject;
        }

      pObject = metab->getObject(CCopasiObjectName("Reference=Concentration"));

      if (filter(classes, pObject))
        {
          pItem = new Q3ListViewItem(mpMetaboliteTransientConcentrationSubtree, FROM_UTF8(name + "(t)"));
          treeItems[pItem] = pObject;
        }

      if (metab->getStatus() != CModelEntity::ASSIGNMENT)
        {
          pObject = metab->getObject(CCopasiObjectName("Reference=Rate"));

          if (filter(classes, pObject))
            {
              pItem = new Q3ListViewItem(mpMetaboliteRateConcentrationSubtree, FROM_UTF8("d(" + name + ")/dt"));
              treeItems[pItem] = pObject;
            }
        }
    }

  removeEmptySubTree(&mpMetaboliteInitialNumberSubtree);
  removeEmptySubTree(&mpMetaboliteTransientNumberSubtree);
  removeEmptySubTree(&mpMetaboliteRateNumberSubtree);
  removeEmptySubTree(&mpMetaboliteInitialConcentrationSubtree);
  removeEmptySubTree(&mpMetaboliteTransientConcentrationSubtree);
  removeEmptySubTree(&mpMetaboliteRateConcentrationSubtree);
  removeEmptySubTree(&mpMetaboliteSubtree);

  // find all reactions and create items in the reaction subtree
  const CCopasiVectorNS<CReaction>& reactions = pModel->getReactions();
  maxCount = reactions.size();

  for (counter = maxCount; counter != 0; --counter)
    {
      const CReaction* react = reactions[counter - 1];
      std::string name = "flux(" + react->getObjectName() + ")";

      pObject = react->getObject(CCopasiObjectName("Reference=Flux"));

      if (filter(classes, pObject))
        {
          pItem = new Q3ListViewItem(mpReactionFluxConcentrationSubtree, FROM_UTF8(name));
          treeItems[pItem] = pObject;
        }

      pObject = react->getObject(CCopasiObjectName("Reference=ParticleFlux"));

      if (filter(classes, pObject))
        {
          pItem = new Q3ListViewItem(mpReactionFluxNumberSubtree, FROM_UTF8("particle " + name));
          treeItems[pItem] = pObject;
        }

      // create items for the reaction parameters

      pItem = new Q3ListViewItem(mpReactionParameterSubtree,
                                 FROM_UTF8(react->getObjectName()));
      const CCopasiParameterGroup & Parameters = react->getParameters();
      unsigned int j;
      unsigned int numParameters = Parameters.size();

      for (j = numParameters; j != 0; --j)
        {
          const CCopasiParameter * pParameter = Parameters.getParameter(j - 1);

          // We skip local parameters which ar covered by global parameters
          if (!react->isLocalParameter(pParameter->getObjectName()))
            continue;

          pObject = pParameter->getObject(CCopasiObjectName("Reference=Value"));

          if (filter(classes, pObject))
            {
              Q3ListViewItem * pParameterItem =
                new Q3ListViewItem(pItem, FROM_UTF8(pParameter->getObjectName()));
              treeItems[pParameterItem] = pObject;
            }
        }

      removeEmptySubTree(&pItem);
    }

  removeEmptySubTree(&mpReactionFluxNumberSubtree);
  removeEmptySubTree(&mpReactionFluxConcentrationSubtree);
  removeEmptySubTree(&mpReactionParameterSubtree);
  removeEmptySubTree(&mpReactionSubtree);

  // find all global parameters (aka model values) variables
  const CCopasiVector<CModelValue>& objects = pModel->getModelValues();
  maxCount = objects.size();

  for (counter = maxCount; counter != 0; --counter)
    {
      const CModelEntity* object = objects[counter - 1];
      std::string name = object->getObjectName();

      pObject = object->getObject(CCopasiObjectName("Reference=InitialValue"));

      if (filter(classes, pObject))
        {
          pItem = new Q3ListViewItem(mpModelQuantityInitialValueSubtree, FROM_UTF8(name + "(t=0)"));
          treeItems[pItem] = pObject;
        }

      pObject = object->getObject(CCopasiObjectName("Reference=Value"));

      if (filter(classes, pObject))
        {
          pItem = new Q3ListViewItem(mpModelQuantityTransientValueSubtree, FROM_UTF8(name + "(t)"));
          treeItems[pItem] = pObject;
        }

      if (object->getStatus() != CModelEntity::ASSIGNMENT)
        {
          pObject = object->getObject(CCopasiObjectName("Reference=Rate"));

          if (filter(classes, pObject))
            {
              pItem = new Q3ListViewItem(mpModelQuantityRateSubtree, FROM_UTF8("d(" + name + ")/dt"));
              treeItems[pItem] = pObject;
            }
        }
    }

  removeEmptySubTree(&mpModelQuantityRateSubtree);
  removeEmptySubTree(&mpModelQuantityInitialValueSubtree);
  removeEmptySubTree(&mpModelQuantityTransientValueSubtree);
  removeEmptySubTree(&mpModelQuantitySubtree);

  // find all compartments
  const CCopasiVector<CCompartment>& objects2 = pModel->getCompartments();
  maxCount = objects2.size();

  for (counter = maxCount; counter != 0; --counter)
    {
      const CModelEntity* object = objects2[counter - 1];
      std::string name = object->getObjectName();

      pObject = object->getObject(CCopasiObjectName("Reference=InitialVolume"));

      if (filter(classes, pObject))
        {
          pItem = new Q3ListViewItem(mpCompartmentInitialVolumeSubtree, FROM_UTF8(name + "(t=0)"));
          treeItems[pItem] = pObject;
        }

      pObject = object->getObject(CCopasiObjectName("Reference=Volume"));

      if (filter(classes, pObject))
        {
          pItem = new Q3ListViewItem(mpCompartmentTransientVolumeSubtree, FROM_UTF8(name + "(t)"));
          treeItems[pItem] = pObject;
        }

      if (object->getStatus() != CModelEntity::ASSIGNMENT)
        {
          pObject = object->getObject(CCopasiObjectName("Reference=Rate"));

          if (filter(classes, pObject))
            {
              pItem = new Q3ListViewItem(mpCompartmentRateSubtree, FROM_UTF8("d(" + name + ")/dt"));
              treeItems[pItem] = pObject;
            }
        }
    }

  removeEmptySubTree(&mpCompartmentRateSubtree);
  removeEmptySubTree(&mpCompartmentInitialVolumeSubtree);
  removeEmptySubTree(&mpCompartmentTransientVolumeSubtree);
  removeEmptySubTree(&mpCompartmentSubtree);

  pObject = pModel->getObject(CCopasiObjectName("Reference=Avogadro Constant"));

  if (filter(classes, pObject))
    {
      pItem = new Q3ListViewItem(this, "Avogadro Constant");
      treeItems[pItem] = pObject;
    }

  pObject = pModel->getObject(CCopasiObjectName("Reference=Quantity Conversion Factor"));

  if (filter(classes, pObject))
    {
      pItem = new Q3ListViewItem(this, "Quantity Conversion Factor");
      treeItems[pItem] = pObject;
    }

  // find all model matrices
  const CMatrix<C_FLOAT64> &StoiMatrix = pModel->getStoi();

  if (StoiMatrix.array())
    {
      pObject = pModel->getObject(CCopasiObjectName("Array=Stoichiometry(ann)"));

      if (filter(classes, pObject))
        {
          //      pItem = new QListViewItem(matrixSubtree, "Stoichiometry(ann)");
          pItem = new Q3ListViewItem(mpModelMatrixSubtree, FROM_UTF8(pObject->getObjectName()));
          treeItems[pItem] = pObject;
        }
    }

  const CMatrix<C_FLOAT64> &RedStoiMatrix = pModel->getRedStoi();

  if (RedStoiMatrix.array())
    {
      pObject = pModel->getObject(CCopasiObjectName("Array=Reduced stoichiometry(ann)"));

      if (filter(classes, pObject))
        {
          //      pItem = new QListViewItem(matrixSubtree, "Reduced stoichiometry(ann)");
          pItem = new Q3ListViewItem(mpModelMatrixSubtree, FROM_UTF8(pObject->getObjectName()));
          treeItems[pItem] = pObject;
        }
    }

  const CMatrix<C_FLOAT64> &LinkMatrix = pModel->getL0();

  if (LinkMatrix.array())
    {
      pObject = pModel->getObject(CCopasiObjectName("Array=Link matrix(ann)"));

      if (filter(classes, pObject))
        {
          //      pItem = new QListViewItem(matrixSubtree, "Link matrix(ann)");
          pItem = new Q3ListViewItem(mpModelMatrixSubtree, FROM_UTF8(pObject->getObjectName()));
          treeItems[pItem] = pObject;
        }
    }

  removeEmptySubTree(&mpModelMatrixSubtree);

  // find all result matrices
  // Metabolic Control Analysis
  CCopasiTask *task;
  assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
  CCopasiDataModel* pDataModel = (*CCopasiRootContainer::getDatamodelList())[0];
  assert(pDataModel != NULL);
  // MCA
  task = dynamic_cast<CCopasiTask*>((*pDataModel->getTaskList())["Metabolic Control Analysis"]);

  try
    {
      if (task && task->updateMatrices())
        {
          //for mca the result is in the method
          CMCAMethod* pMethod = dynamic_cast<CMCAMethod *>(task->getMethod());

          const CCopasiContainer::objectMap * pObjects = & pMethod->getObjects();
          CCopasiContainer::objectMap::const_iterator its = pObjects->begin();
          CArrayAnnotation *ann;

          for (; its != pObjects->end(); ++its)
            {
              ann = dynamic_cast<CArrayAnnotation*>(its->second);

              if (!ann) continue;

              if (!ann->isEmpty() && filter(classes, ann))
                {
                  pItem = new Q3ListViewItem(this->mpResultMCASubtree, FROM_UTF8(ann->getObjectName()));
                  treeItems[pItem] = ann;
                }
            }
        }
    }
  catch (...)
    {}

  // Steady State
  task = dynamic_cast<CCopasiTask *>((*pDataModel->getTaskList())["Steady-State"]);

  try
    {
      if (task && task->updateMatrices())
        {
          //for steady state the results are in the task
          const CCopasiContainer::objectMap * pObjects = & task->getObjects();
          CCopasiContainer::objectMap::const_iterator its = pObjects->begin();
          CArrayAnnotation *ann;

          for (; its != pObjects->end(); ++its)
            {
              ann = dynamic_cast<CArrayAnnotation*>(its->second);

              if (!ann) continue;

              if (!ann->isEmpty() && filter(classes, ann))
                {
                  pItem = new Q3ListViewItem(this->mpResultSteadyStateSubtree, FROM_UTF8(ann->getObjectName()));
                  treeItems[pItem] = ann;
                }
            }
        }
    }
  catch (...)
    {}

  // Sensitivities
  task = dynamic_cast<CCopasiTask *>((*pDataModel->getTaskList())["Sensitivities"]);

  try
    {
      if (task && task->updateMatrices())
        {
          //for sensitivities the result is in the problem
          CSensProblem *sens = dynamic_cast<CSensProblem *>(task->getProblem());

          const CCopasiContainer::objectMap * pObjects = & sens->getObjects();
          CCopasiContainer::objectMap::const_iterator its = pObjects->begin();
          CArrayAnnotation *ann;

          for (; its != pObjects->end(); ++its)
            {
              ann = dynamic_cast<CArrayAnnotation*>(its->second);

              if (!ann) continue;

              if (!ann->isEmpty() && filter(classes, ann))
                {
                  pItem = new Q3ListViewItem(this->mpResultSensitivitySubtree, FROM_UTF8(ann->getObjectName()));
                  treeItems[pItem] = (CCopasiObject *) ann;
                }
            }
        }
    }
  catch (...)
    {}

  removeEmptySubTree(&mpResultMCASubtree);
  removeEmptySubTree(&mpResultSensitivitySubtree);
  removeEmptySubTree(&mpResultSteadyStateSubtree);
  removeEmptySubTree(&mpResultMatrixSubtree);

  if (selectionMode() == Q3ListView::NoSelection)
    {
      // see if some objects are there, if yes set to single selection
      Q3ListViewItemIterator it = Q3ListViewItemIterator(this);

      while (it.current())
        {
          if (treeItems.find(it.current()) != treeItems.end())
            {
              setSelectionMode(Q3ListView::Single);
              setCurrentItem(it.current());
              it.current()->setSelected(true);
              Q3ListViewItem* parent = it.current()->parent();

              while (parent)
                {
                  parent->setOpen(true);
                  parent = parent->parent();
                }

              break;
            }

          ++it;
        }
    }
}
示例#20
0
bool Curve2DWidget::SaveToCurveSpec(CPlotItem * curve, const CPlotItem *original /*= NULL*/) const
{
  //if (!(mpObjectX && mpObjectY)) return false;

  //curve->setType(CPlotItem::curve2d);

  std::string title = TO_UTF8(mpEditTitle->text());
  unsigned C_INT32 lineType = (unsigned C_INT32)mpBoxType->currentIndex();
  unsigned C_INT32 lineSubType = (unsigned C_INT32)mpBoxLineSubType->currentIndex();
  unsigned C_INT32 symbolSubType = (unsigned C_INT32)mpBoxSymbolSubType->currentIndex();
  C_FLOAT64 lineWidth = (C_FLOAT64)mpSpinBoxWidth->value();
  std::string color = TO_UTF8(mpBoxColor->currentText());

  C_INT32 Activity = 0;

  if (mpCheckBefore->isChecked()) Activity += COutputInterface::BEFORE;

  if (mpCheckDuring->isChecked()) Activity += COutputInterface::DURING;

  if (mpCheckAfter->isChecked()) Activity += COutputInterface::AFTER;

  CCopasiObjectName xName = mpObjectX ? mpObjectX->getCN() : CCopasiObjectName("");
  CCopasiObjectName yName = mpObjectY ? mpObjectY->getCN() : CCopasiObjectName("");

  bool thingsChanged = false;

  if (original != NULL)
    {
      // compare whether things changed
      if (original->getTitle() != title)
        thingsChanged = true;

      if (thingsChanged || original->getType() != CPlotItem::curve2d)
        thingsChanged = true;

      if (thingsChanged || *original->getValue("Line type").pUINT != lineType)
        thingsChanged = true;

      if (thingsChanged || *original->getValue("Line subtype").pUINT != lineSubType)
        thingsChanged = true;

      if (thingsChanged || *original->getValue("Symbol subtype").pUINT != symbolSubType)
        thingsChanged = true;

      if (thingsChanged || *original->getValue("Line width").pDOUBLE != lineWidth)
        thingsChanged = true;

      if (thingsChanged || *original->getValue("Color").pSTRING != color)
        thingsChanged = true;

      if (thingsChanged || original->getActivity() != Activity)
        thingsChanged = true;

      if (thingsChanged || original->getChannels().size() != 2)
        thingsChanged = true;

      if (thingsChanged || original->getChannels()[0] != xName)
        thingsChanged = true;

      if (thingsChanged || original->getChannels()[1] != yName)
        thingsChanged = true;
    }
  else thingsChanged = true;

  if (!thingsChanged)
    return false;

  //title
  curve->setTitle(title);

  //channels
  curve->getChannels().clear();
  curve->getChannels().push_back(CPlotDataChannelSpec(xName));
  curve->getChannels().push_back(CPlotDataChannelSpec(yName));

  curve->setValue("Line type", lineType);
  curve->setValue("Line subtype", lineSubType);
  curve->setValue("Symbol subtype", symbolSubType);
  curve->setValue("Line width", lineWidth);

  //color
  curve->setValue("Color", color);

  curve->setActivity((COutputInterface::Activity) Activity);

  return true;
}
示例#21
0
bool ReactionsWidget1::saveToReaction()
{
  CReaction* reac = dynamic_cast< CReaction * >(CCopasiRootContainer::getKeyFactory()->get(mKey));

  if (reac == NULL) return true;

  if (!LineEdit2->isValid()) return false;

  LineEdit2->slotForceUpdate();

  if (!mpRi->isValid()) return false;

  assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
  CCopasiDataModel* pDataModel = (*CCopasiRootContainer::getDatamodelList())[0];
  assert(pDataModel != NULL);

  CModel * pModel = pDataModel->getModel();

  if (pModel == NULL) return false;

  // Before we save any changes we must check whether any local reaction parameters,
  // which are used in any mathematical expression in the model are removed.
  // If that is the case the user must have option to cancel the changes or remove the
  // affected expressions.
  std::set< const CCopasiObject * > DeletedParameters = mpRi->getDeletedParameters();

  if (DeletedParameters.size() != 0)
    {
      QString ObjectType = "parameter(s)";
      QString Objects;

      std::set< const CCopasiObject * >::const_iterator itParameter, endParameter = DeletedParameters.end();
      std::set< const CCopasiObject * > DeletedObjects;

      for (itParameter = DeletedParameters.begin(); itParameter != endParameter; ++itParameter) //all parameters
        {
          Objects.append(FROM_UTF8((*itParameter)->getObjectName()) + ", ");
          DeletedObjects.insert(static_cast< const CCopasiObject * >((*itParameter)->getObject(CCopasiObjectName("Reference=Value"))));
        }

      Objects.remove(Objects.length() - 2, 2);

      QMessageBox::StandardButton choice =
        CQMessageBox::confirmDelete(NULL, ObjectType,
                                    Objects, DeletedObjects);

      switch (choice)
        {
          case QMessageBox::Ok:

            for (itParameter = DeletedParameters.begin(); itParameter != endParameter; ++itParameter) //all parameters
              pModel->removeLocalReactionParameter((*itParameter)->getKey());

            protectedNotify(ListViews::REACTION, ListViews::DELETE, "");
            break;

          default:
            return true;
            break;
        }
    }

  // We need to check whether the current reaction still exists, since it is possible that
  // removing a local reaction parameter triggers its deletion.
  reac = dynamic_cast< CReaction * >(CCopasiRootContainer::getKeyFactory()->get(mKey));

  if (reac == NULL)
    {
      mpRi->setFunctionWithEmptyMapping("");

      protectedNotify(ListViews::REACTION, ListViews::DELETE, mKey);
      protectedNotify(ListViews::REACTION, ListViews::DELETE, ""); //Refresh all as there may be dependencies.
      return true;
    }

  //first check if new metabolites need to be created
  bool createdMetabs = mpRi->createMetabolites();
  bool createdObjects = mpRi->createOtherObjects();

  //this writes all changes to the reaction
  mpRi->writeBackToReaction(NULL);

  assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
  //(*CCopasiRootContainer::getDatamodelList())[0]->getModel()->compile();

  //this tells the gui what it needs to know.
  if (createdObjects)
    protectedNotify(ListViews::MODEL, ListViews::CHANGE, "");
  else
    {
      if (createdMetabs) protectedNotify(ListViews::METABOLITE, ListViews::ADD, "");

      // :TODO Bug 322: This should only be called when actual changes have been saved.
      if (this->isShown())
        protectedNotify(ListViews::REACTION, ListViews::CHANGE, mKey);
    }

  //TODO: detect rename events (mpRi->writeBackToReaction has to do this)

  // :TODO Bug 322: This should only be called when actual changes have been saved.
  if (this->isShown())
    (*CCopasiRootContainer::getDatamodelList())[0]->changed();

  return true;
}
示例#22
0
bool
BandedGraphWidget::SaveToCurveSpec(CPlotItem * curve, const CPlotItem *original /*= NULL*/) const
{
  //curve->setType(CPlotItem::bandedGraph);

  std::string title = TO_UTF8(mpEditTitle->text());

  CCopasiObjectName xName = mpObjectX ? mpObjectX->getCN() : CCopasiObjectName("");
  CCopasiObjectName yName1 = mpObjectYone ? mpObjectYone->getCN() : CCopasiObjectName("");
  CCopasiObjectName yName2 = mpObjectYtwo ? mpObjectYtwo->getCN() : (mpObjectYone ? mpObjectYone->getCN() : CCopasiObjectName(""));

  C_INT32 Activity = 0;

  if (mpCheckBefore->isChecked()) Activity += COutputInterface::BEFORE;

  if (mpCheckDuring->isChecked()) Activity += COutputInterface::DURING;

  if (mpCheckAfter->isChecked()) Activity += COutputInterface::AFTER;

  bool thingsChanged = false;

  if (original != NULL)
    {
      // compare whether things changed
      if (original->getTitle() != title)
        thingsChanged = true;

      if (thingsChanged || original->getType() != CPlotItem::bandedGraph)
        thingsChanged = true;

      if (thingsChanged || original->getActivity() != Activity)
        thingsChanged = true;

      if (thingsChanged || original->getChannels().size() != 3)
        thingsChanged = true;

      if (thingsChanged || original->getChannels()[0] != xName)
        thingsChanged = true;

      if (thingsChanged || original->getChannels()[1] != yName1)
        thingsChanged = true;

      if (thingsChanged || original->getChannels()[2] != yName2)
        thingsChanged = true;
    }
  else thingsChanged = true;

  if (!thingsChanged)
    return false;

  //title
  curve->setTitle(title);

  //channels
  curve->getChannels().clear();
  curve->getChannels().push_back(CPlotDataChannelSpec(xName));
  curve->getChannels().push_back(CPlotDataChannelSpec(yName1));
  curve->getChannels().push_back(CPlotDataChannelSpec(yName2));

  curve->setActivity((COutputInterface::Activity) Activity);

  return true;
}
示例#23
0
/**
 * Creates the data generators for SEDML.
 */
void CSEDMLExporter::createDataGenerators(CCopasiDataModel & dataModel,
    std::string & taskId,
    CCopasiTask* task)
{
  const CModel* pModel = dataModel.getModel();
  std::vector<std::string> stringsContainer; //split string container

  if (pModel == NULL)
    CCopasiMessage(CCopasiMessage::ERROR, "SED-ML: No model for this SED-ML document. An SBML model must exist for every SED-ML document.");

  SedPlot2D* pPSedPlot;
  SedCurve* pCurve; // = pPSedPlot->createCurve();

  //create generator for special varibale time
  const CCopasiObject* pTime = static_cast<const CCopasiObject *>(dataModel.getModel()->getObject(CCopasiObjectName("Reference=Time")));
  SedDataGenerator *pTimeDGenp = this->mpSEDMLDocument->createDataGenerator();
  pTimeDGenp->setId("time");
  pTimeDGenp->setName(pTime->getObjectName());
  SedVariable *pTimeVar = pTimeDGenp->createVariable();
  pTimeVar->setId("var_time");
  pTimeVar->setTaskReference(taskId);
  pTimeVar->setSymbol(SEDML_TIME_URN);
  pTimeDGenp->setMath(SBML_parseFormula(pTimeVar->getId().c_str()));

  size_t i, imax = dataModel.getPlotDefinitionList()->size();
  SedDataGenerator *pPDGen;

  if (imax == 0 && (task == NULL || task->getReport().getTarget().empty()))
    CCopasiMessage(CCopasiMessage::ERROR, "SED-ML: No plot/report definition for this SED-ML document.");

  // export report
  if (task != NULL && !task->getReport().getTarget().empty())
    {
      CReportDefinition* def = task->getReport().getReportDefinition();

      if (def != NULL)
        {
          SedReport* pReport = mpSEDMLDocument->createReport();
          std::string name = def->getObjectName();
          SEDMLUtils::removeCharactersFromString(name, "[]");
          //
          pReport->setId(SEDMLUtils::getNextId("report", mpSEDMLDocument->getNumOutputs()));
          pReport->setName(name);

          std::vector<CRegisteredObjectName> header = *def->getHeaderAddr();
          std::vector<CRegisteredObjectName> body =
            def->isTable() ? *def->getTableAddr() :
            *def->getBodyAddr();

          int dsCount = 0;

          for (size_t i = 0; i < body.size(); ++i)
            {
              CRegisteredObjectName& current = body[i];

              if (current == def->getSeparator().getCN()) continue;

              CCopasiObject *object = dataModel.getDataObject(current);

              if (object == NULL) continue;

              const std::string& typeX = object->getObjectName();
              std::string xAxis = object->getObjectDisplayName();

              std::string targetXPathStringX = SEDMLUtils::getXPathAndName(xAxis, typeX,
                                               pModel, dataModel);

              if (object->getCN() == pTime->getCN())
                pPDGen = pTimeDGenp;
              else
                pPDGen = createDataGenerator(
                           this->mpSEDMLDocument,
                           xAxis,
                           targetXPathStringX,
                           taskId,
                           i,
                           0
                         );

              SedDataSet* pDS = pReport->createDataSet();
              pDS->setId(SEDMLUtils::getNextId("ds", ++dsCount));

              if (def->isTable())
                {
                  CCopasiObject *headerObj = NULL;

                  if (header.size() > i)
                    headerObj = dataModel.getDataObject(header[i]);
                  else
                    headerObj = dataModel.getDataObject(body[i]);

                  if (headerObj != NULL)
                    pDS->setLabel(headerObj->getObjectDisplayName());
                  else
                    pDS->setLabel(xAxis);
                }
              else
                pDS->setLabel(xAxis);

              pDS->setDataReference(pPDGen->getId());
            }
        }
    }

  // export plots
  for (i = 0; i < imax; i++)
    {
      pPSedPlot = this->mpSEDMLDocument->createPlot2D();
      const CPlotSpecification* pPlot = (*dataModel.getPlotDefinitionList())[i];
      std::string plotName = pPlot->getObjectName();

      SEDMLUtils::removeCharactersFromString(plotName, "[]");

      pPSedPlot->setId(SEDMLUtils::getNextId("plot", mpSEDMLDocument->getNumOutputs()));
      pPSedPlot->setName(plotName);

      size_t j, jmax = pPlot->getItems().size();

      for (j = 0; j < jmax; j++)
        {
          const CPlotItem* pPlotItem = pPlot->getItems()[j];

          CCopasiObject *objectX, *objectY;

          if (pPlotItem->getChannels().size() >= 1)
            {
              objectX = dataModel.getDataObject(pPlotItem->getChannels()[0]);
            }
          else
            {
              CCopasiMessage(CCopasiMessage::WARNING, "SED-ML: Can't export plotItem '%s', as it has no data channel.", pPlotItem->getObjectName().c_str());
              continue;
            }

          if (objectX == NULL)
            {
              CCopasiMessage(CCopasiMessage::WARNING, "SED-ML: Can't export plotItem '%s' variable '%s', as it cannot be resolved.",  pPlotItem->getObjectName().c_str(), pPlotItem->getChannels()[0].c_str());
              continue;
            }

          bool xIsTime = objectX->getCN() == pTime->getCN();

          if (pPlotItem->getChannels().size() >= 2)
            {
              objectY = dataModel.getDataObject(pPlotItem->getChannels()[1]);
            }
          else
            {
              CCopasiMessage(CCopasiMessage::WARNING, "SED-ML: Can't export plotItem '%s', as it has only 1 data channel.", pPlotItem->getObjectName().c_str());
              continue;
            }

          if (objectY == NULL)
            {
              CCopasiMessage(CCopasiMessage::WARNING, "SED-ML: Can't export plotItem '%s' variable '%s', as it cannot be resolved.",  pPlotItem->getObjectName().c_str(), pPlotItem->getChannels()[1].c_str());
              continue;
            }

          const std::string& type = objectY->getObjectName();
          std::string yAxis = objectY->getObjectDisplayName();
          std::string sbmlId = yAxis;
          std::string targetXPathString = SEDMLUtils::getXPathAndName(sbmlId, type,
                                          pModel, dataModel);

          if (targetXPathString.empty())
            {
              CCopasiMessage(CCopasiMessage::WARNING, "SED-ML: Can't export plotItem '%s' variable '%s', as no xpath expression for it could be generated.",  pPlotItem->getObjectName().c_str(), pPlotItem->getChannels()[1].c_str());
              continue;
            }

          pPDGen = createDataGenerator(
                     this->mpSEDMLDocument,
                     sbmlId,
                     targetXPathString,
                     taskId,
                     i,
                     j
                   );

          pPDGen->setName(yAxis);

          pCurve = pPSedPlot->createCurve();
          std::ostringstream idCurveStrStream;
          idCurveStrStream << "p";
          idCurveStrStream << i + 1;
          idCurveStrStream << "_curve_";
          idCurveStrStream << j + 1;
          pCurve->setId(idCurveStrStream.str());
          pCurve->setLogX(pPlot->isLogX());
          pCurve->setLogY(pPlot->isLogY());
          pCurve->setName(yAxis);
          pCurve->setYDataReference(pPDGen->getId());

          if (xIsTime)
            {
              pCurve->setXDataReference(pTimeDGenp->getId());
            }
          else
            {
              const std::string& typeX = objectX->getObjectName();
              std::string xAxis = objectX->getObjectDisplayName();
              std::string targetXPathStringX = SEDMLUtils::getXPathAndName(xAxis, typeX,
                                               pModel, dataModel);

              pPDGen = createDataGenerator(
                         this->mpSEDMLDocument,
                         xAxis,
                         targetXPathStringX,
                         taskId,
                         i,
                         j
                       );
              pCurve->setXDataReference(pPDGen->getId());
            }
        }
    }
}
示例#24
0
/**
 * Creates the data generators for SEDML.
 */
void CSEDMLExporter::createDataGenerators(CCopasiDataModel & dataModel, std::string & taskId)
{
  const CModel* pModel = dataModel.getModel();
  std::vector<std::string> stringsContainer; //split string container

  if (pModel == NULL)
    CCopasiMessage(CCopasiMessage::ERROR, "No model for this SEDML document. An SBML model must exist for every SEDML document.");

  SedPlot2D* pPSedPlot;
  SedCurve* pCurve; // = pPSedPlot->createCurve();

  //create generator for special varibale time
  const CCopasiObject* pTime = static_cast<const CCopasiObject *>(dataModel.getModel()->getObject(CCopasiObjectName("Reference=Time")));
  SedDataGenerator *pTimeDGenp = this->mpSEDMLDocument->createDataGenerator();
  pTimeDGenp->setId("time");
  pTimeDGenp->setName(pTime->getObjectName());
  SedVariable *pTimeVar = pTimeDGenp->createVariable();
  pTimeVar->setId("var_time");
  pTimeVar->setTaskReference(taskId);
  pTimeVar->setSymbol(SEDML_TIME_URN);
  pTimeDGenp->setMath(SBML_parseFormula(pTimeVar->getId().c_str()));

  size_t i, imax = dataModel.getPlotDefinitionList()->size();
  SedDataGenerator *pPDGen;

  if (!imax)
    CCopasiMessage(CCopasiMessage::ERROR, "No plot definition for this SEDML document.");

  for (i = 0; i < imax; i++)
    {
      pPSedPlot = this->mpSEDMLDocument->createPlot2D();
      const CPlotSpecification* pPlot = (*dataModel.getPlotDefinitionList())[i];
      std::string plotName = pPlot->getObjectName();

      SEDMLUtils::removeCharactersFromString(plotName, "[]");

      pPSedPlot->setId(SEDMLUtils::getNextId("plot", mpSEDMLDocument->getNumOutputs()));
      pPSedPlot->setName(plotName);

      size_t j, jmax = pPlot->getItems().size();

      for (j = 0; j < jmax; j++)
        {
          const CPlotItem* pPlotItem = pPlot->getItems()[j];

          CCopasiObject *objectX, *objectY;

          if (pPlotItem->getChannels().size() >= 1)
            objectX = dataModel.getDataObject(pPlotItem->getChannels()[0]);

          bool xIsTime = objectX->getCN() == pTime->getCN();

          if (pPlotItem->getChannels().size() >= 2)
            objectY = dataModel.getDataObject(pPlotItem->getChannels()[1]);

          const std::string& type = objectY->getObjectName();
          std::string yAxis = objectY->getObjectDisplayName();
          std::string targetXPathString = SEDMLUtils::getXPathAndName(yAxis, type,
                                          pModel, dataModel);

          if (targetXPathString.empty())
            {
              continue;
            }

          pPDGen = createDataGenerator(
                     this->mpSEDMLDocument,
                     yAxis,
                     targetXPathString,
                     taskId,
                     i,
                     j
                   );

          pCurve = pPSedPlot->createCurve();
          std::ostringstream idCurveStrStream;
          idCurveStrStream << "p";
          idCurveStrStream << i + 1;
          idCurveStrStream << "_curve_";
          idCurveStrStream << j + 1;
          pCurve->setId(idCurveStrStream.str());
          pCurve->setLogX(pPlot->isLogX());
          pCurve->setLogY(pPlot->isLogY());
          pCurve->setYDataReference(pPDGen->getId());

          if (xIsTime)
            {
              pCurve->setXDataReference(pTimeDGenp->getId());
            }
          else
            {
              const std::string& typeX = objectX->getObjectName();
              std::string xAxis = objectX->getObjectDisplayName();
              std::string targetXPathStringX = SEDMLUtils::getXPathAndName(xAxis, typeX,
                                               pModel, dataModel);

              pPDGen = createDataGenerator(
                         this->mpSEDMLDocument,
                         xAxis,
                         targetXPathStringX,
                         taskId,
                         i,
                         j
                       );
              pCurve->setXDataReference(pPDGen->getId());
            }
        }
    }
}
示例#25
0
int main(int argc, char *argv[])
{
  // Parse the commandline options
  // first argument is the SBML filename
  // second argument is the endtime
  // third argument is the step number
  // fourth argument is the filename where the results are to be written
  // fifth argument is the tmp directory (this is not needed)
  // the rest of the arguments are species names for the result
  try
    {
      // Create the root container.
      CCopasiRootContainer::init(0, NULL, false);
    }

  catch (copasi::autoexcept &e)
    {}

  catch (copasi::option_error &e)
    {}

  if (argc < 5)
    {
      std::cout << "Usage: stochastic-testsuite METHOD SBMLFILENAME ENDTIME STEPNUMBER REPEATS OUTFILENAME SPECIESID1 SPECIESID2 ..." << std::endl;
      exit(1);
    }

  const char* pMethodType = argv[1];

  const char* pSBMLFilename = argv[2];

  const char* pEndTime = argv[3];

  const char* pStepNumber = argv[4];

  const char* pRepeats = argv[5];

  const char* pOutputFilename = argv[6];

  unsigned int NUMARGS = 7;

  /*
  std::cout << "Input : " << pSBMLFilename << std::endl;
  std::cout << "Endtime : " << pEndTime << std::endl;
  std::cout << "Stepnumber: " << pStepNumber << std::endl;
  std::cout << "Repeats : " << pRepeats << std::endl;
  std::cout << "Output file: " << pOutputFilename << std::endl;
  */
  char** pSBMLSpeciesIds = new char * [argc - NUMARGS];

  unsigned int i, iMax = argc;

  CTrajectoryTask* pTrajectoryTask = NULL;

  CScanTask* pScanTask = NULL;

  std::string CWD = COptions::getPWD();

  double endTime = strToDouble(pEndTime, &pEndTime);

  double stepNumber = strToDouble(pStepNumber, &pStepNumber);

  char** pTmpP = (char**)(&pRepeats);

  long int repeats = strtol(pRepeats, pTmpP , 10);

  CCopasiMethod::SubType MethodType;

  if (!strcmp(pMethodType, "stochastic"))
    {
      MethodType = CCopasiMethod::stochastic;
    }
  else if (!strcmp(pMethodType, "directMethod"))
    {
      MethodType = CCopasiMethod::directMethod;
    }
  else if (!strcmp(pMethodType, "tauLeap"))
    {
      MethodType = CCopasiMethod::tauLeap;
    }
  else if (!strcmp(pMethodType, "adaptiveSA"))
    {
      MethodType = CCopasiMethod::adaptiveSA;
    }
  else if (!strcmp(pMethodType, "LSODA"))
    {
      MethodType = CCopasiMethod::deterministic;
    }
  else
    {
      std::cerr << "Invalid method type. Valid options are:" << std::endl;
      std::cerr << "    stochastic" << std::endl;
      std::cerr << "    directMethod" << std::endl;
      std::cerr << "    tauLeap" << std::endl;
    }

  if (endTime == 0.0)
    {
      std::cerr << "Invalid endtime " << pEndTime << std::endl;
      exit(1);
    }

  if (stepNumber == 0.0)
    {
      std::cerr << "Invalid step number " << pStepNumber << std::endl;
      exit(1);
    }

  for (i = NUMARGS; i < iMax; ++i)
    {
      pSBMLSpeciesIds[i - NUMARGS] = argv[i];
      //std::cout << "Copying pointer to " <<  argv[i]  << "." << std::endl;
    }

  try
    {
      // Create the global data model.
      CCopasiDataModel* pDataModel = CCopasiRootContainer::addDatamodel();

      // Import the SBML File
      pDataModel->importSBML(pSBMLFilename);

      //pDataModel->getModel()->forceCompile();

      // create a report with the correct filename and all the species against
      // time.
      CReportDefinitionVector* pReports = pDataModel->getReportDefinitionList();
      CReportDefinition* pReport = pReports->createReportDefinition("Report", "Output for stochastic testsuite run");
      pReport->setTaskType(CCopasiTask::timeCourse);
      pReport->setIsTable(false);

      CCopasiReportSeparator Separator(std::string(","));
      pReport->setSeparator(Separator);

      std::vector<CRegisteredObjectName> * pHeader = pReport->getHeaderAddr();
      std::vector<CRegisteredObjectName> * pBody = pReport->getBodyAddr();

      // Add time column
      pHeader->push_back(CCopasiStaticString("time").getCN());
      pBody->push_back(CCopasiObjectName(pDataModel->getModel()->getCN() + ",Reference=Time"));

      iMax = iMax - NUMARGS;
      const CCopasiVector<CMetab>& metabolites = pDataModel->getModel()->getMetabolites();

      for (i = 0; i < iMax; ++i)
        {
          pHeader->push_back(Separator.getCN());
          pBody->push_back(Separator.getCN());

          unsigned int j, jMax = metabolites.size();

          std::string SBMLId = unQuote(pSBMLSpeciesIds[i]);

          for (j = 0; j < jMax; ++j)
            {
              if (metabolites[j]->getSBMLId() == SBMLId)
                {
                  break;
                }
            }

          if (j == jMax)
            {
              std::cerr << "Could not find a metabolite for the SBML id \"" << pSBMLSpeciesIds[i] << "\"" << std::endl;
              exit(1);
            }

          pHeader->push_back(CCopasiStaticString(SBMLId).getCN());
          pBody->push_back(metabolites[j]->getObject(CCopasiObjectName("Reference=ParticleNumber"))->getCN());
        }

      // create a trajectory task
      pTrajectoryTask = new CTrajectoryTask();
      pTrajectoryTask->setMethodType(MethodType);
      pTrajectoryTask->getProblem()->setModel(pDataModel->getModel());
      pTrajectoryTask->setScheduled(false);

      //pTrajectoryTask->getReport().setReportDefinition(pReport);
      //pTrajectoryTask->getReport().setTarget(CWD + "/" + pOutputFilename);
      //pTrajectoryTask->getReport().setAppend(false);

      CTrajectoryProblem* pProblem = dynamic_cast<CTrajectoryProblem*>(pTrajectoryTask->getProblem());

      pProblem->setStepNumber((const unsigned C_INT32)stepNumber);
      pProblem->setDuration((const C_FLOAT64)endTime);
      pProblem->setTimeSeriesRequested(true);
      pProblem->setTimeSeriesRequested(false);

      //pProblem->setInitialState(pDataModel->getModel()->getInitialState());

      CCopasiVectorN< CCopasiTask > & TaskList = * pDataModel->getTaskList();

      TaskList.remove("Time-Course");
      TaskList.add(pTrajectoryTask, true);

      // create a scan task

      pScanTask = new CScanTask(pDataModel);
      CScanProblem* pScanProblem = dynamic_cast<CScanProblem*>(pScanTask->getProblem());
      pScanProblem->setModel(pDataModel->getModel());

      pScanTask->setScheduled(true);

      pScanTask->getReport().setReportDefinition(pReport);
      pScanTask->getReport().setTarget(CWD + "/" + pOutputFilename);
      pScanTask->getReport().setAppend(false);

      pScanProblem->setSubtask(CCopasiTask::timeCourse);
      pScanProblem->createScanItem(CScanProblem::SCAN_REPEAT, repeats);
      pScanProblem->setOutputInSubtask(true);
      pScanProblem->setContinueFromCurrentState(false);

      TaskList.remove("Scan");
      TaskList.add(pScanTask, true);

      // save the file for control purposes
      std::string saveFilename = pSBMLFilename;
      saveFilename = saveFilename.substr(0, saveFilename.length() - 4) + ".cps";
      pDataModel->saveModel(saveFilename, NULL, true);

      // Run the trajectory task

      pScanTask->initialize(CCopasiTask::OUTPUT_SE, pDataModel, NULL);
      pScanTask->process(true);
      pScanTask->restore();

      // create another report that will write to the directory where the input file came from
      // this can be used for debugging
      // create a trajectory task
      // pScanTask->getReport().setTarget(pOutputFilename);

      // pScanTask->initialize(CCopasiTask::OUTPUT_SE, pDataModel, NULL);
      // pScanTask->process(true);
      // pScanTask->restore();
    }
  catch (CCopasiException Exception)
    {
      std::cerr << Exception.getMessage().getText() << std::endl;
    }

  CCopasiRootContainer::destroy();

  return 0;
}