Ejemplo n.º 1
0
void checkComp(CompSBMLDocumentPlugin* compdoc, set<string>& components, set<string>& tests,  const map<string, vector<double> >& results)
{
  SBMLDocument* doc = compdoc->getSBMLDocument();
  List* allElements = doc->getAllElements();
  for (unsigned int e=0; e<allElements->getSize(); e++) {
    SBase* element = static_cast<SBase*>(allElements->get(e));
    ReplacedElement* re;
    Submodel* submod;
    switch(element->getTypeCode()) {
    case SBML_COMP_SUBMODEL:
      components.insert("comp:Submodel");
      submod = static_cast<Submodel*>(element);
      if (submod->isSetExtentConversionFactor()) {
        tests.insert("comp:ExtentConversionFactor");
      }
      if (submod->isSetTimeConversionFactor()) {
        tests.insert("comp:TimeConversionFactor");
      }
      break;
    case SBML_COMP_MODELDEFINITION:
      components.insert("comp:ModelDefinition");
      break;
    case SBML_COMP_EXTERNALMODELDEFINITION:
      components.insert("comp:ExternalModelDefinition");
      break;
    case SBML_COMP_SBASEREF:
      components.insert("comp:SBaseRef");
      break;
    case SBML_COMP_DELETION:
      components.insert("comp:Deletion");
      break;
    case SBML_COMP_REPLACEDELEMENT:
      components.insert("comp:ReplacedElement");
      re = static_cast<ReplacedElement*>(element);
      if (re->isSetConversionFactor()) {
        tests.insert("comp:ConversionFactor");
      }
      break;
    case SBML_COMP_REPLACEDBY:
      components.insert("comp:ReplacedBy");
      break;
    case SBML_COMP_PORT:
      components.insert("comp:Port");
      break;
    default:
      break;
    }
  }
  for (map<string, vector<double> >::const_iterator result=results.begin(); 
    result != results.end(); result++) {
      string id = result->first;
      if (id.find("__") != string::npos) {
        //It is probably a submodel element, renamed
        tests.insert("comp:SubmodelOutput");
      }
  }
}
Ejemplo n.º 2
0
int CompModelPlugin::collectDeletionsAndDeleteSome(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 attempt to perform deletions in CompModelPlugin::collectDeletionsAndDeleteSome: 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;
  }

  //Since deletions only exist in submodels, loop through the submodels.
  for (unsigned int sub=0; sub<getNumSubmodels(); sub++) {
    Submodel* submodel = getSubmodel(sub);
    //First perform any deletions
    for (unsigned int d=0; d<submodel->getNumDeletions(); d++) {
      Deletion* deletion = submodel->getDeletion(d);
      SBase* todel = deletion->getReferencedElement();
      if (todel && (todel->getTypeCode() == SBML_COMP_DELETION ||
                    todel->getTypeCode() == SBML_COMP_REPLACEDBY ||
                    todel->getTypeCode() == SBML_COMP_REPLACEDELEMENT ||
                    todel->getTypeCode() == SBML_LOCAL_PARAMETER) )
      {
        //Go ahead and delete it!
        set<SBase*> newToRemove;
        newToRemove.insert(todel);
        removeCollectedElements(removed, &newToRemove);
      }
      else {
        //Otherwise, just collect it.
        ret = deletion->collectDeletions(removed, toremove);
        if (ret!=LIBSBML_OPERATION_SUCCESS) {
          return ret;
        }
      }
    }
    //Next collect any deletions in that instantiated submodel (any that weren't just deleted)
    Model* mod = submodel->getInstantiation();
    if (mod==NULL) {
      //getInstantiation sets its own error messages.
      return LIBSBML_OPERATION_FAILED;
    }
    CompModelPlugin* modplug = static_cast<CompModelPlugin*>(mod->getPlugin(getPrefix()));
    if (modplug==NULL) {
      if (doc) {
        //Shouldn't happen:  'getInstantiation' turns on the comp plugin.
        string error = "Unable to rename elements in CompModelPlugin::collectDeletionsAndDeleteSome: no valid 'comp' plugin for the model instantiated from submodel " + submodel->getId();
        doc->getErrorLog()->logPackageError("comp", CompModelFlatteningFailed, getPackageVersion(), getLevel(), getVersion(), error);
      }
      return LIBSBML_OPERATION_FAILED;
    }
    modplug->collectDeletionsAndDeleteSome(removed, toremove);
  }
  return ret;
}
Ejemplo n.º 3
0
SBase* 
ReplacedElement::getReferencedElementFrom(Model* model)
{
  SBMLDocument* doc = getSBMLDocument();
  SBase* referent = Replacing::getReferencedElementFrom(model);
  if (referent != NULL) return referent;
  if (!isSetDeletion()) {
    //In this case, something else went wrong in getReferencedElementFrom, which will have set its own error message.
    return NULL;
  }
  model = getParentModel(this);
  if (model==NULL) {
    if (doc) {
      string error = "In ReplacedElement::getReferencedElementFrom, unable to find referenced deletion '" + getDeletion() + "' for <replacedElement>: no parent model could be found.";
      doc->getErrorLog()->logPackageError("comp", CompModelFlatteningFailed, getPackageVersion(), getLevel(), getVersion(), error, getLine(), getColumn());
    }
    return NULL;
  }
  CompModelPlugin* mplugin = static_cast<CompModelPlugin*>(model->getPlugin(getPrefix()));
  if (mplugin==NULL) {
    if (doc) {
      string error = "In ReplacedElement::getReferencedElementFrom, unable to find referenced deletion '" + getDeletion() + "' for <replacedElement>: no 'comp' plugin for the parent model could be found.";
      doc->getErrorLog()->logPackageError("comp", CompModelFlatteningFailed, getPackageVersion(), getLevel(), getVersion(), error, getLine(), getColumn());
    }
    return NULL;
  }
  Submodel* submod = mplugin->getSubmodel(getSubmodelRef());
  if (submod==NULL) {
    if (doc) {
      string error = "In ReplacedElement::getReferencedElementFrom, unable to find referenced deletion '" + getDeletion() + "' for <replacedElement>: no such submodel '" + getSubmodelRef() + "'.";
      doc->getErrorLog()->logPackageError("comp", CompReplacedElementSubModelRef, getPackageVersion(), getLevel(), getVersion(), error, getLine(), getColumn());
    }
    return NULL;
  }
  SBase* ret = submod->getDeletion(getDeletion());
  if (ret==NULL && doc) {
    string error = "In ReplacedElement::getReferencedElementFrom, unable to find referenced deletion '" + getDeletion() + "' for <replacedElement>: no deletion with that ID exists in the model.";
    doc->getErrorLog()->logPackageError("comp", CompDeletionMustReferenceObject, getPackageVersion(), getLevel(), getVersion(), error, getLine(), getColumn());
  }
  return ret;
}
Ejemplo n.º 4
0
/*
 * Loop through all Submodels in this Model, instantiate all of them, 
 * perform all deletions, and synchronize all replacements.  
 * The resulting models are stored in the Submodel objects, 
 * and available from 'Submodel::getInstantiation()'
 */
