static SBMLDocument *createEmptyDocument()
{
    SBMLDocument *doc = new SBMLDocument();
    doc->createModel("");
    return doc;
}
int main(int argc,char** argv) 
{
  int retval = 0;
  SBMLNamespaces sbmlns(3,1,"comp",1);

  // create the document
  SBMLDocument *document = new SBMLDocument(&sbmlns);

  //Create our submodel
  CompSBMLDocumentPlugin* compdoc
      = static_cast<CompSBMLDocumentPlugin*>(document->getPlugin("comp"));
  compdoc->setRequired(true);
  ModelDefinition* mod1 = compdoc->createModelDefinition();
  mod1->setId("enzyme");
  mod1->setName("enzyme");
  Compartment* comp=mod1->createCompartment();
  comp->setSpatialDimensions((unsigned int)3);
  comp->setConstant(true);
  comp->setId("comp");
  comp->setSize(1L);
  Species spec(&sbmlns);
  spec.setCompartment("comp");
  spec.setHasOnlySubstanceUnits(false);
  spec.setConstant(false);
  spec.setBoundaryCondition(false);
  spec.setId("S");
  mod1->addSpecies(&spec);
  spec.setId("E");
  mod1->addSpecies(&spec);
  spec.setId("D");
  mod1->addSpecies(&spec);
  spec.setId("ES");
  mod1->addSpecies(&spec);
  Reaction rxn(&sbmlns);
  rxn.setReversible(true);
  rxn.setFast(false);
  Reaction rxn2(rxn);
  rxn.setId("J0");
  rxn2.setId("J1");
  SpeciesReference sr(&sbmlns);
  sr.setConstant(true);
  sr.setStoichiometry(1);
  sr.setSpecies("S");
  rxn.addReactant(&sr);
  sr.setSpecies("E");
  rxn.addReactant(&sr);
  rxn2.addProduct(&sr);
  sr.setSpecies("ES");
  rxn.addProduct(&sr);
  rxn2.addReactant(&sr);
  sr.setSpecies("D");
  rxn2.addProduct(&sr);

  mod1->addReaction(&rxn);
  mod1->addReaction(&rxn2);

  // create the Model
  Model* model=document->createModel();
  model->setId("aggregate");
  
  // Create a submodel
  CompModelPlugin* mplugin = static_cast<CompModelPlugin*>(model->getPlugin("comp"));
  Submodel* submod1 = mplugin->createSubmodel();
  submod1->setId("submod1");
  submod1->setModelRef("enzyme");

  Submodel submod2;
  submod2.setId("submod2");
  submod2.setModelRef("enzyme");
  mplugin->addSubmodel(&submod2);

  writeSBMLToFile(document,"eg-simple-aggregate.xml");
  writeSBMLToFile(document,"enzyme_model.xml");
  delete document;
  document = readSBMLFromFile("enzyme_model.xml");
  if (document == NULL)
  {
    cout << "Error reading back in file." << endl;
    retval = -1;
  }
  else
  {
    document->setConsistencyChecks(LIBSBML_CAT_UNITS_CONSISTENCY, false);
    document->checkConsistency();
    if (document->getErrorLog()->getNumFailsWithSeverity(2) > 0
        || document->getErrorLog()->getNumFailsWithSeverity(3) > 0)
    {
      stringstream errorstream;
      document->printErrors(errorstream);
      cout << "Errors encoutered when round-tripping  SBML file: \n"
           <<  errorstream.str() << endl;
      retval = -1;
    }
    writeSBMLToFile(document, "enzyme_model_rt.xml");
    delete document;
  }
#ifdef WIN32
  if (retval != 0)
  {
    cout << "(Press any key to exit.)" << endl;
    _getch();
  }
#endif
  return retval;
}
int
main (int argc, char* argv[])
{
  if (argc != 2)
  {
    cout << endl << "Usage: printNotes filename" << endl << endl;
    return 1;
  }

  unsigned int i,j;
  const char* filename   = argv[1];
  SBMLDocument* document;
  SBMLReader reader;

  document = reader.readSBML(filename);

  unsigned int errors = document->getNumErrors();

  cout << endl;
  cout << "filename: " << filename << endl;
  cout << endl;

  if(errors > 0)
  {
    document->printErrors(cerr);
    delete document;

    return errors;
  }

  /* Model */

  Model* m = document->getModel();
  printNotes(m);

  for(i=0; i < m->getNumReactions(); i++)
  {
    Reaction* re = m->getReaction(i);
    printNotes(re);

    /* SpeciesReference (Reacatant) */

    for(j=0; j < re->getNumReactants(); j++)
    {
      SpeciesReference* rt = re->getReactant(j);
      if (rt->isSetNotes()) cout << "   ";
      printNotes(rt, (rt->isSetSpecies() ? rt->getSpecies() : std::string("")) );
    }

    /* SpeciesReference (Product) */

    for(j=0; j < re->getNumProducts(); j++)
    {
      SpeciesReference* rt = re->getProduct(j);
      if (rt->isSetNotes()) cout << "   ";
      printNotes(rt, (rt->isSetSpecies() ? rt->getSpecies() : std::string("")) );
    }

    /* ModifierSpeciesReference (Modifier) */

    for(j=0; j < re->getNumModifiers(); j++)
    {
      ModifierSpeciesReference* md = re->getModifier(j);
      if (md->isSetNotes()) cout << "   ";
      printNotes(md, (md->isSetSpecies() ? md->getSpecies() : std::string("")) );
    }

    /* Kineticlaw */

    if(re->isSetKineticLaw())
    {
      KineticLaw* kl = re->getKineticLaw();
      if (kl->isSetNotes()) cout << "   ";
      printNotes(kl);

      /* Parameter */

      for(j=0; j < kl->getNumParameters(); j++)
      {
        Parameter* pa = kl->getParameter(j);
        if (pa->isSetNotes()) cout << "      ";
        printNotes(pa);
      }
    }

  }

  /* Species */

  for(i=0; i < m->getNumSpecies(); i++)
  {
    Species* sp = m->getSpecies(i);
    printNotes(sp);
  }

  /* Compartment */

  for(i=0; i < m->getNumCompartments(); i++)
  {
    Compartment* sp = m->getCompartment(i);
    printNotes(sp);
  }

  /* FunctionDefinition */

  for(i=0; i < m->getNumFunctionDefinitions(); i++)
  {
    FunctionDefinition* sp = m->getFunctionDefinition(i);
    printNotes(sp);
  }

  /* UnitDefinition */

  for(i=0; i < m->getNumUnitDefinitions(); i++)
  {
    UnitDefinition* sp = m->getUnitDefinition(i);
    printNotes(sp);
  }

  /* Parameter */

  for(i=0; i < m->getNumParameters(); i++)
  {
    Parameter* sp = m->getParameter(i);
    printNotes(sp);
  }

  /* Rule */

  for(i=0; i < m->getNumRules(); i++)
  {
    Rule* sp = m->getRule(i);
    printNotes(sp);
  }

  /* InitialAssignment */

  for(i=0; i < m->getNumInitialAssignments(); i++)
  {
    InitialAssignment* sp = m->getInitialAssignment(i);
    printNotes(sp);
  }

  /* Event */

  for(i=0; i < m->getNumEvents(); i++)
  {
    Event* sp = m->getEvent(i);
    printNotes(sp);

    /* Trigger */

    if(sp->isSetTrigger())
    {
      const Trigger* tg = sp->getTrigger();
      if (tg->isSetNotes()) cout << "   ";
      printNotes(const_cast<Trigger*>(tg));
    }

    /* Delay */

    if(sp->isSetDelay())
    {
      const Delay* dl = sp->getDelay();
      if (dl->isSetNotes()) cout << "   ";
      printNotes(const_cast<Delay*>(dl));
    }

    /* EventAssignment */

    for(j=0; j < sp->getNumEventAssignments(); j++)
    {
      EventAssignment* ea = sp->getEventAssignment(j);
      if (ea->isSetNotes()) cout << "   ";
      printNotes(ea);
    }
  }

  /* SpeciesType */

  for(i=0; i < m->getNumSpeciesTypes(); i++)
  {
    SpeciesType* sp = m->getSpeciesType(i);
    printNotes(sp);
  }

  /* Constraint */

  for(i=0; i < m->getNumConstraints(); i++)
  {
    Constraint* sp = m->getConstraint(i);
    printNotes(sp);
  }

  delete document;
  return errors;
}
int main(int argc,char** argv)
{
  int retval = 0;
  SBMLNamespaces sbmlns(3,1,"comp",1);

  // create the document
  SBMLDocument *document = new SBMLDocument(&sbmlns);

  //Define the external model definition
  CompSBMLDocumentPlugin* compdoc
      = static_cast<CompSBMLDocumentPlugin*>(document->getPlugin("comp"));
  compdoc->setRequired(true);
  ExternalModelDefinition* extmod = compdoc->createExternalModelDefinition();
  extmod->setId("ExtMod1");
  extmod->setSource("enzyme_model.xml");
  extmod->setModelRef("enzyme");

  //Define the 'simple' model
  ModelDefinition* mod1 = compdoc->createModelDefinition();
  mod1->setId("simple");
  Compartment* comp=mod1->createCompartment();
  comp->setSpatialDimensions((unsigned int)3);
  comp->setConstant(true);
  comp->setId("comp");
  comp->setSize(1L);

  // We have to construct it this way because we get the comp
  // plugin from it later.
  Species spec(&sbmlns);
  spec.setCompartment("comp");
  spec.setHasOnlySubstanceUnits(false);
  spec.setConstant(false);
  spec.setBoundaryCondition(false);
  spec.setId("S");
  spec.setInitialConcentration(5);
  mod1->addSpecies(&spec);
  spec.setId("D");
  spec.setInitialConcentration(10);
  mod1->addSpecies(&spec);

  Reaction rxn(&sbmlns);
  rxn.setReversible(true);
  rxn.setFast(false);
  rxn.setId("J0");

  SpeciesReference sr(&sbmlns);
  sr.setConstant(true);
  sr.setStoichiometry(1);
  sr.setSpecies("S");
  rxn.addReactant(&sr);
  sr.setSpecies("D");
  rxn.addProduct(&sr);

  mod1->addReaction(&rxn);

  CompModelPlugin* mod1plug
      = static_cast<CompModelPlugin*>(mod1->getPlugin("comp"));
  Port port;
  port.setId("S_port");
  port.setIdRef("S");
  mod1plug->addPort(&port);

  Port* port2 = mod1plug->createPort();
  port2->setId("D_port");
  port2->setIdRef("D");

  port.setId("comp_port");
  port.setIdRef("comp");
  mod1plug->addPort(&port);

  port.setId("J0_port");
  port.setIdRef("J0");
  mod1plug->addPort(&port);

  // create the Model
  Model* model=document->createModel();
  model->setId("complexified");
  
  // Set the submodels
  CompModelPlugin* mplugin
      = static_cast<CompModelPlugin*>(model->getPlugin("comp"));
  Submodel* submod1 = mplugin->createSubmodel();
  submod1->setId("A");
  submod1->setModelRef("ExtMod1");
  Submodel* submod2 = mplugin->createSubmodel();
  submod2->setId("B");
  submod2->setModelRef("simple");
  Deletion* del = submod2->createDeletion();
  del->setPortRef("J0_port");

  // Synchronize the compartments
  Compartment* mcomp=model->createCompartment();
  mcomp->setSpatialDimensions((unsigned int)3);
  mcomp->setConstant(true);
  mcomp->setId("comp");
  mcomp->setSize(1L);
  CompSBasePlugin* compartplug
      = static_cast<CompSBasePlugin*>(mcomp->getPlugin("comp"));
  ReplacedElement re;
  re.setIdRef("comp");
  re.setSubmodelRef("A");
  compartplug->addReplacedElement(&re);
  re.setSubmodelRef("B");
  re.unsetIdRef();
  re.setPortRef("comp_port");
  compartplug->addReplacedElement(&re);

  //Synchronize the species
  spec.setId("S");
  spec.unsetInitialConcentration();
  CompSBasePlugin* specplug
      = static_cast<CompSBasePlugin*>(spec.getPlugin("comp"));
  ReplacedElement* sre = specplug->createReplacedElement();
  sre->setSubmodelRef("A");
  sre->setIdRef("S");
  ReplacedBy* srb = specplug->createReplacedBy();
  srb->setSubmodelRef("B");
  srb->setPortRef("S_port");
  model->addSpecies(&spec);

  spec.setId("D");
  sre->setIdRef("D");
  srb->setPortRef("D_port");
  model->addSpecies(&spec);

  writeSBMLToFile(document,"eg-ports.xml");
  writeSBMLToFile(document,"spec_example3.xml");
  delete document;
  document = readSBMLFromFile("spec_example3.xml");
  if (document == NULL)
  {
    cout << "Error reading back in file." << endl;
    retval = -1;
  }
  else
  {
    document->setConsistencyChecks(LIBSBML_CAT_UNITS_CONSISTENCY, false);
    document->checkConsistency();
    if (document->getErrorLog()->getNumFailsWithSeverity(2) > 0
        || document->getErrorLog()->getNumFailsWithSeverity(3) > 0)
    {
      stringstream errorstream;
      document->printErrors(errorstream);
      cout << "Errors encoutered when round-tripping  SBML file: \n"
           <<  errorstream.str() << endl;
      retval = -1;
    }
    writeSBMLToFile(document, "spec_example3_rt.xml");
    delete document;
  }
#ifdef WIN32
  if (retval != 0)
  {
    cout << "(Press any key to exit.)" << endl;
    _getch();
  }
#endif
  return retval;
}
LIBSBML_CPP_NAMESPACE_USE

int main(int argc,char** argv)
{
  SBMLNamespaces sbmlns(3,1,"fbc",1);

  // create the document

  SBMLDocument *document = new SBMLDocument(&sbmlns);
  document->setPackageRequired("fbc", false);

  // create the Model

  Model* model=document->createModel();

  // create the Compartment

  Compartment* compartment = model->createCompartment();
  compartment->setId("compartment");
  compartment->setConstant(true);
  compartment->setSize(1);

  // create the Species

  Species* species = model->createSpecies();
  species->setId("Node1");
  species->setCompartment("compartment");
  species->setBoundaryCondition(false);
  species->setConstant(false);
  species->setHasOnlySubstanceUnits(false);

  species = model->createSpecies();
  species->setId("Node2");
  species->setCompartment("compartment");
  species->setBoundaryCondition(false);
  species->setConstant(false);
  species->setHasOnlySubstanceUnits(false);

  species = model->createSpecies();
  species->setId("Node3");
  species->setCompartment("compartment");
  species->setBoundaryCondition(false);
  species->setConstant(false);
  species->setHasOnlySubstanceUnits(false);

  species = model->createSpecies();
  species->setId("Node4");
  species->setCompartment("compartment");
  species->setBoundaryCondition(false);
  species->setConstant(false);
  species->setHasOnlySubstanceUnits(false);

  species = model->createSpecies();
  species->setId("Node5");
  species->setCompartment("compartment");
  species->setBoundaryCondition(false);
  species->setConstant(false);
  species->setHasOnlySubstanceUnits(false);

  species = model->createSpecies();
  species->setId("Node6");
  species->setCompartment("compartment");
  species->setBoundaryCondition(false);
  species->setConstant(false);
  species->setHasOnlySubstanceUnits(false);

  species = model->createSpecies();
  species->setId("Node7");
  species->setCompartment("compartment");
  species->setBoundaryCondition(false);
  species->setConstant(false);
  species->setHasOnlySubstanceUnits(false);

  species = model->createSpecies();
  species->setId("Node8");
  species->setCompartment("compartment");
  species->setBoundaryCondition(false);
  species->setConstant(false);
  species->setHasOnlySubstanceUnits(false);

  species = model->createSpecies();
  species->setId("Node0");
  species->setCompartment("compartment");
  species->setBoundaryCondition(true);
  species->setConstant(false);
  species->setHasOnlySubstanceUnits(false);

  species = model->createSpecies();
  species->setId("Node9");
  species->setCompartment("compartment");
  species->setBoundaryCondition(true);
  species->setConstant(false);
  species->setHasOnlySubstanceUnits(false);

  Reaction* reaction = model->createReaction();
  reaction->setId("J0");
  reaction->setReversible(false);
  reaction->setFast(false);
  SpeciesReference* reactant = reaction->createReactant();
  reactant->setSpecies("Node0");
  reactant->setStoichiometry(1);
  reactant->setConstant(true);
  SpeciesReference* product = reaction->createProduct();
  product->setSpecies("Node1");
  product->setStoichiometry(1);
  product->setConstant(true);

  reaction = model->createReaction();
  reaction->setId("J1");
  reaction->setReversible(false);
  reaction->setFast(false);
  reactant = reaction->createReactant();
  reactant->setSpecies("Node1");
  reactant->setStoichiometry(1);
  reactant->setConstant(true);
  product = reaction->createProduct();
  product->setSpecies("Node2");
  product->setStoichiometry(1);
  product->setConstant(true);

  reaction = model->createReaction();
  reaction->setId("J2");
  reaction->setReversible(false);
  reaction->setFast(false);
  reactant = reaction->createReactant();
  reactant->setSpecies("Node2");
  reactant->setStoichiometry(1);
  reactant->setConstant(true);
  product = reaction->createProduct();
  product->setSpecies("Node3");
  product->setStoichiometry(1);
  product->setConstant(true);

  reaction = model->createReaction();
  reaction->setId("J3");
  reaction->setReversible(false);
  reaction->setFast(false);
  reactant = reaction->createReactant();
  reactant->setSpecies("Node1");
  reactant->setStoichiometry(1);
  reactant->setConstant(true);
  product = reaction->createProduct();
  product->setSpecies("Node4");
  product->setStoichiometry(1);
  product->setConstant(true);

  reaction = model->createReaction();
  reaction->setId("J4");
  reaction->setReversible(false);
  reaction->setFast(false);
  reactant = reaction->createReactant();
  reactant->setSpecies("Node4");
  reactant->setStoichiometry(1);
  reactant->setConstant(true);
  product = reaction->createProduct();
  product->setSpecies("Node3");
  product->setStoichiometry(1);
  product->setConstant(true);

  reaction = model->createReaction();
  reaction->setId("J5");
  reaction->setReversible(false);
  reaction->setFast(false);
  reactant = reaction->createReactant();
  reactant->setSpecies("Node3");
  reactant->setStoichiometry(1);
  reactant->setConstant(true);
  product = reaction->createProduct();
  product->setSpecies("Node5");
  product->setStoichiometry(1);
  product->setConstant(true);

  reaction = model->createReaction();
  reaction->setId("J6");
  reaction->setReversible(false);
  reaction->setFast(false);
  reactant = reaction->createReactant();
  reactant->setSpecies("Node5");
  reactant->setStoichiometry(1);
  reactant->setConstant(true);
  product = reaction->createProduct();
  product->setSpecies("Node6");
  product->setStoichiometry(1);
  product->setConstant(true);

  reaction = model->createReaction();
  reaction->setId("J7");
  reaction->setReversible(false);
  reaction->setFast(false);
  reactant = reaction->createReactant();
  reactant->setSpecies("Node6");
  reactant->setStoichiometry(1);
  reactant->setConstant(true);
  product = reaction->createProduct();
  product->setSpecies("Node7");
  product->setStoichiometry(1);
  product->setConstant(true);

  reaction = model->createReaction();
  reaction->setId("J8");
  reaction->setReversible(false);
  reaction->setFast(false);
  reactant = reaction->createReactant();
  reactant->setSpecies("Node5");
  reactant->setStoichiometry(1);
  reactant->setConstant(true);
  product = reaction->createProduct();
  product->setSpecies("Node8");
  product->setStoichiometry(1);
  product->setConstant(true);

  reaction = model->createReaction();
  reaction->setId("J9");
  reaction->setReversible(false);
  reaction->setFast(false);
  reactant = reaction->createReactant();
  reactant->setSpecies("Node8");
  reactant->setStoichiometry(1);
  reactant->setConstant(true);
  product = reaction->createProduct();
  product->setSpecies("Node7");
  product->setStoichiometry(1);
  product->setConstant(true);

  reaction = model->createReaction();
  reaction->setId("J10");
  reaction->setReversible(false);
  reaction->setFast(false);
  reactant = reaction->createReactant();
  reactant->setSpecies("Node7");
  reactant->setStoichiometry(1);
  reactant->setConstant(true);
  product = reaction->createProduct();
  product->setSpecies("Node9");
  product->setStoichiometry(1);
  product->setConstant(true);

  //
  // Get a FbcModelPlugin object plugged in the model object.
  //
  // The type of the returned value of SBase::getPlugin() function is
  // SBasePlugin*, and thus the value needs to be casted for the
  // corresponding derived class.
  //
  FbcModelPlugin* mplugin
      = static_cast<FbcModelPlugin*>(model->getPlugin("fbc"));

  FluxBound* bound= mplugin->createFluxBound();

  bound->setId("bound1");
  bound->setReaction("J0");
  bound->setOperation("equal");
  bound->setValue(10);

  Objective* objective = mplugin->createObjective();
  objective->setId("obj1");
  objective->setType("maximize");

  // mark obj1 as active objective
  mplugin->setActiveObjectiveId("obj1");

  FluxObjective* fluxObjective = objective->createFluxObjective();
  fluxObjective->setReaction("J8");
  fluxObjective->setCoefficient(1);

  writeSBML(document,"fbc_example1.xml");
  delete document;
}
END_TEST


START_TEST (test_conversion_inlineFD_bug)
{
  std::string filename = "/inline_bug_minimal.xml";
  filename = TestDataDirectory + filename;
  SBMLDocument* doc = readSBMLFromFile(filename.c_str());

  ConversionProperties props;
  props.addOption("expandFunctionDefinitions", "true");

  fail_unless(doc->getModel() != NULL);
  fail_unless(doc->convert(props) == LIBSBML_OPERATION_SUCCESS);
  fail_unless(doc->getModel()->getNumReactions() == 1);
  fail_unless(doc->getModel()->getReaction(0)->isSetKineticLaw());
  fail_unless(doc->getModel()->getReaction(0)->getKineticLaw()->getMath() != NULL);

  // all seems good ... write it 
  const ASTNode * node = doc->getModel()->getReaction(0)->getKineticLaw()->getMath();
#ifndef LIBSBML_USE_LEGACY_MATH
  fail_unless(node->ASTBase::isChild() == false);
#endif
  std::string math = writeMathMLToString(node);
  ASTNode* test = readMathMLFromString(math.c_str());
  fail_unless(test != NULL);

  // additional test where the node being converted is the top-level
  fail_unless(doc->getModel()->getNumRules() == 1);
  fail_unless(doc->getModel()->getRule(0)->isSetMath());
  fail_unless(doc->getModel()->getRule(0)->getMath() != NULL);

  node = doc->getModel()->getRule(0)->getMath();
#ifndef LIBSBML_USE_LEGACY_MATH
  fail_unless(node->ASTBase::isChild() == false);
#endif
  math = writeMathMLToString(node);
  test = readMathMLFromString(math.c_str());
  fail_unless(test != NULL);

  delete test;
  delete doc;
}
Example #7
0
/**
 * This method tries to import CellDesigner annotations.
 */
void DataModelGUI::importCellDesigner()
{
  // add code to check for CellDesigner annotations
  // ask the user if the annotations should be imported
  CCopasiDataModel* pDataModel = (*CCopasiRootContainer::getDatamodelList())[0];
  assert(pDataModel != NULL);

  if (pDataModel != NULL)
    {
      SBMLDocument* pSBMLDocument = pDataModel->getCurrentSBMLDocument();

      if (pSBMLDocument != NULL &&
          pSBMLDocument->getModel() != NULL &&
          pSBMLDocument->getModel()->getAnnotation() != NULL)
        {
          // check for the CellDesigner namespace
          std::pair<bool, std::string> foundNamespace = CCellDesignerImporter::findCellDesignerNamespace(pSBMLDocument);

          if (foundNamespace.first == true)
            {
              const XMLNode* pAnno = CCellDesignerImporter::findCellDesignerAnnotation(pSBMLDocument, pSBMLDocument->getModel()->getAnnotation());

              // first we check if there are supported cell designer annotations
              if (pAnno != NULL)
                {
                  // check if the file contains the correct version
                  double version = CCellDesignerImporter::determineVersion(pAnno);

                  if (version < 4.0)
                    {
                      CCopasiMessage(CCopasiMessage::RAW, "CellDesigner annotation was found in the file, but the version is not supported.\nPlease open the file in the latest version of CellDesigner and save it again.");
                    }
                  else
                    {
                      bool importCD = false;
#if LIBSBML_VERSION >= 50400
                      // if we don't have a layout import it!
                      LayoutModelPlugin* mplugin = (LayoutModelPlugin*)pSBMLDocument->getModel()->getPlugin("layout");

                      if (mplugin == NULL || (mplugin != NULL && mplugin->getNumLayouts() == 0))
                        importCD = true;

#endif

                      // ask the user if the CellDesigner annotation should be imported
                      if (importCD || CQMessageBox::question(NULL, "CellDesigner import", "A CellDesigner diagram was found in this file.\nDo you want to import the diagram?" , QMessageBox::Yes | QMessageBox::No , QMessageBox::No) == QMessageBox::Yes)
                        {
                          // do the import
                          CCellDesignerImporter cd_importer(pSBMLDocument);

                          if (cd_importer.getLayout() == NULL)
                            {
                              CCopasiMessage(CCopasiMessage::WARNING, "Sorry, CellDesigner annotations could not be importet.");
                            }
                          else
                            {
                              // now we have to import the created layout
                              // create the model map
                              std::string s1, s2;
                              std::map<std::string, std::string> modelmap;
                              std::map<CCopasiObject*, SBase*>::const_iterator it;
                              std::map<CCopasiObject*, SBase*>::const_iterator itEnd = pDataModel->getCopasi2SBMLMap().end();

                              for (it = pDataModel->getCopasi2SBMLMap().begin(); it != itEnd; ++it)
                                {
                                  s1 = SBMLUtils::getIdFromSBase(it->second);

                                  if (it->first)
                                    {
                                      s2 = it->first->getKey();
                                    }
                                  else
                                    {
                                      s2 = "";
                                    }

                                  if ((s1 != "") && (s2 != ""))
                                    {
                                      modelmap[s1] = s2;
                                    }
                                }

                              // the layout map and the id to key map can be empty
                              std::map<std::string, std::string> layoutmap;
                              std::map<std::string, std::string> idToKeyMap;
#ifdef USE_CRENDER_EXTENSION
                              CLayout* pLayout = SBMLDocumentLoader::createLayout(*cd_importer.getLayout(), modelmap, layoutmap, idToKeyMap);
#else
                              CLayout* pLayout = SBMLDocumentLoader::createLayout(*cd_importer.getLayout(), modelmap, layoutmap);
#endif /* USE_CRENDER_EXTENSION */

                              // add the layout to the DataModel
                              if (pLayout != NULL && pDataModel->getListOfLayouts() != NULL)
                                {
                                  // the addLayout methods expects a map as the second argument which currently is
                                  // ignored, so we just pass an empty one
                                  // TODO maybe the methods actually expects one of the maps above (layoutmap or idToKeyMap), but
                                  // TODO this is not documented in CListOfLayouts
                                  std::map<std::string, std::string> tmp;
                                  pDataModel->getListOfLayouts()->addLayout(pLayout, tmp);
                                }
                              else
                                {
                                  CCopasiMessage(CCopasiMessage::WARNING, "Sorry, Layout from CellDesigner annotations could not be created.");
                                }
                            }
                        }
                    }
                }
              else
                {
                  CCopasiMessage(CCopasiMessage::RAW, "CellDesigner annotation was found in the file, but the version is not supported.\nPlease open the file in the latest version of CellDesigner and save it again.");
                }
            }
        }
    }
}
END_TEST


START_TEST (test_QualExtension_read_L3V1V1_defaultNS)
{
  string filename = string(TestDataDirectory) + "qual-example1-defaultNS.xml";
  SBMLDocument *document = readSBMLFromFile(filename.c_str());
  
  fail_unless(document->getPackageName() == "core");

  Model *model = document->getModel();

  fail_unless(model != NULL);
  fail_unless(model->getPackageName() == "core");

  // get the Qualitative species

  QualModelPlugin* mplugin = static_cast<QualModelPlugin*>(model->getPlugin("qual"));
  fail_unless(mplugin != NULL);

  fail_unless(mplugin->getNumQualitativeSpecies() == 1);
  fail_unless(mplugin->getListOfQualitativeSpecies()->getPackageName() == "qual");

  fail_unless(mplugin->getNumTransitions() == 1);
  fail_unless(mplugin->getListOfTransitions()->getPackageName() == "qual");

  QualitativeSpecies* qs = mplugin->getQualitativeSpecies(0);
  fail_unless(qs->getPackageName() == "qual");
  fail_unless(qs->getId() == "s1");
  fail_unless(qs->getName() == "sss");
  fail_unless(qs->getMetaId() == "_ddd");
  fail_unless(qs->getCompartment() == "c");
  fail_unless(qs->getConstant() == false);
  fail_unless(qs->getInitialLevel() == 1);
  fail_unless(qs->getMaxLevel() == 4);

  Transition* t = mplugin->getTransition(0);

  
  fail_unless(t->getPackageName() == "qual");
  fail_unless(t->getId() == "d");
  fail_unless(t->getNumInputs() == 1);
  fail_unless(t->getNumOutputs() == 1);
  fail_unless(t->getNumFunctionTerms() == 1);
  fail_unless(t->isSetDefaultTerm() == true);

  Input *i = t->getInput(0);
  
  fail_unless(i->getPackageName() == "qual");
  fail_unless(i->getId() == "RD");
  fail_unless(i->getName() == "aa" );
  fail_unless(i->getQualitativeSpecies() == "s1");
  fail_unless(i->getTransitionEffect() == INPUT_TRANSITION_EFFECT_NONE );
  fail_unless(i->getSign() == INPUT_SIGN_NEGATIVE);
  fail_unless(i->getThresholdLevel() == 2);

  Output *o = t->getOutput(0);
  
  fail_unless(o->getPackageName() == "qual");
  fail_unless(o->getId() == "wd");
  fail_unless(o->getName() == "asa" );
  fail_unless(o->getQualitativeSpecies() == "s1");
  fail_unless(o->getTransitionEffect() == OUTPUT_TRANSITION_EFFECT_PRODUCTION );
  fail_unless(o->getOutputLevel() == 2);

  FunctionTerm* ft1 = t->getFunctionTerm(0);

  fail_unless(ft1->getPackageName() == "qual");
  fail_unless(ft1->getResultLevel() == 1);
  fail_unless(ft1->getMath() != NULL);

  DefaultTerm* dt = t->getDefaultTerm();

  fail_unless(dt->getPackageName() == "qual");
  fail_unless(dt->getResultLevel() == 2);


  delete document;  
}
Example #9
0
LIBSBML_CPP_NAMESPACE_USE