int 
CompModelPlugin::instantiateSubmodels()
{
  Model* model = static_cast<Model*>(getParentSBMLObject());
  
  if (model==NULL) 
    return LIBSBML_INVALID_OBJECT;
  
  int ret;

  // First we instantiate all the submodels.  
  // This acts recursively downward through the stack.
  for (unsigned int sub=0; sub<mListOfSubmodels.size(); sub++) 
  {
    Submodel* submodel = mListOfSubmodels.get(sub);
    // Instead of 'instantiate', since we might have already 
    // been instantiated ourselves from above.
    Model* submodinst = submodel->getInstantiation(); 
    
    if (submodinst == NULL ) {
      //'getInstantiation' already sets any errors that might have occurred.
      return LIBSBML_OPERATION_FAILED;
    }
    
    //// if we have a transformer specified, then we need to propagate it, so it can
    //// be used

    // this needs to happen in Submodel:instantiate

    //if (isSetTransformer())
    //{
    //  CompModelPlugin* other = dynamic_cast<CompModelPlugin*>(submodinst->getPlugin("comp"));
    //  if (other != NULL)
    //    other->setTransformer(getTransformer());
    //}
  }

  // Next, recursively find all the targets of SBaseRef elements 
  // and save them, since we're about to rename everything and 
  // we won't be able to find things by name any more.
  ret = saveAllReferencedElements(); 
  if (ret != LIBSBML_OPERATION_SUCCESS) {
    //saveAllReferencedElements sets any errors.
    return ret;
  }

  mRemoved.clear();
  set<SBase*> toremove;

  // Collect deletions (top-down):  
  // need to do this before renaming in case we delete a local parameter.
  ret = collectDeletionsAndDeleteSome(&mRemoved, &toremove);

  if (ret != LIBSBML_OPERATION_SUCCESS) {
    return ret;
  }

  //Next, we rename *all* the elements so everything is unique.
  ret = renameAllIDsAndPrepend("");
  if (ret != LIBSBML_OPERATION_SUCCESS) {
    return ret;
  }

  //Perform replacements and conversions (top-down) and collect them.
  ret = collectRenameAndConvertReplacements(&mRemoved, &toremove);

  if (ret != LIBSBML_OPERATION_SUCCESS) {
    return ret;
  }

  //Finally, actually remove the collected elements from the model--they are
  // all now redundant.  Have to wait until now to do this, because of the
  // possibility of nested constructs:  replacing the child of a replaced
  // element, for example, or even replacing the child of a deleted
  // element.
  removeCollectedElements(&mRemoved, &toremove);

  mRemoved.clear();

  return LIBSBML_OPERATION_SUCCESS;
}
Ejemplo n.º 5
0
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;
}
Ejemplo n.º 6
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.";
      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;
}
Ejemplo n.º 7
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;
}
Ejemplo n.º 8
0
int Submodel::convertTimeAndExtentWith(const ASTNode* tcf, const ASTNode* xcf, const ASTNode* klmod)
{
  if (tcf==NULL && xcf==NULL) return LIBSBML_OPERATION_SUCCESS;
  Model* model = getInstantiation();
  if (model==NULL) {
    //getInstantiation sets its own error messages.
    return LIBSBML_OPERATION_FAILED;
  }
  ASTNode tcftimes(AST_TIMES);
  ASTNode tcfdiv(AST_DIVIDE);
  if (tcf != NULL) {
    tcftimes.addChild(tcf->deepCopy());
    tcfdiv.addChild(tcf->deepCopy());
  }
  ASTNode rxndivide(AST_DIVIDE);
  if (klmod != NULL) {
    ASTNode rxnref(AST_NAME);
    rxndivide.addChild(rxnref.deepCopy());
    rxndivide.addChild(klmod->deepCopy());
  }
  List* allElements = model->getAllElements();
  for (ListIterator iter = allElements->begin(); iter != allElements->end(); ++iter)
  {
    SBase* element = static_cast<SBase*>(*iter);
    assert(element != NULL);
    ASTNode* ast1 = NULL;
    ASTNode* ast2 = NULL;
    Constraint* constraint = NULL;
    Delay* delay = NULL;
    EventAssignment* ea = NULL;
    InitialAssignment* ia = NULL;
    KineticLaw* kl = NULL;
    Priority* priority = NULL;
    RateRule* rrule = NULL;
    Rule* rule = NULL;
    Submodel* submodel = NULL;
    Trigger* trigger = NULL;
    string cf = "";
    //Reaction math will be converted below, in the bits with the kinetic law.  But because of that, we need to handle references *to* the reaction:  even if it has no kinetic law, the units have changed, and this needs to be reflected by the flattening routine.
    if (rxndivide.getNumChildren() != 0 && element->getTypeCode()==SBML_REACTION && element->isSetId()) {
      rxndivide.getChild(0)->setName(element->getId().c_str());
      for (ListIterator iter = allElements->begin(); iter != allElements->end(); ++iter)
      {
        SBase* subelement = static_cast<SBase*>(*iter);
        subelement->replaceSIDWithFunction(element->getId(), &rxndivide);
      }
    }

    //Submodels need their timeConversionFactor and extentConversionFactor attributes converted.  We're moving top-down, so all we need to do here is fix the conversion factor attributes themselves, pointing them to new parameters if need be.
    if ((tcf !=NULL || xcf != NULL) && element->getTypeCode()==SBML_COMP_SUBMODEL) {
      submodel = static_cast<Submodel*>(element);
      if (tcf != NULL) {
        if (submodel->isSetTimeConversionFactor()) {
          createNewConversionFactor(cf, tcf, submodel->getTimeConversionFactor(), model);
          submodel->setTimeConversionFactor(cf);
        }
        else {
          submodel->setTimeConversionFactor(tcf->getName());
        }
      }
      if (xcf != NULL) {
        if (submodel->isSetExtentConversionFactor()) {
          createNewConversionFactor(cf, xcf, submodel->getExtentConversionFactor(), model);
          submodel->setExtentConversionFactor(cf);
        }
        else {
          submodel->setExtentConversionFactor(xcf->getName());
        }
      }
    }
    if (tcf==NULL) {
      if (klmod !=NULL && element->getTypeCode()==SBML_KINETIC_LAW) {
        kl = static_cast<KineticLaw*>(element);
        if (kl->isSetMath()) {
          ast1 = new ASTNode(AST_TIMES);
          ast1->addChild(klmod->deepCopy());
          ast1->addChild(kl->getMath()->deepCopy());
          kl->setMath(ast1);
          delete ast1;
        }
      }
    }
    else {
      // All math 'time' and 'delay' csymbols must still be converted.
      // Also, several constructs are modified directly.
      switch(element->getTypeCode()) {
        //This would be a WHOLE LOT SIMPLER if there was a 'hasMath' class in libsbml.  But even so, it would have to
        // handle the kinetic laws, rate rules, and delays separately.
      case SBML_KINETIC_LAW:
        //Kinetic laws are multiplied by 'klmod'.
        kl = static_cast<KineticLaw*>(element);
        ast1 = kl->getMath()->deepCopy();
        convertCSymbols(ast1, &tcfdiv, &tcftimes);
        if (klmod !=NULL) {
          kl = static_cast<KineticLaw*>(element);
          if (kl->isSetMath()) {
            ast2 = new ASTNode(AST_TIMES);
            ast2->addChild(klmod->deepCopy());
            ast2->addChild(ast1);
            kl->setMath(ast2);
            delete ast2;
          }
        }
        else {
          kl->setMath(ast1);
          delete ast1;
        }
        break;
      case SBML_DELAY:
        //Delays are multiplied by the time conversion factor.
        delay = static_cast<Delay*>(element);
        if (delay->isSetMath()) {
          ast1 = delay->getMath()->deepCopy();
          convertCSymbols(ast1, &tcfdiv, &tcftimes);
          tcftimes.addChild(ast1);
          delay->setMath(&tcftimes);
          tcftimes.removeChild(1);
          delete ast1;
        }
        break;
      case SBML_RATE_RULE:
        //Rate rules are divided by the time conversion factor.
        rrule = static_cast<RateRule*>(element);
        if (rrule->isSetMath()) {
          ast1 = rrule->getMath()->deepCopy();
          tcfdiv.insertChild(0, ast1);
          rrule->setMath(&tcfdiv);
          tcfdiv.removeChild(0);
          delete ast1;
        }
        //Fall through to:
      case SBML_ASSIGNMENT_RULE:
      case SBML_ALGEBRAIC_RULE:
        //Rules in general need csymbols converted.
        rule = static_cast<Rule*>(element);
        if (rule->isSetMath()) {
          ast1 = rule->getMath()->deepCopy();
          convertCSymbols(ast1, &tcfdiv, &tcftimes);
          rule->setMath(ast1);
          delete ast1;
        }
        break;
      case SBML_EVENT_ASSIGNMENT:
        //Event assignments need csymbols converted.
        ea = static_cast<EventAssignment*>(element);
        if (ea->isSetMath()) {
          ast1 = ea->getMath()->deepCopy();
          convertCSymbols(ast1, &tcfdiv, &tcftimes);
          ea->setMath(ast1);
          delete ast1;
        }
        break;
      case SBML_INITIAL_ASSIGNMENT:
        //Initial assignments need csymbols converted.
        ia = static_cast<InitialAssignment*>(element);
        if (ia->isSetMath()) {
          ast1 = ia->getMath()->deepCopy();
          convertCSymbols(ast1, &tcfdiv, &tcftimes);
          ia->setMath(ast1);
          delete ast1;
        }
        break;
      case SBML_CONSTRAINT:
        //Constraints need csymbols converted.
        constraint = static_cast<Constraint*>(element);
        if (constraint->isSetMath()) {
          ast1 = constraint->getMath()->deepCopy();
          convertCSymbols(ast1, &tcfdiv, &tcftimes);
          constraint->setMath(ast1);
          delete ast1;
        }
        break;
      case SBML_PRIORITY:
        //Priorities need csymbols converted.
        priority = static_cast<Priority*>(element);
        if (priority->isSetMath()) {
          ast1 = priority->getMath()->deepCopy();
          convertCSymbols(ast1, &tcfdiv, &tcftimes);
          priority->setMath(ast1);
          delete ast1;
        }
        break;
      case SBML_TRIGGER:
        //Triggers need csymbols converted.
        trigger = static_cast<Trigger*>(element);
        if (trigger->isSetMath()) {
          ast1 = trigger->getMath()->deepCopy();
          convertCSymbols(ast1, &tcfdiv, &tcftimes);
          trigger->setMath(ast1);
          delete ast1;
        }
        break;
      default:
        //Do nothing!  If we wanted to call a plugin routine, this would be the place.  The only other alternative is to #ifdef some code in here that deals with the math-containing package objects explicitly.  Which might be the best option, all told.
        break;
      }
    }
  }

  delete allElements;

  return LIBSBML_OPERATION_SUCCESS;
}
Ejemplo n.º 9
0
void
CompIdBase::checkId (const Submodel& x)
{
  if (x.isSetId()) doCheckId(x.getId(), x);
}
Ejemplo n.º 10
0
LIBSBML_CPP_NAMESPACE_USE