int main(int argc, char** argv)
{
    //
    // Creates an SBMLNamespaces object with the given SBML level, version
    // package name.
    //

    SBMLNamespaces sbmlns(2, 3);
    sbmlns.addNamespace(LayoutExtension::getXmlnsL2(), "layout");

    // (NOTES) The above code creating an SBMLNamespaces object can be replaced
    //         with the following other style.
    //
    // (2) Creates a LayoutPkgNamespaces object (SBMLNamespace derived class
    //     for layout package. The class is basically used for createing an
    //     SBase derived objects belonging to the layout package) with the
    //     given SBML level, version.  (Package version is not required by
    //     Layout extension of SBML Level 2)
    //
    //        LayoutPkgNamespaces sbmlns(2, 3);
    //

    // create the document

    SBMLDocument *document = new SBMLDocument(&sbmlns);
    // create the Model

    Model* model = document->createModel();
    model->setId("TestModel_with_modifiers");
    document->setModel(model);

    // create the Layout

    LayoutPkgNamespaces layoutns(2, 3);

    LayoutModelPlugin* mplugin
        = static_cast<LayoutModelPlugin*>(model->getPlugin("layout"));
    Layout* layout = mplugin->createLayout();

    layout->setId("Layout_1");
    Dimensions dim(&layoutns, 400.0, 230.0);
    layout->setDimensions(&dim);


    // create the Compartment

    Compartment* compartment = model->createCompartment();
    compartment->setId("Yeast");

    // create the CompartmentGlyph

    CompartmentGlyph* compartmentGlyph = layout->createCompartmentGlyph();
    compartmentGlyph->setId("CompartmentGlyph_1");
    compartmentGlyph->setCompartmentId(compartment->getId());
    BoundingBox bb(&layoutns, "bb1", 5, 5, 390, 220);
    compartmentGlyph->setBoundingBox(&bb);

    // create the Species, SpeciesGlyphs and associated TextGlyphs

    // Glucose

    Species* species_Gluc = model->createSpecies();
    species_Gluc->setId("Glucose");
    species_Gluc->setCompartment(compartment->getId());

    SpeciesGlyph* glyph_Gluc = layout->createSpeciesGlyph();
    glyph_Gluc->setId("SpeciesGlyph_Glucose");
    glyph_Gluc->setSpeciesId(species_Gluc->getId());
    bb = BoundingBox(&layoutns, "bb2", 105, 20, 130, 20);
    glyph_Gluc->setBoundingBox(&bb);

    TextGlyph* tGlyph = layout->createTextGlyph();
    tGlyph->setId("TextGlyph_Glucose");
    bb = BoundingBox(&layoutns, "bbA", 115, 20, 110, 20);
    tGlyph->setBoundingBox(&bb);
    tGlyph->setOriginOfTextId(species_Gluc->getId());
    tGlyph->setGraphicalObjectId(glyph_Gluc->getId());

    // Glucose-6-phosphate

    Species* species_G6P = model->createSpecies();
    species_G6P->setId("Glucose_hyphen_6_hyphen_phosphate");
    species_G6P->setCompartment(compartment->getId());

    SpeciesGlyph* glyph_G6P = layout->createSpeciesGlyph();
    glyph_G6P->setId("SpeciesGlyph_G6P");
    glyph_G6P->setSpeciesId(species_G6P->getId());
    bb = BoundingBox(&layoutns, "bb5", 50, 190, 270, 20);
    glyph_G6P->setBoundingBox(&bb);

    tGlyph = layout->createTextGlyph();
    tGlyph->setId("TextGlyph_G6P");
    bb = BoundingBox(&layoutns, "bbD", 60, 190, 250, 20);
    tGlyph->setBoundingBox(&bb);
    tGlyph->setOriginOfTextId(species_G6P->getId());
    tGlyph->setGraphicalObjectId(glyph_G6P->getId());

    // ATP

    Species* species_ATP = model->createSpecies();
    species_ATP->setId("ATP");
    species_ATP->setCompartment(compartment->getId());

    SpeciesGlyph* glyph_ATP = layout->createSpeciesGlyph();
    glyph_ATP->setId("SpeciesGlyph_ATP");
    glyph_ATP->setSpeciesId(species_ATP->getId());
    bb = BoundingBox(&layoutns, "bb3", 270, 70, 80, 20);
    glyph_ATP->setBoundingBox(&bb);

    tGlyph = layout->createTextGlyph();
    tGlyph->setId("TextGlyph_ATP");
    bb = BoundingBox(&layoutns, "bbB", 280, 70, 60, 20);
    tGlyph->setBoundingBox(&bb);
    tGlyph->setOriginOfTextId(species_ATP->getId());
    tGlyph->setGraphicalObjectId(glyph_ATP->getId());

    // ADP

    Species* species_ADP = model->createSpecies();
    species_ADP->setId("ADP");
    species_ADP->setCompartment(compartment->getId());

    SpeciesGlyph* glyph_ADP = layout->createSpeciesGlyph();
    glyph_ADP->setId("glyph_ADP");
    glyph_ADP->setSpeciesId(species_ADP->getId());
    bb = BoundingBox(&layoutns, "bb4", 270, 140, 80, 20);
    glyph_ADP->setBoundingBox(&bb);

    tGlyph = layout->createTextGlyph();
    tGlyph->setId("TextGlyph_ADP");
    bb = BoundingBox(&layoutns, "bbC", 280, 140, 60, 20);
    tGlyph->setBoundingBox(&bb);
    tGlyph->setOriginOfTextId(species_ADP->getId());
    tGlyph->setGraphicalObjectId(glyph_ADP->getId());

    // Phosphate

    Species* species_Pi = model->createSpecies();
    species_Pi->setId("Pi");
    species_Pi->setCompartment(compartment->getId());

    SpeciesGlyph* glyph_Pi = layout->createSpeciesGlyph();
    glyph_Pi->setId("SpeciesGlyph_Pi");
    glyph_Pi->setSpeciesId(species_Pi->getId());
    bb = BoundingBox(&layoutns, "bb6", 50, 100, 60, 20);
    glyph_Pi->setBoundingBox(&bb);

    tGlyph = layout->createTextGlyph();
    tGlyph->setId("TextGlyph_PI");
    bb = BoundingBox(&layoutns, "bbE", 60, 100, 40, 20);
    tGlyph->setBoundingBox(&bb);
    tGlyph->setOriginOfTextId(species_Pi->getId());
    tGlyph->setGraphicalObjectId(glyph_Pi->getId());

    // create the Reaction

    Reaction* reaction_Hexokinase = model->createReaction();
    reaction_Hexokinase->setId("Hexokinase");
    reaction_Hexokinase->setReversible(false);

    ReactionGlyph* glyph_Hexokinase = layout->createReactionGlyph();
    glyph_Hexokinase->setId("glyph_Hexokinase");
    glyph_Hexokinase->setReactionId(reaction_Hexokinase->getId());

    Curve* curve_Hexokinase = glyph_Hexokinase->getCurve();
    LineSegment* ls = curve_Hexokinase->createLineSegment();
    Point p(&layoutns, 170, 100);
    ls->setStart(&p);
    p = Point(&layoutns, 170, 130);
    ls->setEnd(&p);

    // create the species reference for glucose

    SpeciesReference* reference_Gluc = reaction_Hexokinase->createReactant();
    reference_Gluc->setSpecies(species_Gluc->getId());
    reference_Gluc->setId("SpeciesReference_Glucose");

    // create species reference glyph for glucose

    SpeciesReferenceGlyph* speciesReferenceGlyph
        = glyph_Hexokinase->createSpeciesReferenceGlyph();
    speciesReferenceGlyph->setId("SpeciesReferenceGlyph_Glucose");
    speciesReferenceGlyph->setSpeciesGlyphId(glyph_Gluc->getId());
    speciesReferenceGlyph->setSpeciesReferenceId(reference_Gluc->getId());
    speciesReferenceGlyph->setRole(SPECIES_ROLE_SUBSTRATE);

    ls = speciesReferenceGlyph->createLineSegment();
    p = Point(&layoutns, 170, 100);
    ls->setStart(&p);
    p = Point(&layoutns, 170, 50);
    ls->setEnd(&p);

    // create species reference for ATP

    SpeciesReference* reference_ATP
        = reaction_Hexokinase->createReactant();
    reference_ATP->setSpecies(species_ATP->getId());
    reference_ATP->setId("SpeciesReference_ATP");

    // create the species reference glyph for ATP

    speciesReferenceGlyph = glyph_Hexokinase->createSpeciesReferenceGlyph();
    speciesReferenceGlyph->setId("SpeciesReferenceGlyph_ATP");
    speciesReferenceGlyph->setSpeciesGlyphId(glyph_ATP->getId());
    speciesReferenceGlyph->setSpeciesReferenceId(reference_ATP->getId());
    speciesReferenceGlyph->setRole(SPECIES_ROLE_SIDESUBSTRATE);

    CubicBezier* cb = speciesReferenceGlyph->createCubicBezier();
    p = Point(&layoutns, 170, 100);
    cb->setStart(&p);
    p = Point(&layoutns, 170, 80);
    cb->setBasePoint1(&p);
    p = Point(&layoutns, 170, 80);
    cb->setBasePoint2(&p);
    p = Point(&layoutns, 260, 80);
    cb->setEnd(&p);

    // create species reference for G6P

    SpeciesReference* reference_G6P = reaction_Hexokinase->createProduct();
    reference_G6P->setSpecies(species_G6P->getId());
    reference_G6P->setId("SpeciesReference_G6P");

    // create species reference for G6P as product

    speciesReferenceGlyph = glyph_Hexokinase->createSpeciesReferenceGlyph();
    speciesReferenceGlyph->setId("SpeciesReferenceGlyph_G6P_1");
    speciesReferenceGlyph->setSpeciesGlyphId(glyph_G6P->getId());
    speciesReferenceGlyph->setSpeciesReferenceId(reference_G6P->getId());
    speciesReferenceGlyph->setRole(SPECIES_ROLE_PRODUCT);

    ls = speciesReferenceGlyph->createLineSegment();
    p = Point(&layoutns, 170, 130);
    ls->setStart(&p);
    p = Point(&layoutns, 170, 180);
    ls->setEnd(&p);

    // create species reference for ADP

    SpeciesReference* reference_ADP = reaction_Hexokinase->createProduct();
    reference_ADP->setSpecies(species_ADP->getId());
    reference_ADP->setId("SpeciesReference_ADP");

    // create the species reference glyph for ADP

    speciesReferenceGlyph = glyph_Hexokinase->createSpeciesReferenceGlyph();
    speciesReferenceGlyph->setId("SpeciesReferenceGlyph_ADP");
    speciesReferenceGlyph->setSpeciesGlyphId(glyph_ADP->getId());
    speciesReferenceGlyph->setSpeciesReferenceId(reference_ADP->getId());
    speciesReferenceGlyph->setRole(SPECIES_ROLE_SIDEPRODUCT);

    cb = speciesReferenceGlyph->createCubicBezier();
    p = Point(&layoutns, 170, 130);
    cb->setStart(&p);
    p = Point(&layoutns, 170, 150);
    cb->setBasePoint1(&p);
    p = Point(&layoutns, 170, 150);
    cb->setBasePoint2(&p);
    p = Point(&layoutns, 260, 150);
    cb->setEnd(&p);

    // create modifier species reference for glucose-6-phosphate

    ModifierSpeciesReference* reference_G6P_2
        = reaction_Hexokinase->createModifier();
    reference_G6P_2->setSpecies(species_G6P->getId());
    reference_G6P_2->setId("ModifierSpeciesReference_G6P");

    reaction_Hexokinase->addModifier(reference_G6P_2);

    // create species reference glyph for G6P as a modifier

    speciesReferenceGlyph = glyph_Hexokinase->createSpeciesReferenceGlyph();
    speciesReferenceGlyph->setId("SpeciesReferenceGlyph_G6P_2");
    speciesReferenceGlyph->setSpeciesReferenceId(reference_G6P_2->getId());
    speciesReferenceGlyph->setSpeciesGlyphId(glyph_G6P->getId());
    speciesReferenceGlyph->setRole(SPECIES_ROLE_INHIBITOR);

    cb = speciesReferenceGlyph->createCubicBezier();
    p = Point(&layoutns, 45, 200);
    cb->setStart(&p);
    p = Point(&layoutns, 0, 200);
    cb->setBasePoint1(&p);
    p = Point(&layoutns, 0, 120);
    cb->setBasePoint2(&p);
    p = Point(&layoutns, 165, 120);
    cb->setEnd(&p);

    // create modifier species reference for phosphate

    ModifierSpeciesReference* reference_Pi = reaction_Hexokinase->createModifier();
    reference_Pi->setSpecies(species_Pi->getId());
    reference_Pi->setId("ModifierSpeciesReference_Pi");

    reaction_Hexokinase->addModifier(reference_Pi);

    // create the species reference glyph for Phosphate

    speciesReferenceGlyph = glyph_Hexokinase->createSpeciesReferenceGlyph();
    speciesReferenceGlyph->setId("SpeciesReferenceGlyph_PI");
    speciesReferenceGlyph->setSpeciesReferenceId(reference_Pi->getId());
    speciesReferenceGlyph->setSpeciesGlyphId(glyph_Pi->getId());
    speciesReferenceGlyph->setRole(SPECIES_ROLE_ACTIVATOR);

    cb = speciesReferenceGlyph->createCubicBezier();
    p = Point(&layoutns, 115, 110);
    cb->setStart(&p);
    p = Point(&layoutns, 140, 110);
    cb->setBasePoint1(&p);
    p = Point(&layoutns, 140, 110);
    cb->setBasePoint2(&p);
    p = Point(&layoutns, 165, 110);
    cb->setEnd(&p);

    // write model to file

    writeSBML(document, "layout_example3_L2.xml");
    delete document;

}
Example #10
0
/** @cond doxygenLibsbmlInternal */
int 
Replacing::updateIDs(SBase* oldnames, SBase* newnames)
{
  int ret = LIBSBML_OPERATION_SUCCESS;
  SBMLDocument* doc = getSBMLDocument();
  if (oldnames->isSetId() && !newnames->isSetId()) {
    if (doc) {
      string error = "Unable to transform IDs in Replacing::updateIDs during replacement:  the '" + oldnames->getId() + "' element's replacement does not have an ID set.";
      doc->getErrorLog()->logPackageError("comp", CompMustReplaceIDs, getPackageVersion(), getLevel(), getVersion(), error, getLine(), getColumn());
    }
    return LIBSBML_INVALID_OBJECT;
  }
  if (oldnames->isSetMetaId() && !newnames->isSetMetaId()) {
    if (doc) {
      string error = "Unable to transform IDs in Replacing::updateIDs during replacement:  the replacement of the element with metaid '" + oldnames->getMetaId() + "' does not have a metaid.";
      doc->getErrorLog()->logPackageError("comp", CompMustReplaceMetaIDs, getPackageVersion(), getLevel(), getVersion(), error, getLine(), getColumn());
    }
    return LIBSBML_INVALID_OBJECT;
  }
  //LS DEBUG Somehow we need to check identifiers from other packages here (like spatial id's).  How, exactly, is anyone's guess.
  Model* replacedmod = const_cast<Model*>(CompBase::getParentModel(oldnames));
  KineticLaw* replacedkl;
  ASTNode newkl;
  if (replacedmod==NULL) {
    if (doc) {
      string error = "Unable to transform IDs in Replacing::updateIDs during replacement:  the replacement of '" + oldnames->getId() + "' does not have a valid model.";
      doc->getErrorLog()->logPackageError("comp", CompModelFlatteningFailed, getPackageVersion(), getLevel(), getVersion(), error, getLine(), getColumn());
    }
    return LIBSBML_INVALID_OBJECT;
  }
  List* allElements = replacedmod->getAllElements();
  string oldid = oldnames->getId();
  string newid = newnames->getId();
  if (!oldid.empty()) {
    switch(oldnames->getTypeCode()) {
    case SBML_UNIT_DEFINITION:
      replacedmod->renameUnitSIdRefs(oldid, newid);
      for (unsigned int e=0; e<allElements->getSize(); e++) {
        SBase* element = static_cast<SBase*>(allElements->get(e));
        element->renameUnitSIdRefs(oldid, newid);
      }
      break;
    case SBML_LOCAL_PARAMETER:
      replacedkl = static_cast<KineticLaw*>(oldnames->getAncestorOfType(SBML_KINETIC_LAW));
      if (replacedkl->isSetMath()) {
        newkl = *replacedkl->getMath();
        newkl.renameSIdRefs(oldid, newid);
        replacedkl->setMath(&newkl);
      }
      break;
    case SBML_COMP_PORT:
      break;
      //LS DEBUG And here is where we would need some sort of way to check if the id wasn't an SId for some objects.
    default:
      replacedmod->renameSIdRefs(oldnames->getId(), newnames->getId());
      for (unsigned int e=0; e<allElements->getSize(); e++) {
        SBase* element = static_cast<SBase*>(allElements->get(e));
        element->renameSIdRefs(oldid, newid);
      }
    }
  }
  string oldmetaid = oldnames->getMetaId();
  string newmetaid = newnames->getMetaId();
  if (oldnames->isSetMetaId()) {
    replacedmod->renameMetaIdRefs(oldmetaid, newmetaid);
    for (unsigned int e=0; e<allElements->getSize(); e++) {
      SBase* element = static_cast<SBase*>(allElements->get(e));
      element->renameMetaIdRefs(oldmetaid, newmetaid);
    }
  }
  //LS DEBUG And here is where we would need some sort of way to check for ids that were not 'id' or 'metaid'.
  delete allElements;
  return ret;
}
END_TEST

START_TEST (test_SBMLTransforms_expandFD)
{
  std::string filename(TestDataDirectory);
  filename += "multiple-functions.xml";


  // test 1: skip expansion of 'f'
  SBMLDocument *doc = readSBMLFromFile(filename.c_str());

  ConversionProperties props; 
  props.addOption("expandFunctionDefinitions", true);
  props.addOption("skipIds", "f");

  fail_unless(doc->convert(props) == LIBSBML_OPERATION_SUCCESS);
  fail_unless(doc->getModel() != NULL);
  fail_unless(doc->getModel()->getNumFunctionDefinitions() == 1);
  fail_unless(doc->getModel()->getFunctionDefinition("f") != NULL);
  
  delete doc;

  // test 2: expand all
  doc = readSBMLFromFile(filename.c_str());

  props = ConversionProperties(); 
  props.addOption("expandFunctionDefinitions", true);

  fail_unless(doc->convert(props) == LIBSBML_OPERATION_SUCCESS);
  fail_unless(doc->getModel() != NULL);
  fail_unless(doc->getModel()->getNumFunctionDefinitions() == 0);
  
  delete doc;

  // test 3: don't expand f and g
  doc = readSBMLFromFile(filename.c_str());

  props = ConversionProperties(); 
  props.addOption("expandFunctionDefinitions", true);
  props.addOption("skipIds", "f,g");

  fail_unless(doc->convert(props) == LIBSBML_OPERATION_SUCCESS);
  fail_unless(doc->getModel() != NULL);
  fail_unless(doc->getModel()->getNumFunctionDefinitions() == 2);
  
  delete doc;

  // test 4: even though comma separated is advertized, make sure that ';' works
  doc = readSBMLFromFile(filename.c_str());

  props = ConversionProperties(); 
  props.addOption("expandFunctionDefinitions", true);
  props.addOption("skipIds", "f;g");

  fail_unless(doc->convert(props) == LIBSBML_OPERATION_SUCCESS);
  fail_unless(doc->getModel() != NULL);
  fail_unless(doc->getModel()->getNumFunctionDefinitions() == 2);
  
  delete doc;

  // test 5: or space
  doc = readSBMLFromFile(filename.c_str());

  props = ConversionProperties(); 
  props.addOption("expandFunctionDefinitions", true);
  props.addOption("skipIds", "f g");

  fail_unless(doc->convert(props) == LIBSBML_OPERATION_SUCCESS);
  fail_unless(doc->getModel() != NULL);
  fail_unless(doc->getModel()->getNumFunctionDefinitions() == 2);
  
  delete doc;

  // test 6: or tab
  doc = readSBMLFromFile(filename.c_str());

  props = ConversionProperties(); 
  props.addOption("expandFunctionDefinitions", true);
  props.addOption("skipIds", "f\tg");

  fail_unless(doc->convert(props) == LIBSBML_OPERATION_SUCCESS);
  fail_unless(doc->getModel() != NULL);
  fail_unless(doc->getModel()->getNumFunctionDefinitions() == 2);
  
  delete doc;

  // test 7: or a combination
  doc = readSBMLFromFile(filename.c_str());

  props = ConversionProperties(); 
  props.addOption("expandFunctionDefinitions", true);
  props.addOption("skipIds", "f; g");

  fail_unless(doc->convert(props) == LIBSBML_OPERATION_SUCCESS);
  fail_unless(doc->getModel() != NULL);
  fail_unless(doc->getModel()->getNumFunctionDefinitions() == 2);
  
  delete doc;

}
Example #12
0
int 
Replacing::saveReferencedElement()
{
  SBMLDocument* doc = getSBMLDocument();
  if (!isSetSubmodelRef()) {
    if (doc) {
      string error = "Unable to find referenced element in Replacing::saveReferencedElement: the given <" + getElementName() + "> element";
      if (isSetId()) {
        error += " '" + getId() + "'";
      }
      error += " has no 'submodelRef' attribute.";
      doc->getErrorLog()->logPackageError("comp", CompReplacedElementAllowedAttributes, getPackageVersion(), getLevel(), getVersion(), error, getLine(), getColumn());
    }
    return LIBSBML_INVALID_OBJECT;
  }
  Model* model = getParentModel(this);
  if (model==NULL) {
    if (doc) {
      string error = "Unable to find referenced element in Replacing::saveReferencedElement: no parent model could be found for the given <" + getElementName() + "> element";
      if (isSetId()) {
        error += " '" + getId() + "'.";
      }
      doc->getErrorLog()->logPackageError("comp", CompModelFlatteningFailed, getPackageVersion(), getLevel(), getVersion(), error, getLine(), getColumn());
    }
    return LIBSBML_OPERATION_FAILED;
  }
  CompModelPlugin* cmp = static_cast<CompModelPlugin*>(model->getPlugin(getPrefix()));
  if (cmp==NULL) {
    if (doc) {
      string error = "Unable to find referenced element in Replacing::saveReferencedElement: no 'comp' plugin for the parent model could be found for the given <" + getElementName() + "> element";
      if (isSetId()) {
        error += " '" + getId() + "'.";
      }
      doc->getErrorLog()->logPackageError("comp", CompModelFlatteningFailed, getPackageVersion(), getLevel(), getVersion(), error, getLine(), getColumn());
    }
    return LIBSBML_OPERATION_FAILED;
  }
  Submodel* submod = cmp->getSubmodel(getSubmodelRef());
  if (submod==NULL) {
    if (doc) {
      string error = "Unable to find referenced element for the given <" + getElementName() + "> element";
      if (isSetId()) {
        error += " '" + getId() + "'";
      }
      error += " in Replacing::saveReferencedElement: the submodelRef '" + getSubmodelRef() + "' could not be found in the model.";
      unsigned int errnumber = CompReplacedElementSubModelRef;
      if (getTypeCode() == SBML_COMP_REPLACEDBY) {
        errnumber = CompReplacedBySubModelRef;
      }
      doc->getErrorLog()->logPackageError("comp", errnumber, getPackageVersion(), getLevel(), getVersion(), error, getLine(), getColumn());
    }
    return LIBSBML_INVALID_ATTRIBUTE_VALUE;
  }
  Model* inst = submod->getInstantiation();
  if (inst==NULL) {
    //getInstantiation sets it own error messages.
    return LIBSBML_OPERATION_FAILED;
  }
  mReferencedElement = getReferencedElementFrom(inst);
  if (mDirectReference==NULL) {
    mDirectReference = mReferencedElement;
  }
  //getReferencedElement* set their own error messages:
  if (mReferencedElement==NULL) {
    return LIBSBML_OPERATION_FAILED;
  }
  if (mReferencedElement->getTypeCode()==SBML_COMP_PORT) {
    mReferencedElement = static_cast<Port*>(mReferencedElement)->getReferencedElement();
  }
  if (mReferencedElement==NULL) {
    return LIBSBML_OPERATION_FAILED;
  }
  return LIBSBML_OPERATION_SUCCESS;
}
END_TEST

START_TEST(test_FbcExtension_create_and_write_L3V1V1)
{
  FbcPkgNamespaces *sbmlns = new FbcPkgNamespaces(3, 1, 1);

  // create the document

  SBMLDocument *document = new SBMLDocument(sbmlns);
  delete sbmlns;

  // create the Model

  Model* model = document->createModel();

  // create the Compartment

  Compartment* compartment = model->createCompartment();
  compartment->setId("compartment");
  compartment->setConstant(true);
  compartment->setSize(1);

  // create the Species

  Species* species = model->createSpecies();
  species->setId("Node1");
  species->setCompartment("compartment");
  species->setBoundaryCondition(false);

  species = model->createSpecies();
  species->setId("Node2");
  species->setCompartment("compartment");
  species->setBoundaryCondition(false);

  Reaction* reaction = model->createReaction();
  reaction->setId("J0");
  reaction->setReversible(false);
  SpeciesReference* reactant = reaction->createReactant();
  reactant->setSpecies("Node0");
  reactant->setStoichiometry(1);
  SpeciesReference* product = reaction->createProduct();
  product->setSpecies("Node1");
  product->setStoichiometry(1);

  // use fbc

  FbcModelPlugin* mplugin = static_cast<FbcModelPlugin*>(model->getPlugin("fbc"));

  fail_unless(mplugin != NULL);

  FluxBound* bound = mplugin->createFluxBound();

  bound->setId("bound1");
  bound->setReaction("J0");
  bound->setOperation("equal");
  bound->setValue(10);

  Objective* objective = mplugin->createObjective();
  objective->setId("obj1");
  objective->setType("maximize");

  FluxObjective* fluxObjective = objective->createFluxObjective();
  fluxObjective->setReaction("J0");
  fluxObjective->setCoefficient(1);

  string s1 = writeSBMLToStdString(document);

  // check clone()

  SBMLDocument* document2 = document->clone();
  string s2 = writeSBMLToStdString(document2);
  fail_unless(s1 == s2);

  // check operator=

  Model m = *(document->getModel());
  document2->setModel(&m);
  s2 = writeSBMLToStdString(document2);

  fail_unless(s1 == s2);
  delete document2;

  delete document;
}
LIBSBML_CPP_NAMESPACE_USE

int
main (int argc, char* argv[])
{
  SBMLNamespaces sbmlns(3,1,"multi",1);

  // create the document

  SBMLDocument *document = new SBMLDocument(&sbmlns);

  // set the required attribute to true
  MultiSBMLDocumentPlugin * docPlug = 
    static_cast<MultiSBMLDocumentPlugin*>(document->getPlugin("multi"));
  docPlug->setRequired(true);


  // create the Model

  Model* model=document->createModel();

  // create the compartments

  Compartment * c = model->createCompartment();
  c->setId("membrane");
  c->setConstant(true);

  // set the multi attribute isType via the compartmentPlugin
  MultiCompartmentPlugin * compPlug = 
    static_cast<MultiCompartmentPlugin*>(c->getPlugin("multi"));
  compPlug->setIsType(true);

  // create the speciesTypes

  MultiModelPlugin * modelPlug = 
    static_cast<MultiModelPlugin*>(model->getPlugin("multi"));

  MultiSpeciesType * st = modelPlug->createMultiSpeciesType();
  st->setId("stX");
  st->setCompartment("membrane");

  // create species
  Species *s = model->createSpecies();
  s->setId("s1");
  s->setCompartment("membrane");
  s->setBoundaryCondition(false);
  s->setHasOnlySubstanceUnits(false);
  s->setConstant(false);

  // set the multi attribute speciesType via the compartmentPlugin
  MultiSpeciesPlugin * spPlug = 
    static_cast<MultiSpeciesPlugin*>(s->getPlugin("multi"));
  spPlug->setSpeciesType("stX");

  // create species feature
  SpeciesFeature *sf = spPlug->createSpeciesFeature();
  sf->setSpeciesFeatureType("a");
  sf->setOccur(1);
  sf->setComponent("b");

  SpeciesFeatureValue *sfv = sf->createSpeciesFeatureValue();
  sfv->setValue("c");

  // create a subListOfSpeciesFeatures
  SubListOfSpeciesFeatures* subloSF = spPlug->createSubListOfSpeciesFeatures();
  subloSF->setRelation(Relation_fromString("and"));

  // add speciesFeatures to the subList
  SpeciesFeature *sf1 = new SpeciesFeature(3, 1, 1);
  sf1->setSpeciesFeatureType("a1");
  sf1->setOccur(1);
  sf1->setComponent("b1");

  SpeciesFeatureValue *sfv1 = sf1->createSpeciesFeatureValue();
  sfv1->setValue("c1");

  subloSF->appendAndOwn(sf1);

  sf1 = new SpeciesFeature(3, 1, 1);
  sf1->setSpeciesFeatureType("a2");
  sf1->setOccur(1);
  sf1->setComponent("b2");

  sfv1 = sf1->createSpeciesFeatureValue();
  sfv1->setValue("c2");

  subloSF->appendAndOwn(sf1);

  // create a second subListOfSpeciesfeatures
  subloSF = spPlug->createSubListOfSpeciesFeatures();
  subloSF->setRelation(Relation_fromString("or"));

  sf1 = new SpeciesFeature(3, 1, 1);
  sf1->setSpeciesFeatureType("a3");
  sf1->setOccur(1);
  sf1->setComponent("b3");

  sfv1 = sf1->createSpeciesFeatureValue();
  sfv1->setValue("c3");

  subloSF->appendAndOwn(sf1);

  sf1 = new SpeciesFeature(3, 1, 1);
  sf1->setSpeciesFeatureType("a4");
  sf1->setOccur(1);
  sf1->setComponent("b4");

  sfv1 = sf1->createSpeciesFeatureValue();
  sfv1->setValue("c4");

  subloSF->appendAndOwn(sf1);

  writeSBML(document,"multi_example3.xml");
 
  delete document;

  return 0;
}
LIBSBML_CPP_NAMESPACE_USE

int
main (int argc, char *argv[])
{

  SBMLDocument* d;
  unsigned int  errors, n;
  Reaction *r;

  if (argc != 3)
  {
    cout << endl
         << "  usage: addingEvidenceCodes_1 <input-filename> <output-filename>" << endl
         << "  Adds controlled vocabulary term to a reaction"        << endl
         << endl;
    return 2;
  }


  d      = readSBML(argv[1]);
  errors = d->getNumErrors();

  if (errors > 0)
  {
    cout << "Read Error(s):" << endl;
	  d->printErrors(cout);

    cout << "Correct the above and re-run." << endl;
  }
  else
  {
  
    n = d->getModel()->getNumReactions();
    
    if (n <= 0)
    {
      cout << "Model has no reactions.\n Cannot add CV terms\n";
    }
    else
    {
      r = d->getModel()->getReaction(0);

      /* check that the reaction has a metaid
       * no CVTerms will be added if there is no metaid to reference
       */
      if (!r->isSetMetaId())
        r->setMetaId("metaid_0000052");

      CVTerm * cv1 = new CVTerm(BIOLOGICAL_QUALIFIER);
      cv1->setBiologicalQualifierType(BQB_IS_DESCRIBED_BY);
      cv1->addResource("urn:miriam:obo.eco:ECO%3A0000183");

      r->addCVTerm(cv1);

      CVTerm * cv2 = new CVTerm(BIOLOGICAL_QUALIFIER);
      cv2->setBiologicalQualifierType(BQB_IS);
      cv2->addResource("urn:miriam:kegg.reaction:R00756");
      cv2->addResource("urn:miriam:reactome:REACT_736");

      r->addCVTerm(cv2);

      writeSBML(d, argv[2]);
    }
  }

  delete d;
  return errors;
}
Example #16
0
/** 
 * Load a gene network from an SBML file. Overrides Structure.load(). Format must
 * be equal GeneNetwork.SBML. Note, the SBML file must be in the exact same format
 * as the SBML files produced by writeSBML(). In particular, we assume that reactions are listed
 * *ordered* as we do in writeSBML().
 * @param filename URL to the file describing the network to load
 * @param format File format (GML, DOT, etc.)
 * @throws IOException 
 */
void GeneNetwork::load_sbml(const char *filename) {
	SBMLDocument* document;
  	SBMLReader reader;

  	document = reader.readSBML(filename);

  	unsigned int errors = document->getNumErrors();
	if (errors > 0) {
        std::cerr << "Failed to open file " << filename << std::endl;
        exit(1);
    }

	Model *m = document->getModel();

	// -----------------------------------------
	// Set the network size and create the genes
	// do not count the species _void_
	int size = m->getNumSpecies() - 1;
	ListOfSpecies *species = m->getListOfSpecies();
	
	for (int g=0; g < size; g++) {
		if (species->get(g)->getId() != "_void_") {
			//HillGene hg = new HillGene(this);
			//hg.setLabel(species.get(g).getId());
			HillGene *n = new HillGene(species->get(g)->getId());
			//n.setLabel(species->get(g)->getId());
			nodes_.push_back(*n);
			delete n;
		}
	}
	
	x_ = Vec_DP(nodes_.size());
	x_ = 0;
	y_ = Vec_DP(nodes_.size());
	y_ = 0;
	
	//vector<string> parameterNames; // the names of the parameters
	//vector<double> parameterValues; // the values of the parameters
	std::map<std::string, double> params;
	std::vector<std::string> inputNodes; // the indexes of the inputs
	HillGene src, tgt;
	Parameter *param;
	
	// 2 loops for one gene: both synthesis and degradation reactions
	// (we assume that reactions are listed *ordered* as we do in writeSBML())
	//int counter = 0;
	for (unsigned int i=0; i < m->getNumReactions(); i++) {
		Reaction *re = m->getReaction(i);
		std::string id = re->getId();
		
		std::stringstream ss;
		ss << i;
		//::logging::log::emit<Debug>() << id.c_str() <<
		//		::logging::log::endl;
	
		tgt = nodes_.at(getIndexOfNode(getGeneReactantId(id)));
		//tgt->setLabel(getGeneReactantId(*re));
      	//SpeciesReference *rt = re->getReactant(0);
      	//Node *tgt = new HillGene();
      	//tgt->setLabel(rt->getSpecies());
      	//ListOfSpeciesReferences *modifiers = re->getListOfModifiers();

    	for (unsigned int j=0; j < re->getNumModifiers(); j++) {
      		ModifierSpeciesReference *md = re->getModifier(j);
      		src = nodes_.at(getIndexOfNode(md->getSpecies()));      		
      		inputNodes.push_back(src.getLabel());
      		
            // set output genes
            std::vector<std::string> outputs = src.getOutputGenes();
            outputs.push_back(tgt.getLabel());
            src.setOutputGenes(outputs);
      		
            // The edge type is unknown for now, it is initialized later
      		Edge *e = new Edge(&src, &tgt, "+-");
			edges_.push_back(*e);
			//delete src;
			delete e;
		}

      	KineticLaw *kl = re->getKineticLaw();
      		
      	for(unsigned int j=0; j < kl->getNumParameters(); j++) {
        	param = kl->getParameter(j);
			params[param->getId()] = param->getValue();
			//char buf[256];
      		//sprintf(buf, "%s\t%f", param->getId().c_str(), param->getValue());
			//::logging::log::emit<Info>() << buf <<	::logging::log::endl;
		}
		
		//::logging::log::emit<Info>() << ::logging::log::dec << params.size() <<
		//		::logging::log::endl;
		
		// in the second iteration for this gene
		if (i%2 == 1) {
			// set parameters in gene
			//tgt.initialization(params, inputNodes);
			nodes_.at(getIndexOfNode(getGeneReactantId(id))).initialization(params, inputNodes);;
			//char buf[256];
			//sprintf(buf, "%f", params["k_1"]);
			//::logging::log::emit<Info>() << buf << ::logging::log::endl;
			
			inputNodes.clear(); // don't clear because the reference was copied to the gene
			//parameterNames.clear(); // reset (they were not copied)
			//parameterValues.clear();
			params.clear();
		}
		//counter++;
	}
	//setEdgeTypesAccordingToDynamicalModel();
	//signed_ = true;
	
	//delete document;
	//delete n;
	//delete e;
}
LIBSBML_CPP_NAMESPACE_USE