int main(int argc,char** argv)
{
  
  DynPkgNamespaces sbmlns;
  sbmlns.addPackageNamespace("comp", 1, "comp");

  // create the document

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

  // create the Model

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

  // create the Compartment

  Compartment* compartment = model->createCompartment();
  compartment->setId("Loc1");
  compartment->setConstant(false);
  compartment->setSize(1);
  compartment->setSpatialDimensions(2.0);

  DynCompartmentPlugin* cplugin =
    static_cast<DynCompartmentPlugin*>(compartment->getPlugin("dyn"));
  
  SpatialComponent* component = cplugin->createSpatialComponent();
  component->setSpatialIndex(DYN_SPATIALKIND_CARTESIANX);
  component->setVariable("q1_X");

  component = cplugin->createSpatialComponent();
  component->setSpatialIndex(DYN_SPATIALKIND_CARTESIANY);
  component->setVariable("q1_Y");

  CompSBasePlugin* compPlugin = 
    static_cast<CompSBasePlugin*>(compartment->getPlugin("comp"));

  ReplacedElement* relement = compPlugin->createReplacedElement();
  relement->setIdRef("C");
  relement->setSubmodelRef("GRID_1_1_cell");

  compartment = model->createCompartment();
  compartment->setId("Loc2");
  compartment->setConstant(false);
  compartment->setSize(1);
  compartment->setSpatialDimensions(2.0);

  cplugin =
    static_cast<DynCompartmentPlugin*>(compartment->getPlugin("dyn"));

  component = cplugin->createSpatialComponent();
  component->setSpatialIndex(DYN_SPATIALKIND_CARTESIANX);
  component->setVariable("q2_X");

  component = cplugin->createSpatialComponent();
  component->setSpatialIndex(DYN_SPATIALKIND_CARTESIANY);
  component->setVariable("q2_Y");

  compPlugin =
    static_cast<CompSBasePlugin*>(compartment->getPlugin("comp"));

  relement = compPlugin->createReplacedElement();
  relement->setIdRef("C");
  relement->setSubmodelRef("GRID_1_2_cell");

  compartment = model->createCompartment();
  compartment->setId("Loc3");
  compartment->setConstant(false);
  compartment->setSize(1);
  compartment->setSpatialDimensions(2.0);

  cplugin =
    static_cast<DynCompartmentPlugin*>(compartment->getPlugin("dyn"));

  component = cplugin->createSpatialComponent();
  component->setSpatialIndex(DYN_SPATIALKIND_CARTESIANX);
  component->setVariable("q3_X");

  component = cplugin->createSpatialComponent();
  component->setSpatialIndex(DYN_SPATIALKIND_CARTESIANY);
  component->setVariable("q3_Y");

  compPlugin =
    static_cast<CompSBasePlugin*>(compartment->getPlugin("comp"));

  relement = compPlugin->createReplacedElement();
  relement->setIdRef("C");
  relement->setSubmodelRef("GRID_2_1_cell");

  compartment = model->createCompartment();
  compartment->setId("Loc4");
  compartment->setConstant(false);
  compartment->setSize(1);
  compartment->setSpatialDimensions(2.0);

  cplugin =
    static_cast<DynCompartmentPlugin*>(compartment->getPlugin("dyn"));

  component = cplugin->createSpatialComponent();
  component->setSpatialIndex(DYN_SPATIALKIND_CARTESIANX);
  component->setVariable("q4_X");

  component = cplugin->createSpatialComponent();
  component->setSpatialIndex(DYN_SPATIALKIND_CARTESIANY);
  component->setVariable("q4_Y");

  compPlugin =
    static_cast<CompSBasePlugin*>(compartment->getPlugin("comp"));

  relement = compPlugin->createReplacedElement();
  relement->setIdRef("C");
  relement->setSubmodelRef("GRID_2_2_cell");

  // create Parameters

  Parameter* param = model->createParameter();
  param->initDefaults();
  param->setId("q1_X");
  param->setValue(1);

  param = model->createParameter();
  param->initDefaults();
  param->setId("q1_Y");
  param->setValue(1);

  param = model->createParameter();
  param->initDefaults();
  param->setId("q2_X");
  param->setValue(2);

  param = model->createParameter();
  param->initDefaults();
  param->setId("q2_Y");
  param->setValue(1);
  
  param = model->createParameter();
  param->initDefaults();
  param->setId("q3_X");
  param->setValue(1);

  param = model->createParameter();
  param->initDefaults();
  param->setId("q3_Y");
  param->setValue(2);

  param = model->createParameter();
  param->initDefaults();
  param->setId("q4_X");
  param->setValue(2);

  param = model->createParameter();
  param->initDefaults();
  param->setId("q4_Y");
  param->setValue(2);

  // create SubModels

  CompModelPlugin* mplugin =
    static_cast<CompModelPlugin*>(model->getPlugin("comp"));

  Submodel* submodel = mplugin->createSubmodel();
  submodel->setId("GRID_1_1_cell");
  submodel->setModelRef("Cell");

  submodel = mplugin->createSubmodel();
  submodel->setId("GRID_1_2_cell");
  submodel->setModelRef("Cell");

  submodel = mplugin->createSubmodel();
  submodel->setId("GRID_2_1_cell");
  submodel->setModelRef("Cell");

  submodel = mplugin->createSubmodel();
  submodel->setId("GRID_2_2_cell");
  submodel->setModelRef("Cell");

  // create the ModelDefinition

  CompSBMLDocumentPlugin* dplugin =
    static_cast<CompSBMLDocumentPlugin*>(document->getPlugin("comp"));
  
  ModelDefinition* mdef = dplugin->createModelDefinition();
  mdef->setId("Cell");

  compartment = mdef->createCompartment();
  compartment->initDefaults();
  compartment->setId("C");
  compartment->setSpatialDimensions(2.0);
  compartment->setSize(1.0);

  Species* species = mdef->createSpecies();
  species->setId("R");
  species->setCompartment("C");
  species->setHasOnlySubstanceUnits(false);
  species->setBoundaryCondition(false);
  species->setConstant(false);

  species = mdef->createSpecies();
  species->setId("S");
  species->setCompartment("C");
  species->setHasOnlySubstanceUnits(false);
  species->setBoundaryCondition(false);
  species->setConstant(false);

  Reaction* reaction = mdef->createReaction();
  reaction->setId("Degradation_R");
  reaction->setReversible(false);
  reaction->setFast(false);
  reaction->setCompartment("C");

  SpeciesReference* reactant = reaction->createReactant();  
  reactant->setSpecies("R");
  reactant->setStoichiometry(1);
  reactant->setConstant(true);
  
  reaction = mdef->createReaction();
  reaction->setId("Degradation_S");
  reaction->setReversible(false);
  reaction->setFast(false);
  reaction->setCompartment("C");

  reactant = reaction->createReactant();
  reactant->setSpecies("S");
  reactant->setStoichiometry(1);
  reactant->setConstant(true);
  document->checkConsistency();

  Event* event = mdef->createEvent();
  event->setId("event0");
  event->setUseValuesFromTriggerTime(false);

  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#CellDivision");

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

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

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

}
Ejemplo n.º 11
0
SBase* 
SBaseRef::getReferencedElementFrom(Model* model)
{
  SBMLDocument* doc = getSBMLDocument();
  if (!hasRequiredAttributes()) {
    if (doc) {
      string error = "In SBaseRef::getReferencedElementFrom, unable to find referenced element from <" + getElementName() + "> ";
      if (isSetId()) {
        error += "with ID '" + getId() + "' ";
      }
      error += "as it does not have the required attributes.";
      int en = CompSBaseRefMustReferenceObject;
      switch(getTypeCode()) {
      case SBML_COMP_REPLACEDBY:
        en = CompReplacedByAllowedAttributes;
        break;
      case SBML_COMP_REPLACEDELEMENT:
        en = CompReplacedElementAllowedAttributes;
        break;
      case SBML_COMP_PORT:
        en = CompPortAllowedAttributes;
        break;
      case SBML_COMP_DELETION:
        en = CompDeletionAllowedAttributes;
      }
      doc->getErrorLog()->logPackageError("comp", en, getPackageVersion(), getLevel(), getVersion(), error, getLine(), getColumn());
    }
    return NULL;
  }
  SBase* referent = NULL;
  if (isSetPortRef()) {
    CompModelPlugin* mplugin = static_cast<CompModelPlugin*>(model->getPlugin(getPrefix()));
    Port* port = mplugin->getPort(getPortRef());
    if (port==NULL) {
      if (doc) {
        string error = "In SBaseRef::getReferencedElementFrom, unable to find referenced element from SBase reference ";
        if (isSetId()) {
          error += "'" + getId() + "' ";
        }
        error += "as the port it references ('" + getPortRef() +"') could not be found.";
        doc->getErrorLog()->logPackageError("comp", CompPortRefMustReferencePort, getPackageVersion(), getLevel(), getVersion(), error, getLine(), getColumn());
      }
      return NULL;
    }
    mDirectReference = port;
    referent = port->getReferencedElementFrom(model);
  }
  else if (isSetIdRef()) {
    referent = model->getElementBySId(getIdRef());
    if (referent == NULL && doc) {
      string error = "In SBaseRef::getReferencedElementFrom, unable to find referenced element: no such SId in the model: '" + getIdRef() + "'.";
      if (doc->getErrorLog()->contains(UnrequiredPackagePresent) 
        || doc->getErrorLog()->contains(RequiredPackagePresent))
      {
        doc->getErrorLog()->logPackageError("comp", 
          CompIdRefMayReferenceUnknownPackage, getPackageVersion(), 
          getLevel(), getVersion(), error, getLine(), getColumn());
      }
      else
      {
        doc->getErrorLog()->logPackageError("comp", 
          CompIdRefMustReferenceObject, getPackageVersion(), 
          getLevel(), getVersion(), error, getLine(), getColumn());
      }
    }
  }
  else if (isSetUnitRef()) {
    referent = model->getUnitDefinition(getUnitRef());
    if (referent == NULL && doc) {
      string error = "In SBaseRef::getReferencedElementFrom, unable to find referenced element: no such Unit in the model: '" + getUnitRef() + "'.";
      doc->getErrorLog()->logPackageError("comp", CompUnitRefMustReferenceUnitDef, getPackageVersion(), getLevel(), getVersion(), error, getLine(), getColumn());
    }
  }
  else if (isSetMetaIdRef()) {
    referent = model->getElementByMetaId(getMetaIdRef());
    if (referent == NULL && doc) {
      string error = "In SBaseRef::getReferencedElementFrom, unable to find referenced element: no such metaid in the model: '" + getMetaIdRef() + "'.";
      if (doc->getErrorLog()->contains(UnrequiredPackagePresent) 
        || doc->getErrorLog()->contains(RequiredPackagePresent))
      {
        doc->getErrorLog()->logPackageError("comp", 
          CompIdRefMayReferenceUnknownPackage, getPackageVersion(), 
          getLevel(), getVersion(), error, getLine(), getColumn());
      }
      else
      {
        doc->getErrorLog()->logPackageError("comp", 
          CompMetaIdRefMustReferenceObject, getPackageVersion(), 
          getLevel(), getVersion(), error, getLine(), getColumn());
      }
    }
  }
  else {
    //This is actually possible if the subclass overrides getNumReferents() (which some do).  In that case, we just return NULL and let the overriding function find the referent instead.
    return NULL;
  }
  if (referent == NULL) {
    //No need to set an error message--one was already set above.
    return NULL;
  }
  if (isSetSBaseRef()) {
    //We're drilling into the submodels here, so our referent must be a submodel.
    if (referent->getTypeCode() != SBML_COMP_SUBMODEL) {
      if (doc) {
        string error = "In SBaseRef::getReferencedElementFrom, unable to find referenced element: the element ";
        if (referent->isSetId()) {
          error += "'" + referent->getId() + "'";
        }
        else if (referent->isSetMetaId()) {
          error += "with the metaid '" + referent->getMetaId() + "'";
        }
        error += " is not a submodel, and therefore has no subobjects for the child <sBaseRef> to refer to.";
        doc->getErrorLog()->logPackageError("comp", CompParentOfSBRefChildMustBeSubmodel, getPackageVersion(), getLevel(), getVersion(), error, getLine(), getColumn());
      }
      return NULL;
    }
    Submodel* subm = static_cast<Submodel*>(referent);
    if (subm==NULL) {
      //Note:  should be impossible.
      if (doc) {
        string error = "In SBaseRef::getReferencedElementFrom, unable to find referenced element: the element ";
        if (referent->isSetId()) {
          error += "'" + referent->getId() + "' ";
        }
        else if (referent->isSetMetaId()) {
          error += "with the metaid '" + referent->getMetaId() + "' ";
        }
        error += "claims to be a Submodel, but could not be programmatically turned into one.";
        doc->getErrorLog()->logPackageError("comp", CompParentOfSBRefChildMustBeSubmodel, getPackageVersion(), getLevel(), getVersion(), error, getLine(), getColumn());
      }
      return NULL;
    }
    Model* inst = subm->getInstantiation();
    if (inst==NULL) {
      //No need to set an additional error, as 'getInstantiation' will set one itself.
      return NULL;
    }
    //Recursive, so will set its own error messages:
    referent = getSBaseRef()->getReferencedElementFrom(inst);
    mDirectReference = getSBaseRef()->getDirectReference();
  }
  return referent;
}