int
main (int argc, char *argv[])
{
  const unsigned int latestLevel   = SBMLDocument::getDefaultLevel();
  const unsigned int latestVersion = SBMLDocument::getDefaultVersion();


  if (argc != 3)
  {
    cout << "Usage: convertSBML input-filename output-filename" << endl
	 << "This program will attempt to convert a model either to" << endl
	 << "SBML Level " << latestLevel << " Version " << latestVersion
	 << " (if the model is not already) or, if " << endl
	 << "the model is already expressed in Level " << latestLevel
	 << " Version " << latestVersion << ", this" << endl
	 << "program will attempt to convert the model to Level 1 Version 2."
	 << endl;
    return 1;
  }

  const char* inputFile   = argv[1];
  const char* outputFile  = argv[2];

  SBMLDocument* document  = readSBML(inputFile);
  unsigned int  errors    = document->getNumErrors();

  if (errors > 0)
  {
    cerr << "Encountered the following SBML errors:" << endl;
    document->printErrors(cerr);
    cerr << "Conversion skipped.  Please correct the problems above first."
	 << endl;
    return errors;
  }

  /**
   * If the given model is not already L2v4, assume that the user wants to
   * convert it to the latest release of SBML (which is L2v4 currently).
   * If the model is already L2v4, assume that the user wants to attempt to
   * convert it down to Level 1 (specifically L1v2).
   */

  unsigned int olevel   = document->getLevel();
  unsigned int oversion = document->getVersion();
  bool success;

  if (olevel < latestLevel || oversion < latestVersion)
  {
    cout << "Attempting to convert Level " << olevel << " Version " << oversion
	 << " model to Level " << latestLevel
	 << " Version " << latestVersion << "."  << endl;
    success = document->setLevelAndVersion(latestLevel, latestVersion);
  }
  else
  {
    cout << "Attempting to convert Level " << olevel << " Version " << oversion
	 << " model to Level 1 Version 2." << endl;
    success = document->setLevelAndVersion(1, 2);
  }

  errors = document->getNumErrors();

  if (!success)
  {
    cerr << "Unable to perform conversion due to the following:" << endl;
    document->printErrors(cerr);
    cout << endl;
    cout << "Conversion skipped.  Either libSBML does not (yet)" << endl
	 << "have the ability to convert this model or (automatic)" << endl
	 << "conversion is not possible in this case." << endl;

    delete document;
    return errors;
  }   
  else if (errors > 0)
  {
    cout << "Information may have been lost in conversion; but a valid model ";
    cout << "was produced by the conversion.\nThe following information ";
    cout << "was provided:\n";
    document->printErrors(cout);
    writeSBML(document, outputFile);
  }
  else
  {
    cout << "Conversion completed." << endl;
    writeSBML(document, outputFile);
  }

  delete document;
  return 0;
}
Example #18
0
/**
 * Save the gene network to an SBML file. If the argument is null, use the network id.
 * @param filename URL to the file describing the network to load
 * @throws IOException
 */
void GeneNetwork::writeSBML(const char *filename) {
			
	ofstream data_file(filename); 
    if (!data_file.is_open()) {
        std::cerr << "Failed to open file " << filename << std::endl;
        exit(1);
    }
    data_file.close();
			
	::logging::log::emit<Info>() << "Writing file " << filename <<
		::logging::log::endl;
	
	SBMLDocument *sbmlDoc = new SBMLDocument(3, 1);

	Model *model = sbmlDoc->createModel();
	model->setId(id_);
	//model.getNotes ().add (comment_); // save network description
	
	int size = getSize();
	
	Compartment *comp = model->createCompartment();
  	comp->setId("cell");
	comp->setSize(1);

	std::vector<Species*> all_sp;
	Species *sp;

	for (int s=0; s < size; s++) { // save gene as species
//			species[s] = new Species(nodeIds_.get(s), nodeIds_.get(s));
		sp = model->createSpecies();
  		sp->setCompartment("cell");
  		sp->setId((nodes_.at(s)).getLabel());
  		all_sp.push_back(sp);
		//species[s].setInitialAmount(?); // maybe save the wild-type steady state?
		//model.addSpecies(species[s]);
	}
	
	// create the void species
	sp = model->createSpecies();
  	sp->setCompartment("cell");
  	sp->setId("_void_");
	sp->setInitialAmount(0);
	sp->setBoundaryCondition(true);
	sp->setConstant(true);
	all_sp.push_back(sp);
	//model.addSpecies(species[size]);


	// SET SYNTHESIS AND DEGRADATION REACTIONS FOR EVERY GENE
	for (int i=0; i<size; i++) {
		//::logging::log::emit<Info>() << ::logging::log::dec << i <<
		//::logging::log::endl;
		
		// the ID of gene i
//			String currentGeneID = nodeIds_.get(i);
		string currentGeneID = (nodes_.at(i)).getLabel();
		// The modifiers (regulators) of gene i
		std::vector<std::string> inputGenes = (nodes_.at(i)).getInputGenes();
		
		// SYNTHESIS REACTION
		std::string reactionId = currentGeneID + "_synthesis";
		Reaction *reaction = model->createReaction();
		KineticLaw *kineticLaw = reaction->createKineticLaw();
		SpeciesReference *spr;
		ModifierSpeciesReference *msr;
		reaction->setId(reactionId);
		reaction->setReversible (false);
		spr = reaction->createReactant();
  		spr->setSpecies(sp->getId());
  		spr = reaction->createProduct();
  		spr->setSpecies((all_sp.at(i))->getId());
		
		std::stringstream ss;
		ss << inputGenes.size();
		//::logging::log::emit<Debug>() << "node = " << nodes_.at(i).getLabel().c_str() << " #inputs = " << ss.str().c_str() << ::logging::log::endl;
		
		for (unsigned int r=0; r<inputGenes.size(); r++) {// set gene modifiers
//				reaction.addModifier(species[inputIndexes.get(r)]);
			//log.log(Level.INFO, "i = " + size);
			msr = reaction->createModifier();
			msr->setSpecies((all_sp.at(getIndexOfNode(inputGenes.at(r))))->getId());
		}

		//std::vector<RegulatoryModule> modules = (nodes_.at(i)).getRegulatoryModules();
		//log.log(Level.INFO, "size = " + modules.size());
		std::map<std::string, double> *params = new std::map<std::string, double>();
		(nodes_.at(i)).compileParameters(*params);
		
		//char buf[256];
		//sprintf(buf, "%f", nodes_.at(i).getDelta());
		//::logging::log::emit<Info>() << buf << ::logging::log::endl;
		//::logging::log::emit<Info>() << ::logging::log::dec << nodes_.at(i).getAlpha().size() <<
		//		::logging::log::endl;
		
		Parameter *para;
		// save gene parameters (note, the first param is the degradation rate)
		std::map<std::string, double>::iterator p = params->begin();
		//p++;
		for (; p!=params->end(); p++) {
			//if (p == params->begin()) {
			//	p++;
			//	continue;
			//}
			//::logging::log::emit<Info>() << p->first.c_str() <<
			//	::logging::log::endl;
			if (p->first != "delta") {
				para = kineticLaw->createParameter();
				para->setId(p->first);
				para->setValue(p->second);
			}
		}
		reaction->setKineticLaw(kineticLaw);
		model->addReaction(reaction);

		// DEGRADATION REACTION
		reaction = model->createReaction();
		kineticLaw = reaction->createKineticLaw();
		reactionId = currentGeneID + "_degradation";
		reaction->setId(reactionId);
		reaction->setReversible(false);
		spr = reaction->createReactant();
  		spr->setSpecies((all_sp.at(i))->getId());
  		spr = reaction->createProduct();
  		spr->setSpecies(sp->getId());

		para = kineticLaw->createParameter();
		std::map<std::string,double>::iterator it = params->find("delta");
		para->setId(it->first);
		para->setValue(it->second);
		
		reaction->setKineticLaw (kineticLaw);
		model->addReaction (reaction);
	}
	
	// PRINT FILE
	SBMLWriter sbmlWriter;
	sbmlWriter.writeSBML(sbmlDoc, filename);
	
	delete sbmlDoc;
}
LIBSBML_CPP_NAMESPACE_USE

int main(int argc,char** argv)
{
  
  DynPkgNamespaces sbmlns;

  // create the document

  SBMLDocument *document = new SBMLDocument(&sbmlns);
  document->setPackageRequired("dyn", true);

  // create the Model

  Model* model=document->createModel();
  model->setId("singleCell");

  // create the Compartment

  Compartment* compartment = model->createCompartment();
  compartment->setId("Extracellular");
  compartment->setConstant(true);
  compartment->setSize(8000000);
  compartment->setSpatialDimensions(3.0);

  compartment = model->createCompartment();
  compartment->setId("PlasmaMembrane");
  compartment->setConstant(true);
  compartment->setSize(314);
  compartment->setSpatialDimensions(2.0);

  compartment = model->createCompartment();
  compartment->setId("Cytosol");
  compartment->setConstant(true);
  compartment->setSize(523);
  compartment->setSpatialDimensions(3.0);

  // create the Species

  Species* species = model->createSpecies();
  species->setId("C_EC");
  species->setCompartment("Extracellular");
  species->setBoundaryCondition(false);
  species->setConstant(false);
  species->setHasOnlySubstanceUnits(false);

  species = model->createSpecies();
  species->setId("RTR_M");
  species->setCompartment("PlasmaMembrane");
  species->setBoundaryCondition(false);
  species->setConstant(false);
  species->setHasOnlySubstanceUnits(false);

  species = model->createSpecies();
  species->setId("RCC_M");
  species->setCompartment("PlasmaMembrane");
  species->setBoundaryCondition(false);
  species->setConstant(false);
  species->setHasOnlySubstanceUnits(false);

  species = model->createSpecies();
  species->setId("A_C");
  species->setCompartment("Cytosol");
  species->setBoundaryCondition(false);
  species->setConstant(false);
  species->setHasOnlySubstanceUnits(false);

  species = model->createSpecies();
  species->setId("AA_C");
  species->setCompartment("Cytosol");
  species->setBoundaryCondition(false);
  species->setConstant(false);
  species->setHasOnlySubstanceUnits(false);

  species = model->createSpecies();
  species->setId("T");
  species->setCompartment("Cytosol");
  species->setBoundaryCondition(false);
  species->setConstant(false);
  species->setInitialConcentration(10);
  species->setHasOnlySubstanceUnits(false);

  species = model->createSpecies();
  species->setId("S");
  species->setCompartment("Cytosol");
  species->setBoundaryCondition(false);
  species->setConstant(false);
  species->setInitialConcentration(5);
  species->setHasOnlySubstanceUnits(false);

  // create the Reactions

  Reaction* reaction = model->createReaction();
  reaction->setId("r1");
  reaction->setReversible(true);
  reaction->setFast(false);
  reaction->setCompartment("Extracellular");
  
  SpeciesReference* reactant = reaction->createReactant();
  reactant->setSpecies("RTR_M");
  reactant->setStoichiometry(1);
  reactant->setConstant(true);
  
  reactant = reaction->createReactant();
  reactant->setSpecies("C_EC");
  reactant->setStoichiometry(1);
  reactant->setConstant(true);
  
  SpeciesReference* product = reaction->createProduct();
  product->setSpecies("RCC_M");
  product->setStoichiometry(1);
  product->setConstant(true);

  reaction = model->createReaction();
  reaction->setId("r2");
  reaction->setReversible(true);
  reaction->setFast(false);
  reaction->setCompartment("Cytosol");
  
  reactant = reaction->createReactant();
  reactant->setSpecies("A_C");
  reactant->setStoichiometry(1);
  reactant->setConstant(true);
  
  product = reaction->createProduct();
  product->setSpecies("AA_C");
  product->setStoichiometry(1);
  product->setConstant(true);

  SimpleSpeciesReference* modifier = reaction->createModifier();
  modifier->setSpecies("RCC_M");

  // Create Event

  Event* event = model->createEvent();
  event->setUseValuesFromTriggerTime(true);

  Trigger* trigger = event->createTrigger();
  trigger->setInitialValue(false);
  trigger->setPersistent(true);
  trigger->setMath(SBML_parseFormula("lt(AA_C, T)"));

  //
  // Get a DynEventPlugin object plugged in the event object.
  //
  // The type of the returned value of SBase::getPlugin() function is
  // SBasePlugin*, and thus the value needs to be casted for the
  // corresponding derived class.
  //
  DynEventPlugin* eplugin
    = static_cast<DynEventPlugin*>(event->getPlugin("dyn"));

  eplugin->setApplyToAll(true);
  eplugin->setCboTerm("http://cbo.biocomplexity.indiana.edu/svn/cbo/trunk/CBO_1_0.owl#CellDeath");
 
  event = model->createEvent();
  event->setUseValuesFromTriggerTime(true);

  trigger = event->createTrigger();
  trigger->setInitialValue(false);
  trigger->setPersistent(true);
  trigger->setMath(SBML_parseFormula("lt(AA_C, S)"));

  eplugin = static_cast<DynEventPlugin*>(event->getPlugin("dyn"));

  eplugin->setApplyToAll(true);
  eplugin->setCboTerm("http://cbo.biocomplexity.indiana.edu/svn/cbo/trunk/CBO_1_0.owl#CellDevision");

  document->checkConsistency();

  if (document->getNumErrors(LIBSBML_SEV_ERROR) > 0)
    document->printErrors();

  writeSBML(document,"dyn_example1.xml");
  delete document;
}
int main(int argc,char** argv)
{
  int retval = 0;
  SBMLNamespaces sbmlns(3,1,"comp",1);

  // create the document
  SBMLDocument *document = new SBMLDocument(&sbmlns);

  //Define the external model definitions
  CompSBMLDocumentPlugin* compdoc
      = static_cast<CompSBMLDocumentPlugin*>(document->getPlugin("comp"));
  compdoc->setRequired(true);
  ExternalModelDefinition* extmod = compdoc->createExternalModelDefinition();
  extmod->setId("ExtMod1");
  extmod->setSource("enzyme_model.xml");
  extmod->setModelRef("enzyme");


  // create the main Model
  Model* model=document->createModel();
  
  // Set the submodels
  CompModelPlugin* mplugin = static_cast<CompModelPlugin*>(model->getPlugin("comp"));
  Submodel* submod1 = mplugin->createSubmodel();
  submod1->setId("A");
  submod1->setModelRef("ExtMod1");
  Submodel* submod2 = mplugin->createSubmodel();
  submod2->setId("B");
  submod2->setModelRef("ExtMod1");

  // create a replacement compartment
  Compartment* comp=model->createCompartment();
  comp->setSpatialDimensions((unsigned int)3);
  comp->setConstant(true);
  comp->setId("comp");
  comp->setSize(1L);

  //Tell the model that this compartment replaces both of the inside ones.
  CompSBasePlugin* compartplug = static_cast<CompSBasePlugin*>(comp->getPlugin("comp"));
  ReplacedElement re;
  re.setIdRef("comp");
  re.setSubmodelRef("A");
  compartplug->addReplacedElement(&re);
  re.setSubmodelRef("B");
  compartplug->addReplacedElement(&re);

  // create a replacement species
  Species* spec = model->createSpecies();
  spec->setCompartment("comp");
  spec->setHasOnlySubstanceUnits(false);
  spec->setConstant(false);
  spec->setBoundaryCondition(false);
  spec->setId("S");

  //Tell the model that this species replaces both of the inside ones.
  CompSBasePlugin* spp = static_cast<CompSBasePlugin*>(spec->getPlugin("comp"));
  re.setIdRef("S");
  re.setSubmodelRef("A");
  spp->addReplacedElement(&re);
  re.setSubmodelRef("B");
  spp->addReplacedElement(&re);

  writeSBMLToFile(document,"eg-import-external.xml");
  writeSBMLToFile(document,"spec_example2.xml");
  delete document;
  document = readSBMLFromFile("spec_example2.xml");
  if (document == NULL)
  {
    cout << "Error reading back in file." << endl;
    retval = -1;
  }
  else
  {
    document->setConsistencyChecks(LIBSBML_CAT_UNITS_CONSISTENCY, false);
    document->checkConsistency();
    if (document->getErrorLog()->getNumFailsWithSeverity(2) > 0
        || document->getErrorLog()->getNumFailsWithSeverity(3) > 0)
    {
      stringstream errorstream;
      document->printErrors(errorstream);
      cout << "Errors encoutered when round-tripping  SBML file: \n"
           <<  errorstream.str() << endl;
      retval = -1;
    }
    writeSBMLToFile(document, "spec_example2_rt.xml");
    delete document;
  }
#ifdef WIN32
  if (retval != 0)
  {
    cout << "(Press any key to exit.)" << endl;
    _getch();
  }
#endif
  return retval;
}
END_TEST


START_TEST (test_GetMultipleObjects_getMetaId)
{
  SBMLReader        reader;
  SBMLDocument*     d;

  std::string filename(TestDataDirectory);
  filename += "multiple-ids.xml";


  d = reader.readSBML(filename);

  if (d == NULL)
  {
    fail("readSBML(\"multiple-ids.xml\") returned a NULL pointer.");
  }

  SBase* obj = d->getElementByMetaId("no_id");
  fail_unless(obj == NULL);

  obj = d->getElementByMetaId("");
  fail_unless(obj == NULL);

  obj = d->getElementByMetaId("meta1");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_DOCUMENT);

  obj = d->getElementByMetaId("meta2");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_MODEL);

  obj = d->getElementByMetaId("meta3");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_LIST_OF);
  fail_unless(static_cast<ListOf*>(obj)->getItemTypeCode() == SBML_COMPARTMENT);

  obj = d->getElementByMetaId("meta4");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_COMPARTMENT);

  obj = d->getElementByMetaId("meta5");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_LIST_OF);
  fail_unless(static_cast<ListOf*>(obj)->getItemTypeCode() == SBML_SPECIES);

  obj = d->getElementByMetaId("meta6");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_SPECIES);

  obj = d->getElementByMetaId("meta7");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_LIST_OF);
  fail_unless(static_cast<ListOf*>(obj)->getItemTypeCode() == SBML_REACTION);

  obj = d->getElementByMetaId("meta8");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_REACTION);

  obj = d->getElementByMetaId("meta9");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_LIST_OF);
  fail_unless(static_cast<ListOf*>(obj)->getItemTypeCode() == SBML_SPECIES_REFERENCE);

  obj = d->getElementByMetaId("meta10");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_SPECIES_REFERENCE);

  obj = d->getElementByMetaId("meta11");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_KINETIC_LAW);

  obj = d->getElementByMetaId("meta12");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_LIST_OF);
  fail_unless(static_cast<ListOf*>(obj)->getItemTypeCode() == SBML_EVENT);

  obj = d->getElementByMetaId("meta13");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_EVENT);

  obj = d->getElementByMetaId("meta14");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_TRIGGER);

  obj = d->getElementByMetaId("meta15");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_LIST_OF);
  fail_unless(static_cast<ListOf*>(obj)->getItemTypeCode() == SBML_EVENT_ASSIGNMENT);

  obj = d->getElementByMetaId("meta16");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_EVENT_ASSIGNMENT);

  obj = d->getElementByMetaId("meta17");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_DELAY);

  obj = d->getElementByMetaId("meta18");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_PARAMETER);

  obj = d->getElementByMetaId("meta19");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_PRIORITY);

  obj = d->getElementByMetaId("meta20");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_LIST_OF);
  fail_unless(static_cast<ListOf*>(obj)->getItemTypeCode() == SBML_FUNCTION_DEFINITION);

  obj = d->getElementByMetaId("meta21");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_FUNCTION_DEFINITION);

  obj = d->getElementByMetaId("meta22");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_LIST_OF);
  fail_unless(static_cast<ListOf*>(obj)->getItemTypeCode() == SBML_INITIAL_ASSIGNMENT);

  obj = d->getElementByMetaId("meta23");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_INITIAL_ASSIGNMENT);

  obj = d->getElementByMetaId("meta24");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_LIST_OF);
  fail_unless(static_cast<ListOf*>(obj)->getItemTypeCode() == SBML_RULE);

  obj = d->getElementByMetaId("meta25");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_RATE_RULE);

  obj = d->getElementByMetaId("meta26");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_ASSIGNMENT_RULE);

  obj = d->getElementByMetaId("meta27");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_LIST_OF);
  fail_unless(static_cast<ListOf*>(obj)->getItemTypeCode() == SBML_LOCAL_PARAMETER);

  obj = d->getElementByMetaId("meta28");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_LOCAL_PARAMETER);

  obj = d->getElementByMetaId("meta29");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_LIST_OF);
  fail_unless(static_cast<ListOf*>(obj)->getItemTypeCode() == SBML_UNIT_DEFINITION);

  obj = d->getElementByMetaId("meta30");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_UNIT_DEFINITION);

  obj = d->getElementByMetaId("meta31");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_LIST_OF);
  fail_unless(static_cast<ListOf*>(obj)->getItemTypeCode() == SBML_UNIT);

  obj = d->getElementByMetaId("meta32");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_UNIT);

  obj = d->getElementByMetaId("meta33");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_LIST_OF);
  fail_unless(static_cast<ListOf*>(obj)->getItemTypeCode() == SBML_PARAMETER);

  obj = d->getElementByMetaId("meta34");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_LIST_OF);
  fail_unless(static_cast<ListOf*>(obj)->getItemTypeCode() == SBML_MODIFIER_SPECIES_REFERENCE);

  obj = d->getElementByMetaId("meta35");
  fail_unless(obj != NULL);
  fail_unless(obj->getTypeCode() == SBML_MODIFIER_SPECIES_REFERENCE);


  delete d;
}
int CompModelPlugin::collectRenameAndConvertReplacements(set<SBase*>* removed, set<SBase*>* toremove)
{
  int ret = LIBSBML_OPERATION_SUCCESS;
  SBMLDocument* doc = getSBMLDocument();
  Model* model = static_cast<Model*>(getParentSBMLObject());
  if (model==NULL) {
    if (doc) {
      string error = "Unable to perform replacements in CompModelPlugin::collectRenameAndConvertReplacements: no parent model could be found for the given 'comp' model plugin element.";
      doc->getErrorLog()->logPackageError("comp", CompModelFlatteningFailed, getPackageVersion(), getLevel(), getVersion(), error);
    }
    return LIBSBML_OPERATION_FAILED;
  }
  List* allElements = model->getAllElements();
  vector<ReplacedElement*> res;
  vector<ReplacedBy*> rbs;
  //Collect replaced elements and replaced by's.
  for (unsigned int e=0; e<allElements->getSize(); e++) {
    SBase* element = static_cast<SBase*>(allElements->get(e));
    int type = element->getTypeCode();
    if (type==SBML_COMP_REPLACEDELEMENT) {
      ReplacedElement* reference = static_cast<ReplacedElement*>(element);
      res.push_back(reference);
    }
    if (type==SBML_COMP_REPLACEDBY) {
      ReplacedBy* reference = static_cast<ReplacedBy*>(element);
      rbs.push_back(reference);
    }
  }
  delete allElements;

  //ReplacedElement replacements
  for (size_t re=0; re<res.size(); re++) {
    ret = res[re]->performReplacementAndCollect(removed, toremove);
    if (ret != LIBSBML_OPERATION_SUCCESS) {
      return ret;
    }
  }

  //Now do the same thing for anything left over in the submodels
  for (unsigned int sub=0; sub<getNumSubmodels(); sub++) {
    Submodel* submodel = getSubmodel(sub);
    Model* mod = submodel->getInstantiation();
    if (mod==NULL) return LIBSBML_OPERATION_FAILED;
    CompModelPlugin* modplug = static_cast<CompModelPlugin*>(mod->getPlugin(getPrefix()));
    if (modplug==NULL) return LIBSBML_OPERATION_FAILED;
    //'left behind' converions (not LaHaye-style)
    ret = submodel->convertTimeAndExtent();
    if (ret != LIBSBML_OPERATION_SUCCESS) return ret;
    ret = modplug->collectRenameAndConvertReplacements(removed, toremove);
    if (ret != LIBSBML_OPERATION_SUCCESS) return ret;
  }

  //Perform ReplacedBy replacements *after* the submodels are done, so that the topmost-level names take precedence.
  for (size_t rb=0; rb<rbs.size(); rb++) {
    ret = rbs[rb]->performReplacementAndCollect(removed, toremove);
    if (ret != LIBSBML_OPERATION_SUCCESS) {
      return ret;
    }
  }

  return ret;
}
END_TEST

START_TEST(test_FbcExtension_read_L3V1V1_with_wonky_chemicals)
{
  const char* modelString = "<?xml version='1.0' encoding='UTF-8'?>"
"<sbml xmlns:html='http://www.w3.org/1999/xhtml' xmlns='http://www.sbml.org/sbml/level3/version1/core' xmlns:fbc='http://www.sbml.org/sbml/level3/version1/fbc/version1' level='3' version='1' fbc:required='false'>"
"  <model metaid='xxx' id='yyy' timeUnits='dimensionless'>"
"    <listOfCompartments>"
"      <compartment id='Internal_Species' name='Internal_Species' spatialDimensions='3' size='1' constant='false'/>"
"      <compartment id='External_Species' name='External_Species' spatialDimensions='3' size='1' constant='false'/>"
"    </listOfCompartments>"
"    <listOfSpecies>"
"      <species metaid='meta_B1' id='B1' name='Protein component' compartment='Internal_Species' initialConcentration='0' hasOnlySubstanceUnits='false' boundaryCondition='false' constant='false' fbc:chemicalFormula='PROTEIN COMPONENT'>"
"        <notes>"
"          <html:p>chemFormula: Protein component</html:p>"
"        </notes>"
"        <annotation>"
"          <listOfKeyValueData xmlns='http://pysces.sourceforge.net/KeyValueData'>"
"            <data id='chemFormula' type='string' value='Protein component'/>"
"          </listOfKeyValueData>"
"        </annotation>"
"      </species>"
"      <species metaid='meta_B2' id='B2' name='DNA component' compartment='Internal_Species' initialConcentration='0' hasOnlySubstanceUnits='false' boundaryCondition='false' constant='false' fbc:chemicalFormula='DNA COMPONENT'>"
"        <notes>"
"          <html:p>chemFormula: DNA component</html:p>"
"        </notes>"
"        <annotation>"
"          <listOfKeyValueData xmlns='http://pysces.sourceforge.net/KeyValueData'>"
"            <data id='chemFormula' type='string' value='DNA component'/>"
"          </listOfKeyValueData>"
"        </annotation>"
"      </species>"
"    </listOfSpecies>"
"    <listOfReactions>"
"      <reaction metaid='meta_R00192' id='R00192' name='R106' reversible='false' fast='false'>"
"        <notes>"
"          <html:p>EC Number: 3.3.1.1</html:p>"
"          <html:p>GENE ASSOCIATION: sll1234</html:p>"
"        </notes>"
"        <annotation>"
"          <listOfKeyValueData xmlns='http://pysces.sourceforge.net/KeyValueData'>"
"            <data id='EC_Number' type='string' value='3.3.1.1'/>"
"            <data id='GENE_ASSOCIATION' type='string' value='sll1234'/>"
"          </listOfKeyValueData>"
"        </annotation>"
"        <listOfReactants>"
"          <speciesReference species='B1' stoichiometry='1' constant='true'/>"
"        </listOfReactants>"
"        <listOfProducts>"
"          <speciesReference species='B2' stoichiometry='1' constant='true'/>"
"        </listOfProducts>"
"      </reaction>"
"    </listOfReactions>"
"    <fbc:listOfFluxBounds>"
"      <fbc:fluxBound fbc:reaction='R00192' fbc:operation='greaterEqual' fbc:value='0'/>"
"      <fbc:fluxBound fbc:reaction='R00192' fbc:operation='lessEqual' fbc:value='999999'/>     "
"    </fbc:listOfFluxBounds>"
"    <fbc:listOfObjectives fbc:activeObjective='obj'>"
"      <fbc:objective fbc:id='obj' fbc:type='maximize'>"
"        <fbc:listOfFluxObjectives>"
"          <fbc:fluxObjective fbc:reaction='R00192' fbc:coefficient='1'/>"
"        </fbc:listOfFluxObjectives>"
"      </fbc:objective>"
"    </fbc:listOfObjectives>"
"  </model>"
"</sbml>";

  SBMLDocument* doc = readSBMLFromString(modelString);
  doc->checkConsistency();
  fail_unless(doc->getErrorLog()->contains(FbcSpeciesFormulaMustBeString));

  //convert to cobra just to test
  ConversionProperties prop;
  prop.addOption("convert fbc to cobra", true);
  fail_unless(doc->convert(prop) == LIBSBML_OPERATION_SUCCESS);
  
  // add species with notes 
  Species* testSpecies = doc->getModel()->createSpecies();
  testSpecies->initDefaults();
  testSpecies->setId("testSpecies");
  testSpecies->setNotes(
          "<body xmlns='http://www.w3.org/1999/xhtml'>"
          "  <p>FORMULA: Fe2S2X</p>                   "
          "  <p>CHARGE: -1</p>                        "
          "</body>                                    "
  );
  
  // convert it back
  prop.addOption("convert cobra", true);
  fail_unless(doc->convert(prop) == LIBSBML_OPERATION_SUCCESS);
  
  // check the formula
  Species* tested = doc->getModel()->getSpecies("testSpecies");
  fail_unless(tested != NULL);
  FbcSpeciesPlugin* fbcSpeciesPlugin = dynamic_cast<FbcSpeciesPlugin*>(tested->getPlugin("fbc"));
  fail_unless(fbcSpeciesPlugin != NULL);
  fail_unless(fbcSpeciesPlugin->getCharge() == -1);
  fail_unless(fbcSpeciesPlugin->getChemicalFormula() == "Fe2S2X");
  

}
Model* CompModelPlugin::flattenModel() const
{
  //First make a copy of our parent (the model to be flattened):
  const Model* parent = static_cast<const Model*>(getParentSBMLObject());
  
  if (parent==NULL) {
    return NULL;
  }
  //doc needs to be non-const so that the error messages can be updated.  Otherwise, nothing changes.
  SBMLDocument* doc = const_cast<SBMLDocument*>(getSBMLDocument());
  if (doc==NULL) {
    return NULL;
  }

  //Set the original document so that it can find the model definitions 
  //and external model definitions while we flatten.
  Model* flat = parent->clone();
  flat->setSBMLDocument(doc);
  CompModelPlugin* flatplug = 
    static_cast<CompModelPlugin*>(flat->getPlugin(getPrefix()));

  // Now instantiate its submodels and 
  // follow all renaming/deletion/replacement rules.
  vector<const Model*> submods;
  int success = flatplug->instantiateSubmodels();

  if (success != LIBSBML_OPERATION_SUCCESS) {
    //instantiateSubmodels sets its own error messages.
    delete flat;
    return NULL;
  }

  //Now start the aggregation process.  
  //This goes from the bottom up, calling 'appendFrom' iteratively 
  //(from the plugin).
  for (unsigned int sm=0; sm<flatplug->getNumSubmodels(); sm++) 
  {
    Model* submodel = flatplug->getSubmodel(sm)->getInstantiation();
    if (submodel==NULL) {
      //getInstantiation should be calling a cached value by now, but if not, it will set its own error messages.
      delete flat;
      return NULL;
    }
    CompModelPlugin* submodplug = 
      static_cast<CompModelPlugin*>(submodel->getPlugin(getPrefix()));

    if (submodplug != NULL) {
      //Strip the ports from the submodel, as we no longer need them.
      while (submodplug->getNumPorts() > 0) 
      {
        submodplug->removePort(0);
      }
    }
    success = flat->appendFrom(submodel);
    if (success != LIBSBML_OPERATION_SUCCESS) {
      string error = "Unable to flatten model in CompModelPlugin::flattenModel: appending elements from the submodel '" + submodel->getId() + "' to the elements of the parent model failed.";
      doc->getErrorLog()->logPackageError("comp", CompModelFlatteningFailed, getPackageVersion(), getLevel(), getVersion(), error);
      delete flat;
      return NULL;
    }
  }

  // Now we clear the saved referenced elements in the local Port objects, 
  // but point them to the new object if necessary.
  flatplug->resetPorts();

  // Next, strip the package info from 'flat'.  
  // We're going to remove everything but the Ports:
  flatplug->mListOfSubmodels.clear();
  flatplug->clearReplacedElements();
  flatplug->unsetReplacedBy();
  
  List* allelements = flat->getAllElements();
  
  vector<SBase*> nonReplacedElements;
  
  for (unsigned int el=0; el<allelements->getSize(); el++) 
  {
    SBase* element = static_cast<SBase*>(allelements->get(el));
    int type = element->getTypeCode();
    if (!(type==SBML_COMP_REPLACEDBY ||
          type==SBML_COMP_REPLACEDELEMENT ||
          type==SBML_COMP_SBASEREF)) 
    {
            nonReplacedElements.push_back(element);
    }
  }

  // delete the list
  delete allelements;

  for (unsigned int el=0; el<nonReplacedElements.size(); el++) 
  {
    SBase* element = nonReplacedElements[el];
    CompSBasePlugin* elplug = 
      static_cast<CompSBasePlugin*>(element->getPlugin(getPrefix()));
    if (elplug != NULL) 
    {
      elplug->clearReplacedElements();
      elplug->unsetReplacedBy();
    }
  }



  //Finally, unset the document again.
  flat->setSBMLDocument(NULL);

  return flat;
}
END_TEST


START_TEST (test_GroupsExtension_read_memberConstraints)
{
  char *filename = safe_strcat(TestDataDirectory, "groups_speciestype_example.xml");
  SBMLDocument *document = readSBMLFromFile(filename);
  fail_unless(document->getPackageName() == "core");

  Model *model = document->getModel();

  fail_unless(model != NULL);
  fail_unless(model->getPackageName() == "core");
  fail_unless(document->getNumErrors() == 0);

  // get the Group

  GroupsModelPlugin* mplugin = static_cast<GroupsModelPlugin*>(model->getPlugin("groups"));
  fail_unless(mplugin != NULL);

  fail_unless(mplugin->getNumGroups() == 1);
  fail_unless(mplugin->getListOfGroups()->getPackageName() == "groups");

  Group* group = mplugin->getGroup(0);
  fail_unless(group->getId()          == "ATP");
  fail_unless(group->getKind()        == GROUP_KIND_CLASSIFICATION);
  fail_unless(group->getNumMembers()  == 2);
  fail_unless(group->getNumMemberConstraints() == 3);
  fail_unless(group->getPackageName() == "groups");

  fail_unless(group->getListOfMembers()->getPackageName() == "groups");
  fail_unless(group->getListOfMembers()->getSBOTermID()   == "SBO:0000248");

  Member* member = group->getMember(0);
  fail_unless(member->getIdRef()      == "ATPc");
  fail_unless(member->getPackageName() == "groups");

  member = group->getMember(1);
  fail_unless(member->getIdRef()      == "ATPm");
  fail_unless(member->getPackageName() == "groups");

  ListOfMemberConstraints* lomcs = group->getListOfMemberConstraints();
  fail_unless(lomcs->getPackageName() == "groups");
  fail_unless(lomcs->isSetMembersShareType() == true);
  fail_unless(lomcs->getMembersShareType() == true);

  MemberConstraint* mc = group->getMemberConstraint(0);
  fail_unless(mc->isSetDistinctAttribute() == true);
  fail_unless(mc->isSetIdenticalAttribute() == false);
  fail_unless(mc->getDistinctAttribute() == "compartment");
  fail_unless(mc->getPackageName() == "groups");

  mc = group->getMemberConstraint(1);
  fail_unless(mc->isSetDistinctAttribute() == false);
  fail_unless(mc->isSetIdenticalAttribute() == true);
  fail_unless(mc->getIdenticalAttribute() == "initialConcentration");
  fail_unless(mc->getPackageName() == "groups");

  mc = group->getMemberConstraint(2);
  fail_unless(mc->isSetDistinctAttribute() == false);
  fail_unless(mc->isSetIdenticalAttribute() == true);
  fail_unless(mc->getIdenticalAttribute() == "constant");
  fail_unless(mc->getPackageName() == "groups");


  delete document;  
}
int CompModelPlugin::saveAllReferencedElements(set<SBase*> uniqueRefs, set<SBase*> replacedBys)
{
  SBMLDocument* doc = getSBMLDocument();
  Model* model = static_cast<Model*>(getParentSBMLObject());
  if (model==NULL) {
    if (doc) {
      string error = "Unable to discover any referenced elements in CompModelPlugin::saveAllReferencedElements: no Model parent of the 'comp' model plugin.";
      doc->getErrorLog()->logPackageError("comp", CompModelFlatteningFailed, getPackageVersion(), getLevel(), getVersion(), error);
    }
    return LIBSBML_OPERATION_FAILED;
  }
  int ret = LIBSBML_OPERATION_SUCCESS;

  //Get a list of everything, pull out anything that's a deletion, replacement, or port, and save what they're pointing to.
  //At the same time, make sure that no two things point to the same thing.
  set<SBase*> RE_deletions = set<SBase*>(); //Deletions only point to things in the same model.
  List* allElements = model->getAllElements();
  string modname = "the main model in the document";
  if (model->isSetId()) {
    modname = "the model '" + model->getId() + "'";
  }
  for (unsigned int el=0; el<allElements->getSize(); el++) {
    SBase* element = static_cast<SBase*>(allElements->get(el));
    int type = element->getTypeCode();
    if (type==SBML_COMP_DELETION ||
        type==SBML_COMP_REPLACEDBY ||
        type==SBML_COMP_REPLACEDELEMENT ||
        type==SBML_COMP_PORT) {
          //Don't worry about SBML_COMP_SBASEREF because they're all children of one of the above types.
          SBaseRef* reference = static_cast<SBaseRef*>(element);
          ReplacedElement* re = static_cast<ReplacedElement*>(element);
          ret = reference->saveReferencedElement();
          if (ret != LIBSBML_OPERATION_SUCCESS) 
          {
            if (type != SBML_COMP_REPLACEDBY && doc) 
            {
              SBMLErrorLog* errlog = doc->getErrorLog();
              SBMLError* lasterr = const_cast<SBMLError*>
                (doc->getErrorLog()->getError(doc->getNumErrors()-1));
              if ( (errlog->contains(UnrequiredPackagePresent) || 
                    errlog->contains(RequiredPackagePresent))) 
              {
                if ( lasterr->getErrorId() == CompIdRefMustReferenceObject)
                {
                   //Change the error into a warning
                   string fullmsg = lasterr->getMessage() 
                     + "  However, this may be because of the unrecognized "
                     + "package present in this document:  ignoring this "
                     + "element and flattening anyway.";
                   errlog->remove(lasterr->getErrorId());
                   errlog->logPackageError("comp", 
                     CompIdRefMayReferenceUnknownPackage, getPackageVersion(), 
                     getLevel(), getVersion(), fullmsg, element->getLine(), 
                     element->getColumn(), LIBSBML_SEV_WARNING);
                    element->removeFromParentAndDelete();
                    continue;
                }
                else if ( lasterr->getErrorId() == CompMetaIdRefMustReferenceObject)
                {
                   //Change the error into a warning
                   string fullmsg = lasterr->getMessage() 
                     + "  However, this may be because of the unrecognized "
                     + "package present in this document:  ignoring this "
                     + "element and flattening anyway.";
                   errlog->remove(lasterr->getErrorId());
                   errlog->logPackageError("comp", 
                     CompMetaIdRefMayReferenceUnknownPkg, getPackageVersion(), 
                     getLevel(), getVersion(), fullmsg, element->getLine(), 
                     element->getColumn(), LIBSBML_SEV_WARNING);
                    element->removeFromParentAndDelete();
                    continue;
                }
                else if (lasterr->getErrorId() == 
                                  CompIdRefMayReferenceUnknownPackage)
                {
                  element->removeFromParentAndDelete();
                  continue;
                }
                else if (lasterr->getErrorId() == 
                                  CompMetaIdRefMayReferenceUnknownPkg)
                {
                  element->removeFromParentAndDelete();
                  continue;
                }
              }
              else 
              {
                delete allElements;
                return ret;
              }
            }
            else {
              delete allElements;
              return ret;
            }
          }
          SBase* direct = reference->getDirectReference();
          bool adddirect = true;
          if (type == SBML_COMP_REPLACEDBY) {
            SBase* rbParent = reference->getParentSBMLObject();
            if (uniqueRefs.insert(rbParent).second == false) {
              if (doc) {
                string error = "Error discovered in CompModelPlugin::saveAllReferencedElements when checking " + modname + ": a <" + rbParent->getElementName() + "> ";
                if (direct->isSetId()) {
                  error += "with the id '" + rbParent->getId() + "'";
                  if (rbParent->isSetMetaId()) {
                    error += ", and the metaid '" + rbParent->getMetaId() + "'";
                  }
                }
                else if (rbParent->isSetMetaId()) {
                  error += "with the metaId '" + rbParent->getMetaId() + "'";
                }
                error += " has a <replacedBy> child and is also pointed to by a <port>, <deletion>, <replacedElement>, or one or more <replacedBy> objects.";
                doc->getErrorLog()->logPackageError("comp", CompNoMultipleReferences, getPackageVersion(), getLevel(), getVersion(), error);
              }
              delete allElements;
              return LIBSBML_OPERATION_FAILED;
            }
            adddirect = replacedBys.insert(direct).second;
          }
          if (type==SBML_COMP_REPLACEDELEMENT && re->isSetDeletion()) {
            adddirect = RE_deletions.insert(direct).second;
          }
          if (adddirect) {
            if (uniqueRefs.insert(direct).second == false) {
              if (doc) {
                string error = "Error discovered in CompModelPlugin::saveAllReferencedElements when checking " + modname + ": ";
                if (replacedBys.find(direct) != replacedBys.end()) {
                  error += "one or more <replacedBy> elements, plus a <deletion>, <replacedElement>, or <port> element";
                }
                else if (RE_deletions.find(direct) != RE_deletions.end()) {
                  error += "one or more <replacedElement> elements using a 'deletion' attribute, plus a <deletion>, <replacedElement>, or <port> element";
                }
                else {
                  error += "multiple <deletion>, <replacedElement>, and/or <port> elements";
                }
                error += " point directly to the <" + direct->getElementName() + "> ";
                if (direct->isSetId()) {
                  error += "with the id '" + direct->getId() + "'";
                  if (direct->isSetMetaId()) {
                    error += ", and the metaid '" + direct->getMetaId() + "'";
                  }
                  error += ".";
                }
                else if (direct->isSetMetaId()) {
                  error += "with the metaId '" + direct->getMetaId() + "'.";
                }
                doc->getErrorLog()->logPackageError("comp", CompNoMultipleReferences, getPackageVersion(), getLevel(), getVersion(), error);
              }
              delete allElements;
              return LIBSBML_OPERATION_FAILED;
            }
          }
    }
  }

  delete allElements;

  //Now call saveAllReferencedElements for all instantiated submodels.
  for (unsigned long sm=0; sm<getNumSubmodels(); sm++) {
    Model* sub = getSubmodel(sm)->getInstantiation();
    if (sub==NULL) {
      return LIBSBML_OPERATION_FAILED;
    }
    CompModelPlugin* subplug = static_cast<CompModelPlugin*>(sub->getPlugin(getPrefix()));
    if (subplug==NULL) {
      return LIBSBML_OPERATION_FAILED;
    }
    ret = subplug->saveAllReferencedElements(uniqueRefs, replacedBys);
    if (ret != LIBSBML_OPERATION_SUCCESS) {
      return ret;
    }
  }

  return LIBSBML_OPERATION_SUCCESS;
}
Example #27
0
LIBSBML_CPP_NAMESPACE_USE

int
main (int argc, char* argv[])
{
  SBMLNamespaces sbmlns(3,1,"arrays",1);

  // create the document

  SBMLDocument *document = new SBMLDocument(&sbmlns);

  // set the required attribute to true
  ArraysSBMLDocumentPlugin * docPlug = 
    static_cast<ArraysSBMLDocumentPlugin*>(document->getPlugin("arrays"));
  docPlug->setRequired(true);


  // create the Model

  Model* model=document->createModel();

  // create the parameters

  // first parameter - for dimension m
  Parameter * p = model->createParameter();
  p->setId("m");
  p->setConstant(true);
  p->setValue(2);

  // second parameter - for dimension n
  p = model->createParameter();
  p->setId("n");
  p->setConstant(true);
  p->setValue(1);

  // third parameter - 2 x 1 matrix of parameters
  p = model->createParameter();
  p->setId("x");
  p->setConstant(false);


  // create the Dimensions via the Plugin
  ArraysSBasePlugin * arraysPlug = 
    static_cast<ArraysSBasePlugin*>(p->getPlugin("arrays"));

  // first dimension
  Dimension * dim = arraysPlug->createDimension();
  dim->setArrayDimension(0);
  dim->setSize("m");

  // second dimension
  dim = arraysPlug->createDimension();
  dim->setArrayDimension(1);
  dim->setSize("n");

  // other parameters
  p = model->createParameter();
  p->setId("y");
  p->setConstant(true);
  p->setValue(2.3);



  // create the initialAssignment
  InitialAssignment *ia = model->createInitialAssignment();
  ia->setSymbol("x");

  ASTNode * row1 = new ASTNode(AST_LINEAR_ALGEBRA_VECTOR_CONSTRUCTOR);
  
  ASTNode * ci1 = new ASTNode(AST_NAME);
  ci1->setName("y");
  
  row1->addChild(ci1);

  ASTNode * row2 = new ASTNode(AST_LINEAR_ALGEBRA_VECTOR_CONSTRUCTOR);
  
  ASTNode * ci2 = new ASTNode(AST_INTEGER);
  ci2->setValue(2);

  row2->addChild(ci2);

  ASTNode * math = new ASTNode(AST_LINEAR_ALGEBRA_VECTOR_CONSTRUCTOR);

  math->addChild(row1);
  math->addChild(row2);

  ia->setMath(math);

  writeSBML(document,"arrays_example3.xml");
 
  delete document;

  return 0;
}
int 
CompModelPlugin::renameAllIDsAndPrepend(const std::string& prefix)
{
  SBMLDocument* doc = getSBMLDocument();
  Model* model = static_cast<Model*>(getParentSBMLObject());
  if (model==NULL) {
    if (doc) {
      string error = "Unable to rename elements in CompModelPlugin::renameAllIDsAndPrepend: no parent model could be found for the given 'comp' model plugin element.";
      doc->getErrorLog()->logPackageError("comp", CompModelFlatteningFailed, getPackageVersion(), getLevel(), getVersion(), error);
    }
    return LIBSBML_INVALID_OBJECT;
  }

  //First rename the elements in all instantiated submodels.
  vector<string> submodids;

  for (unsigned int sm=0; sm<getNumSubmodels(); sm++) {
    Submodel* subm=getSubmodel(sm);
    if (subm==NULL) {
      if (doc) {
        stringstream error;
        error << "Unable to rename elements in CompModelPlugin::renameAllIDsAndPrepend: no valid submodel number " << sm << "for model " << model->getId();
        doc->getErrorLog()->logPackageError("comp", CompModelFlatteningFailed,
          getPackageVersion(), getLevel(), getVersion(), error.str());
      }
      return LIBSBML_OPERATION_FAILED;
    }
    if (!subm->isSetId()) {
      if (doc) {
        stringstream error;
        error << "Unable to rename elements in CompModelPlugin::renameAllIDsAndPrepend: submodel number " << sm << "for model " << model->getId() << " is invalid: it has no 'id' attribute set.";
        doc->getErrorLog()->logPackageError("comp", CompSubmodelAllowedAttributes,
          getPackageVersion(), getLevel(), getVersion(), error.str());
      }
      return LIBSBML_INVALID_OBJECT;
    }
    submodids.push_back(subm->getId());
  }

  //Check to see if any of the various submodel ids are used as a prefix 
  List* allElements = model->getAllElements();
  findUniqueSubmodPrefixes(submodids, allElements);

  //Now that we've found valid prefixes for all our submodels, call this function recursively on them.
  for (unsigned int sm=0; sm<getNumSubmodels(); sm++) {
    Submodel* subm=getSubmodel(sm); //already checked this above.
    Model* inst = subm->getInstantiation();
    if (inst==NULL) {
      //'getInstantiation' will set its own error messages.
      delete allElements;
      return LIBSBML_OPERATION_FAILED;
    }
    CompModelPlugin* instp = static_cast<CompModelPlugin*>(inst->getPlugin(getPrefix()));
    if (instp==NULL) {
      if (doc) {
        //Shouldn't happen:  'getInstantiation' turns on the comp plugin.
        string error = "Unable to rename elements in CompModelPlugin::renameAllIDsAndPrepend: no valid 'comp' plugin for the model instantiated from submodel " + subm->getId();
        doc->getErrorLog()->logPackageError("comp", CompModelFlatteningFailed, getPackageVersion(), getLevel(), getVersion(), error);
      }
      delete allElements;
      return LIBSBML_OPERATION_FAILED;
    }
    int ret = instp->renameAllIDsAndPrepend(prefix + submodids[sm]);
    if (ret != LIBSBML_OPERATION_SUCCESS) {
      //'renameAllIds..' will set its own error messages.
      delete allElements;
      return ret;
    }
  }

  //Finally, actually rename the elements in *this* model with the prefix.
  if (prefix.empty()) 
  {
    delete allElements;
    return LIBSBML_OPERATION_SUCCESS; //Nothing to add
  }

  //Rename the SIds, UnitSIds, and MetaIDs, and references to them.
  renameIDs(allElements, prefix);
  delete allElements;

  return LIBSBML_OPERATION_SUCCESS;
}
Example #29
0
int 
Submodel::instantiate()
{
  SBMLDocument* doc = getSBMLDocument();
  SBMLDocument* rootdoc = doc;
  if (doc==NULL) 
  {
    return LIBSBML_OPERATION_FAILED;
  }

  CompSBMLDocumentPlugin* docplugin = 
    static_cast<CompSBMLDocumentPlugin*>(doc->getPlugin(getPrefix()));
  if (docplugin==NULL)
  {
    return LIBSBML_OPERATION_FAILED;
  }

  SBase* parent  = getParentSBMLObject();
  string parentmodelname = "";
  string parentURI = "";
  set<string> uniqueModels;
  while (parent != NULL && parent->getTypeCode() != SBML_DOCUMENT) {
    if (parent->getTypeCode() == SBML_COMP_SUBMODEL) {
      const Submodel* parentsub = static_cast<const Submodel*>(parent);
      uniqueModels.insert(parentsub->mInstantiationOriginalURI + "::" + parentsub->getModelRef());
      if (parentURI=="") {
        parentURI=parentsub->mInstantiationOriginalURI;
      }
    }
    if (parent->getTypeCode() == SBML_MODEL ||
      parent->getTypeCode() == SBML_COMP_MODELDEFINITION)
    {
      if (parentmodelname == "") {
        parentmodelname = parent->getId();
      }
    }
    rootdoc = parent->getSBMLDocument();
    parent = parent->getParentSBMLObject();
  }

  if (mInstantiatedModel != NULL) 
  {
    delete mInstantiatedModel;
    mInstantiatedModel = NULL;
    mInstantiationOriginalURI.clear();
  }

  if (!hasRequiredAttributes()) {
    string error = "Instantiation error in Submodel::instantiate:  ";
    if (!isSetId()) {
      error += "A submodel in model '" + getParentModel(this)->getId() + "' does not have an 'id' attribute.";
    }
    else if (!isSetModelRef()) {
      error += "The submodel '" + getId() + "' does not have a 'modelRef' attribute.";
    }
    rootdoc->getErrorLog()->logPackageError("comp", CompSubmodelAllowedAttributes, getPackageVersion(), getLevel(), getVersion(), error, getLine(), getColumn());
    return LIBSBML_INVALID_OBJECT;
  }

  SBase* origmodel = docplugin->getModel(getModelRef());
  
  if (origmodel==NULL) {
    string error = "In Submodel::instantiate, unable to instantiate submodel '" + getId() + "' because the referenced model ('" + getModelRef() +"') does not exist.";
    rootdoc->getErrorLog()->logPackageError("comp", CompSubmodelMustReferenceModel, getPackageVersion(), getLevel(), getVersion(), error, getLine(), getColumn());
    return LIBSBML_INVALID_OBJECT;
  }
  ExternalModelDefinition* extmod;
  SBMLDocument* origdoc = NULL;
  string newmodel = parentURI + "::" + getModelRef();
  
  set<pair<string, string> > parents;
  switch(origmodel->getTypeCode()) 
  {
  case SBML_MODEL:
  case SBML_COMP_MODELDEFINITION:
    origdoc = origmodel->getSBMLDocument();
    mInstantiatedModel = static_cast<Model*>(origmodel)->clone();
    if (uniqueModels.insert(newmodel).second == false) {
      //Can't instantiate this model, because we are already a child of it.
      string error = "Error in Submodel::instantiate:  cannot instantiate submodel '" + getId() + "' in model '" + parentmodelname + "' because it references the model '" + getModelRef() + "', which is already an ancestor of the submodel.";
      rootdoc->getErrorLog()->logPackageError("comp", CompSubmodelCannotReferenceSelf, getPackageVersion(), getLevel(), getVersion(), error, getLine(), getColumn());
      return LIBSBML_OPERATION_FAILED;
    }
    mInstantiationOriginalURI = parentURI;
    break;
  case SBML_COMP_EXTERNALMODELDEFINITION:
    extmod = static_cast<ExternalModelDefinition*>(origmodel);
    if (extmod==NULL) 
    {
      //No error message:  it should be impossible, if origmodel has the type code 'external model definition', for it to not be castable to an external model definition.
      mInstantiatedModel = NULL;
      mInstantiationOriginalURI = "";
      return LIBSBML_OPERATION_FAILED;
    }
    mInstantiatedModel = extmod->getReferencedModel(rootdoc, parents);
    if (mInstantiatedModel == NULL) 
    {
      string error = "In Submodel::instantiate, unable to instantiate submodel '" + getId() + "' because the external model definition it referenced (model '" + getModelRef() +"') could not be resolved.";
      rootdoc->getErrorLog()->logPackageError("comp", CompSubmodelMustReferenceModel, getPackageVersion(), getLevel(), getVersion(), error, getLine(), getColumn());
      mInstantiationOriginalURI = "";
      return LIBSBML_OPERATION_FAILED;
    }
    mInstantiationOriginalURI = extmod->getSource();
    origdoc = mInstantiatedModel->getSBMLDocument();
    newmodel = extmod->getSource() + "::" + getModelRef();
    if (uniqueModels.insert(newmodel).second == false) {
      //Can't instantiate this model, because we are already a child of it.
      string error = "Error in Submodel::instantiate:  cannot instantiate submodel '" + getId() + "' in model '" + parentmodelname + "' because it references the model '" + getModelRef() + "', which is already an ancestor of the submodel.";
      rootdoc->getErrorLog()->logPackageError("comp", CompSubmodelCannotReferenceSelf, getPackageVersion(), getLevel(), getVersion(), error, getLine(), getColumn());
      mInstantiatedModel = NULL;
      mInstantiationOriginalURI = "";
      return LIBSBML_OPERATION_FAILED;
    }
    mInstantiatedModel = mInstantiatedModel->clone();
    mInstantiationOriginalURI = extmod->getSource();
    break;
  default:
    //Should always be one of the above, unless someone extends one of the above and doesn't tell us.
    string error = "Instantiation error in Submodel::instantiate:  unable to parse the model '" + origmodel->getId() + "', as it was not of the type 'model' 'modelDefinition', or 'externalModelDefinition'.  The most likely cause of this situation is if some other package extended one of those three types, but the submodel code was not updated.";
    rootdoc->getErrorLog()->logPackageError("comp", CompUnresolvedReference, getPackageVersion(), getLevel(), getVersion(), error, getLine(), getColumn());
    mInstantiatedModel = NULL;
    mInstantiationOriginalURI = "";
    return LIBSBML_OPERATION_FAILED;
  }
  
  if (mInstantiatedModel==NULL) 
  {
    string error = "Instantiation error in Submodel::instantiate:  unable to create a valid copy of model '" + getModelRef() + "'.";
    rootdoc->getErrorLog()->logPackageError("comp", CompModelFlatteningFailed, getPackageVersion(), getLevel(), getVersion(), error, getLine(), getColumn());
    mInstantiationOriginalURI = "";
    return LIBSBML_OPERATION_FAILED;
  }

  mInstantiatedModel->connectToParent(this);
  mInstantiatedModel->setSBMLDocument(origdoc);
  mInstantiatedModel->enablePackage(getPackageURI(), getPrefix(), true);
  CompModelPlugin* instmodplug = 
    static_cast<CompModelPlugin*>(mInstantiatedModel->getPlugin(getPrefix()));
  if (instmodplug == NULL)
  {
    mInstantiatedModel->enablePackageInternal(getPackageURI(), getPrefix(), true);
  }

  // call all registered callbacks
  std::vector<ModelProcessingCallbackData*>::iterator it = mProcessingCBs.begin();
  while(it != mProcessingCBs.end())
  {
    ModelProcessingCallbackData* current = *it;
    int result = current->cb(mInstantiatedModel, rootdoc->getErrorLog(), current->data);
    if (result != LIBSBML_OPERATION_SUCCESS)
      return result;
    ++it;
  }

  
  CompModelPlugin* origmodplug = 
    static_cast<CompModelPlugin*>(rootdoc->getModel()->getPlugin(getPrefix()));

  instmodplug = 
    static_cast<CompModelPlugin*>(mInstantiatedModel->getPlugin(getPrefix()));
  
  if (instmodplug == NULL)
    return LIBSBML_OPERATION_SUCCESS;

  // if we have a transformer specified, then we need to propagate it, so it can
  // be used
  if (origmodplug->isSetTransformer())
  {
    if (instmodplug != NULL)
      instmodplug->setTransformer(origmodplug->getTransformer());
  }

  
  for (unsigned int sub=0; sub<instmodplug->getNumSubmodels(); sub++) 
  {
    Submodel* instsub = instmodplug->getSubmodel(sub);
    int ret = instsub->instantiate();
    if (ret != LIBSBML_OPERATION_SUCCESS) {
      //'instantiate' already sets its own error messages.
      delete mInstantiatedModel;
      mInstantiatedModel = NULL;
      mInstantiationOriginalURI = "";
      return ret;
    }
  }

  return LIBSBML_OPERATION_SUCCESS;
}
Example #30
0
void test000009::test_references_to_species()
{
  // load the CPS file
  // export to SBML
  // check the resulting SBML model
  CCopasiDataModel* pDataModel = pCOPASIDATAMODEL;
  std::istringstream iss(test000009::MODEL_STRING);
  CPPUNIT_ASSERT(load_cps_model_from_stream(iss, *pDataModel) == true);
  CPPUNIT_ASSERT(pDataModel->getModel() != NULL);
  CPPUNIT_ASSERT(pDataModel->exportSBMLToString(NULL, 2, 3).empty() == false);
  SBMLDocument* pDocument = pDataModel->getCurrentSBMLDocument();
  CPPUNIT_ASSERT(pDocument != NULL);
  Model* pModel = pDocument->getModel();
  CPPUNIT_ASSERT(pModel != NULL);
  // assert that there is only one compartment and
  // assert the compartment is constant
  CPPUNIT_ASSERT(pModel->getNumCompartments() == 1);
  Compartment* pCompartment = pModel->getCompartment(0);
  CPPUNIT_ASSERT(pCompartment->getConstant() == false);
  CPPUNIT_ASSERT(pModel->getNumSpecies() == 2);
  Species* pSpecies = pModel->getSpecies(1);
  CPPUNIT_ASSERT(pSpecies->getHasOnlySubstanceUnits() == true);
  pSpecies = pModel->getSpecies(0);
  std::string idSpeciesA = pSpecies->getId();
  CPPUNIT_ASSERT(pSpecies->getHasOnlySubstanceUnits() == true);
  CPPUNIT_ASSERT(pModel->getNumRules() == 2);
  // there are two rules, one is the rule for the compartment
  AssignmentRule* pRule = dynamic_cast<AssignmentRule*>(pModel->getRule(0));
  CPPUNIT_ASSERT(pRule != NULL);
  CPPUNIT_ASSERT(pModel->getNumParameters() == 1);
  Parameter* pParameter = pModel->getParameter(0);
  CPPUNIT_ASSERT(pParameter != NULL);

  if (pRule->getVariable() != pParameter->getId())
    {
      pRule = dynamic_cast<AssignmentRule*>(pModel->getRule(1));
    }

  CPPUNIT_ASSERT(pRule->getVariable() == pParameter->getId());
  const ASTNode* pMath = pRule->getMath();
  CPPUNIT_ASSERT(pMath != NULL);
  // the expression should be the species divided by the volume
  CPPUNIT_ASSERT(pMath->getType() == AST_DIVIDE);
  CPPUNIT_ASSERT(pMath->getChild(0) != NULL);
  CPPUNIT_ASSERT(pMath->getChild(0)->getType() == AST_NAME);
  CPPUNIT_ASSERT(pMath->getChild(0)->getName() == pSpecies->getId());
  CPPUNIT_ASSERT(pMath->getChild(1) != NULL);
  CPPUNIT_ASSERT(pMath->getChild(1)->getType() == AST_NAME);
  CPPUNIT_ASSERT(pMath->getChild(1)->getName() == pCompartment->getId());
  CPPUNIT_ASSERT(pModel->getNumReactions() == 2);
  Reaction* pReaction = pModel->getReaction(0);
  // make sure this is reaction A ->
  CPPUNIT_ASSERT(pReaction != NULL);
  CPPUNIT_ASSERT(pReaction->getNumReactants() == 1);
  CPPUNIT_ASSERT(pReaction->getNumProducts() == 0);
  // check if all references in the kinetic law are unmodified
  // math element must be a multiplication of the mass action term by
  // the compartment volume
  // the mass action term is a multiplication of the parameter node by
  // the species node
  // the code that multiplies the reaction by the compartments volume
  // recognizes the division of the species by the compartment and cancels
  // those two
  CPPUNIT_ASSERT(pReaction->isSetKineticLaw() == true);
  KineticLaw* pLaw = pReaction->getKineticLaw();
  CPPUNIT_ASSERT(pLaw != NULL);
  CPPUNIT_ASSERT(pLaw->isSetMath() == true);
  pMath = pLaw->getMath();
  CPPUNIT_ASSERT(pMath->getType() == AST_TIMES);
  CPPUNIT_ASSERT(pMath->getNumChildren() == 2);
  CPPUNIT_ASSERT(pMath->getChild(0)->getType() == AST_NAME);
  CPPUNIT_ASSERT(pMath->getChild(0)->getName() == std::string("k1"));
  CPPUNIT_ASSERT(pMath->getChild(1) != NULL);
  CPPUNIT_ASSERT(pMath->getChild(1)->getType() == AST_NAME);
  CPPUNIT_ASSERT(pMath->getChild(1)->getName() == idSpeciesA);

  pReaction = pModel->getReaction(1);
  // make sure this is reaction A -> S
  CPPUNIT_ASSERT(pReaction != NULL);
  CPPUNIT_ASSERT(pReaction->getNumReactants() == 1);
  CPPUNIT_ASSERT(pReaction->getNumProducts() == 1);
  // check if all references in the kinetic law are unmodified
  // math element must be a multiplication of the compartments volume with
  // a function call with three arguments
  // the first argument is the reference to the species
  CPPUNIT_ASSERT(pReaction->isSetKineticLaw() == true);
  pLaw = pReaction->getKineticLaw();
  CPPUNIT_ASSERT(pLaw != NULL);
  CPPUNIT_ASSERT(pLaw->isSetMath() == true);
  pMath = pLaw->getMath();
  CPPUNIT_ASSERT(pMath->getType() == AST_TIMES);
  CPPUNIT_ASSERT(pMath->getNumChildren() == 2);
  CPPUNIT_ASSERT(pMath->getChild(0)->getType() == AST_NAME);
  CPPUNIT_ASSERT(pMath->getChild(0)->getName() == pCompartment->getId());
  pMath = pMath->getChild(1);
  CPPUNIT_ASSERT(pMath != NULL);
  CPPUNIT_ASSERT(pMath->getType() == AST_FUNCTION);
  CPPUNIT_ASSERT(pMath->getNumChildren() == 3);
  pMath = pMath->getChild(0);
  CPPUNIT_ASSERT(pMath != NULL);
  CPPUNIT_ASSERT(pMath->getType() == AST_DIVIDE);
  CPPUNIT_ASSERT(pMath->getNumChildren() == 2);
  CPPUNIT_ASSERT(pMath->getChild(0) != NULL);
  CPPUNIT_ASSERT(pMath->getChild(0)->getType() == AST_NAME);
  CPPUNIT_ASSERT(pMath->getChild(0)->getName() == idSpeciesA);
  CPPUNIT_ASSERT(pMath->getChild(1) != NULL);
  CPPUNIT_ASSERT(pMath->getChild(1)->getType() == AST_NAME);
  CPPUNIT_ASSERT(pMath->getChild(1)->getName() == pCompartment->getId());
}