Ejemplo n.º 1
0
bool CODEExporterC::exportKineticFunctionGroup(const CModel* copasiModel)
{
  const CCopasiVector< CReaction > & reacs = copasiModel->getReactions();
  size_t size = reacs.size();
  CReaction* reac;

  std::set<std::string> isExported;

  size_t i;

  for (i = 0; i < size; ++i)
    {
      reac = reacs[i];
      const CFunction* func = reac->getFunction();

      if (func->getRoot())
        findFunctionsCalls(func->getRoot(), isExported);

      if (func->getType() != CEvaluationTree::MassAction)
        {
          if (!exportSingleFunction(func, isExported)) return false;
        }
    }

  return true;
}
Ejemplo n.º 2
0
// virtual
CXMLHandler * ReactionGlyphHandler::processStart(const XML_Char * pszName,
    const XML_Char ** papszAttrs)
{
  CXMLHandler * pHandlerToCall = NULL;

  switch (mCurrentElement.first)
    {
      case ReactionGlyph:
      {
        //workload
        const char * key;
        const char * name;
        const char * reaction;
        key = mpParser->getAttributeValue("key", papszAttrs);
        name = mpParser->getAttributeValue("name", papszAttrs);
        reaction = mpParser->getAttributeValue("reaction", papszAttrs, false);

        mpData->pReactionGlyph = new CLReactionGlyph(name);
        const char * objectRole = mpParser->getAttributeValue("objectRole", papszAttrs, false);

        if (objectRole != NULL && objectRole[0] != 0)
          {
            mpData->pReactionGlyph->setObjectRole(objectRole);
          }

        if (reaction && reaction[0])
          {
            CReaction * pReaction = dynamic_cast< CReaction * >(mpData->mKeyMap.get(reaction));

            if (!pReaction)
              {
                CCopasiMessage(CCopasiMessage::WARNING, MCXML + 19, "ReactionGlyph" , key);
              }
            else
              {
                mpData->pReactionGlyph->setModelObjectKey(pReaction->getKey());
              }
          }

        mpData->pCurrentLayout->addReactionGlyph(mpData->pReactionGlyph);
        addFix(key, mpData->pReactionGlyph);
      }
      break;

      case BoundingBox:
      case Curve:
      case ListOfMetaboliteReferenceGlyphs:
        pHandlerToCall = getHandler(mCurrentElement.second);
        break;

      default:
        CCopasiMessage(CCopasiMessage::EXCEPTION, MCXML + 2,
                       mpParser->getCurrentLineNumber(), mpParser->getCurrentColumnNumber(), pszName);
        break;
    }

  return pHandlerToCall;
}
Ejemplo n.º 3
0
void ReactionsWidget1::slotGotoFunction()
{
  CReaction * pReaction =
    dynamic_cast< CReaction * >(CCopasiRootContainer::getKeyFactory()->get(mKey));
  if (pReaction == NULL) return;
  const CFunction * pFunc = pReaction->getFunction();
  if (pFunc == NULL) return;
  
  mpListView->switchToOtherWidget(C_INVALID_INDEX, pFunc->getKey());
  
}
Ejemplo n.º 4
0
void CModelExpansion::createDiffusionReaction(const std::string & name,
    const std::string & metabkey1, const std::string & metabkey2,
    const std::string & parameterkey)
{
  //try creating the object until we find a name that is not yet used
  CReaction* newObj;
  std::ostringstream name_;
  name_ << name;

  do
    {
      newObj = mpModel->createReaction(name_.str());
      name_ << "_";
    }
  while (!newObj);

  newObj->setReversible(true);
  newObj->addSubstrate(metabkey1, 1);
  newObj->addProduct(metabkey2, 1);
  newObj->setFunction("Mass action (reversible)");
  newObj->addParameterMapping("substrate", metabkey1);
  newObj->addParameterMapping("product", metabkey2);
  newObj->setParameterMapping(0, parameterkey);
  newObj->setParameterMapping(2, parameterkey);
}
Ejemplo n.º 5
0
void UndoDependentData::restoreDependentObjects(CModel *pModel, QList<UndoReactionData *> *reactionData)
{
  if (pModel == NULL || reactionData == NULL || reactionData->empty())
    return;

  QList <UndoReactionData *>::const_iterator j;

  for (j = reactionData->begin(); j != reactionData->end(); ++j)
    {

      UndoReactionData * rData = *j;

      //need to make sure reaction doesn't exist in the model already
      if (pModel->getReactions().getIndex(rData->getName()) != C_INVALID_INDEX)
        continue;

      CReaction *pRea = rData->restoreObjectIn(pModel);

      rData->restoreDependentObjects(pModel);

      updateGUI(ListViews::REACTION, ListViews::ADD, pRea->getKey());
    }
}
Ejemplo n.º 6
0
// Just added 5/18/04
void ReactionsWidget1::slotBtnDelete()
{
  assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
  CCopasiDataModel* pDataModel = (*CCopasiRootContainer::getDatamodelList())[0];
  assert(pDataModel != NULL);
  CModel * pModel = pDataModel->getModel();

  if (pModel == NULL)
    return;

  CReaction * pReaction =
    dynamic_cast< CReaction * >(CCopasiRootContainer::getKeyFactory()->get(mKey));

  if (pReaction == NULL) return;

  QMessageBox::StandardButton choice =
    CQMessageBox::confirmDelete(NULL, "reaction",
                                FROM_UTF8(pReaction->getObjectName()),
                                pReaction->getDeletedObjects());

  switch (choice)
    {
      case QMessageBox::Ok:                                                     // Yes or Enter
      {
        pDataModel->getModel()->removeReaction(mKey);

        mpRi->setFunctionWithEmptyMapping("");

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

      default:                                                     // No or Escape
        break;
    }
}
Ejemplo n.º 7
0
// return pointer on AnimatedSprite object. Create and load data it if not existing yet
// TBD Cleanup is required for died entities...
CAnimatedSprite* CBiotopDisplayGL::GetAnimatedSprite(CBasicEntity* pEntity)
{
  int nDirection, nPosition, nLifeStages, nActions;
  switch (pEntity->getClass())
  {
  case CLASS_MAMMAL:
  case CLASS_REPTILE:
  case CLASS_ARTHROPOD:
  case CLASS_AVE:
    {
      nDirection  = 8;
      nPosition   = 5;
      nLifeStages = 1;
      nActions    = pEntity->getBrain()->GetNumberReaction();
      break;
    }
  case CLASS_SPERMATOPHYTA:
    {
      nDirection  = 1;
      nPosition   = 1;
      nLifeStages = 1;
      nActions    = 1;
      break;
    }
  default:
    {
      nDirection  = 1;
      nPosition   = 1;
      nLifeStages = 1;
      nActions    = 1;
      break;
    }
  }

  // Check if data already loaded
  for (int i=0; i<m_tAnimatedSprite.GetSize(); i++)
  { 
    if ( ( pEntity->getGenome()->getSpecieName().c_str() == m_tAnimatedSprite.GetAt(i)->GetSpriteName() ) 
       &&( nActions == m_tAnimatedSprite.GetAt(i)->GetNbActions() ) )
    {
      // Sprite already exist
      return ( m_tAnimatedSprite.GetAt(i) );
    }
  }

  // Create new sprite
  CAnimatedSprite* pNewSprite = new CAnimatedSprite(pEntity->getGenome()->getSpecieName().c_str(),
                                                    nDirection,nPosition,nLifeStages,nActions,
                                                    m_appBindTexArray[SELECT_ID]);
  
  CString dataDirName;
  CString ageString = _T("\\Age0\\");

  // TBD : loop also on life stages
  for (int idAct=0; idAct<nActions; idAct++)
  {
    if (pEntity->getBrain() != NULL)
    {
      CReaction* pReac = pEntity->getBrain()->GetReactionByIndex(idAct);
      CString strReac;
      {
        strReac = pReac->GetLabel().c_str();
      }

      dataDirName = pEntity->getFormStrName(pEntity->getForm()).c_str() + ageString + strReac;
    }
    else
    {
      //dataDirName = pEntity->getGenome()->getSpecieName().c_str() + ageString + "Data";
      dataDirName = pEntity->getFormStrName(pEntity->getForm()).c_str() + ageString + "Data";
    }

    pNewSprite->LoadData(dataDirName,0,idAct);
    pNewSprite->SetZoomFactor(m_ZoomFactor);
  }
  
  if (pNewSprite != NULL)
    m_tAnimatedSprite.Add(pNewSprite);

  return (pNewSprite);

}
Ejemplo n.º 8
0
bool CODEExporterC::exportTitleData(const CModel* copasiModel, std::ostream & os)
{

  size_t metab_size = copasiModel->getMetabolitesX().size();
  size_t indep_size = copasiModel->getNumIndependentReactionMetabs();
  size_t ode_size = copasiModel->getNumODEMetabs();
  size_t comps_size = copasiModel->getCompartments().size();
  size_t modvals_size = copasiModel->getModelValues().size();
  size_t reacs_size = copasiModel->getReactions().size();

  size_t i, j, num_params, count;
  const CCopasiVector< CReaction > & reacs = copasiModel->getReactions();
  CReaction* reac;

  count = 0;

  for (i = 0; i < reacs_size; ++i)
    {

      reac = reacs[i];
      num_params = reac->getParameters().size();

      for (j = 0; j < num_params; ++j)
        {
          if (reac->isLocalParameter(j))
            ++count;
        }
    }

  size_t numX = 0;
  size_t numY = 0;
  size_t numXC = 0;
  size_t numYC = 0;
  size_t numPC = 0;
  size_t numP = 0;
  size_t numDX = 0;
  size_t numCT = 0;

  std::ostringstream p_names;  p_names  << "const char* p_names[] = {";
  std::ostringstream x_names;  x_names  << "const char* x_names[] = {";
  std::ostringstream y_names;  y_names  << "const char* y_names[] = {";
  std::ostringstream xc_names; xc_names << "const char* xc_names[] = {";
  std::ostringstream pc_names; pc_names << "const char* pc_names[] = {";
  std::ostringstream yc_names; yc_names << "const char* yc_names[] = {";
  std::ostringstream dx_names; dx_names << "const char* dx_names[] = {";
  std::ostringstream ct_names; ct_names << "const char* ct_names[] = {";

  CKeyFactory* kf = CCopasiRootContainer::getKeyFactory();

  std::map< std::string, std::string >::const_iterator it = NameMap.begin();
  std::map< std::string, std::string > reverse_map;

  while (it != NameMap.end())
    {
      const std::string& abbrev = it->second;
      const std::string& key = it->first;

      if (startsWith(abbrev, "p["))
        {
          reverse_map[abbrev] = key;
          ++numP;
        }
      else if (startsWith(abbrev, "x["))
        {
          reverse_map[abbrev] = key;
          ++numX;
        }
      else if (startsWith(abbrev, "y["))
        {
          reverse_map[abbrev] = key;
          ++numY;
        }
      else if (startsWith(abbrev, "dx["))
        {
          reverse_map[abbrev] = key;
          ++numDX;
        }
      else if (startsWith(abbrev, "ct["))
        {
          reverse_map[abbrev] = key;
          ++numCT;
        }
      else if (startsWith(abbrev, "x_c["))
        {
          CCopasiObject* obj = kf->get(key);

          if (obj != NULL)
            {
              reverse_map[abbrev] = obj->getObjectName();
            }
          else
            {
              reverse_map[abbrev] = key;
            }

          ++numXC;
        }
      else if (startsWith(abbrev, "p_c["))
        {
          CCopasiObject* obj = kf->get(key);

          if (obj != NULL)
            {
              reverse_map[abbrev] = obj->getObjectName();
            }
          else
            {
              reverse_map[abbrev] = key;
            }

          ++numPC;
        }
      else if (startsWith(abbrev, "y_c["))
        {
          CCopasiObject* obj = kf->get(key);

          if (obj != NULL)
            {
              reverse_map[abbrev] = obj->getObjectName();
            }
          else
            {
              reverse_map[abbrev] = key;
            }

          ++numYC;
        }

      ++it;
    }

  for (size_t i = 0; i < numP; ++i)
    {
      std::stringstream str; str << "p[" << i << "]";
      printNameForKey(p_names, kf, reverse_map[str.str()]);
    }

  for (size_t i = 0; i < numX; ++i)
    {
      std::stringstream str; str << "x[" << i << "]";
      printNameForKey(x_names, kf, reverse_map[str.str()]);
    }

  for (size_t i = 0; i < numY; ++i)
    {
      std::stringstream str; str << "y[" << i << "]";
      printNameForKey(y_names, kf, reverse_map[str.str()]);
    }

  for (size_t i = 0; i < numDX; ++i)
    {
      std::stringstream str; str << "dx[" << i << "]";
      printNameForKey(dx_names, kf, reverse_map[str.str()]);
    }

  for (size_t i = 0; i < numCT; ++i)
    {
      std::stringstream str; str << "ct[" << i << "]";
      printNameForKey(ct_names, kf, reverse_map[str.str()]);
    }

  for (size_t i = 0; i < numXC; ++i)
    {
      std::stringstream str; str << "x_c[" << i << "]";
      xc_names << "\"" << reverse_map[str.str()] << "\", ";
    }

  for (size_t i = 0; i < numPC; ++i)
    {
      std::stringstream str; str << "p_c[" << i << "]";
      pc_names << "\"" << reverse_map[str.str()] << "\", ";
    }

  for (size_t i = 0; i < numYC; ++i)
    {
      std::stringstream str; str << "y_c[" << i << "]";
      yc_names << "\"" << reverse_map[str.str()] << "\", ";
    }

  os << "#ifdef SIZE_DEFINITIONS" << std::endl;
  os << "#define N_METABS " << metab_size << std::endl;
  os << "#define N_ODE_METABS " << ode_size << std::endl;
  os << "#define N_INDEP_METABS " << indep_size << std::endl;
  os << "#define N_COMPARTMENTS " << comps_size << std::endl;
  os << "#define N_GLOBAL_PARAMS " << modvals_size << std::endl;
  os << "#define N_KIN_PARAMS " << count << std::endl;
  os << "#define N_REACTIONS " << reacs_size << std::endl << std::endl;

  os << "#define N_ARRAY_SIZE_P  " << numP  << "\t// number of parameters" << std::endl;
  os << "#define N_ARRAY_SIZE_X  " << numX  << "\t// number of initials" << std::endl;
  os << "#define N_ARRAY_SIZE_Y  " << numY  << "\t// number of assigned elements" << std::endl;
  os << "#define N_ARRAY_SIZE_XC " << numXC << "\t// number of x concentration" << std::endl;
  os << "#define N_ARRAY_SIZE_PC " << numPC << "\t// number of p concentration" << std::endl;
  os << "#define N_ARRAY_SIZE_YC " << numYC << "\t// number of y concentration" << std::endl;
  os << "#define N_ARRAY_SIZE_DX " << numDX << "\t// number of ODEs " << std::endl;
  os << "#define N_ARRAY_SIZE_CT " << numCT << "\t// number of conserved totals" << std::endl << std::endl;

  os << "#endif // SIZE_DEFINITIONS" << std::endl;
  os << std::endl;

  os << "#ifdef TIME" << std::endl;
  os << "#define T  <set here a user name for the time variable> " << std::endl;
  os << "#endif // TIME" << std::endl;

  os << std::endl;
  os << "#ifdef NAME_ARRAYS" << std::endl;
  os << p_names.str()  << " \"\" };" << std::endl;
  os << x_names.str()  << " \"\" };" << std::endl;
  os << y_names.str()  << " \"\" };" << std::endl;
  os << xc_names.str() << " \"\" };" << std::endl;
  os << pc_names.str() << " \"\" };" << std::endl;
  os << yc_names.str() << " \"\" };" << std::endl;
  os << dx_names.str() << " \"\" };" << std::endl;
  os << ct_names.str() << " \"\" };" << std::endl;
  os << "#endif // NAME_ARRAYS" << std::endl;

  return true;
}
Ejemplo n.º 9
0
bool CModelMerging::mergeMetabolites(std::string toKey, std::string  key)
{

  bool info = false;

  //merge in  the relevant reactions

  size_t i, imax = mpModel->getReactions().size();
  size_t j, jmax;

  for (i = 0; i < imax; ++i)
    {
      CReaction * reac = &mpModel->getReactions()[i];

      jmax = reac->getChemEq().getSubstrates().size();

      for (j = 0; j < jmax; ++j)
        {
          CChemEqElement * subst = const_cast< CChemEqElement * >(&reac->getChemEq().getSubstrates()[j]);

          if (subst->getMetabolite()->getKey() == key)
            subst->setMetabolite(toKey);
        }

      jmax = reac->getChemEq().getProducts().size();

      for (j = 0; j < jmax; ++j)
        {
          CChemEqElement * prod = const_cast< CChemEqElement * >(&reac->getChemEq().getProducts()[j]);

          if (prod->getMetabolite()->getKey() == key)
            prod->setMetabolite(toKey);
        }

      jmax = reac->getChemEq().getModifiers().size();

      for (j = 0; j < jmax; ++j)
        {
          CChemEqElement * modif = const_cast< CChemEqElement * >(&reac->getChemEq().getModifiers()[j]);

          if (modif->getMetabolite()->getKey() == key)
            modif->setMetabolite(toKey);
        }

      //change parameters of  the kinetic function

      for (j = 0; j < reac->getFunctionParameters().size(); ++j)
        {
          switch (reac->getFunctionParameters()[j]->getUsage())
            {
              case CFunctionParameter::SUBSTRATE:
              case CFunctionParameter::PRODUCT:
              case CFunctionParameter::MODIFIER:
                //translate the metab keys
              {

                //we assume that only SUBSTRATE, PRODUCT, MODIFIER can be vectors

                size_t k, kmax = reac->getParameterMappings()[j].size();

                for (k = 0; k < kmax; ++k)
                  if (reac->getParameterMappings()[j][k] == key)
                    reac->getParameterMappings()[j][k] = toKey;
              }
              break;

              case CFunctionParameter::TIME:
                break;

              case CFunctionParameter::VOLUME:
                // ??? TODO : have to ask
                break;

              case CFunctionParameter::PARAMETER:
                break;

              default:
                return info;
                break;
            }
        }
    }

  imax = mpModel->getEvents().size();

  for (i = 0; i < imax; ++i)
    {
      CEvent * event = &mpModel->getEvents()[i];

      if (!event) return info;

      /* merge in  trigger expressions */
      CExpression* pExpression = event->getTriggerExpressionPtr();

      if (pExpression == NULL) return info;

      if (!mergeInExpression(toKey, key, pExpression))  return info;

      pExpression = event->getDelayExpressionPtr();

      if (pExpression)
        if (!mergeInExpression(toKey, key, pExpression))
          return info;

      jmax = event->getAssignments().size();

      for (j = 0; j < jmax; ++j)
        {
          CEventAssignment* assignment = &event->getAssignments()[j];

          if (!assignment) return info;

          std::string assignmentKey = assignment->getTargetKey();

          if (assignmentKey == key) assignment->setTargetKey(toKey);

          pExpression = assignment->getExpressionPtr();

          if (pExpression == NULL) return info;

          if (!mergeInExpression(toKey, key, pExpression))    return info;
        }
    }

  imax = mpModel->getMetabolites().size();

  for (i = 0; i < imax; ++i)
    {
      CMetab* metab = &mpModel->getMetabolites()[i];

      if (!metab) return info;

      switch (metab->getStatus())
        {
          case CModelEntity::FIXED:
          case CModelEntity::REACTIONS:

            break;

          case CModelEntity::ASSIGNMENT:

            if (!mergeInExpression(toKey, key, metab->getExpressionPtr())) return info;

            break;

          case CModelEntity::ODE:

            if (!mergeInExpression(toKey, key, metab->getExpressionPtr())) return info;

            if (metab->getInitialExpression() != "")
              if (!mergeInExpression(toKey, key, metab->getInitialExpressionPtr())) return info;

            break;

          default:
            return info;
            break;
        }
    }

  imax = mpModel->getCompartments().size();

  for (i = 0; i < imax; ++i)
    {
      CCompartment* comp = &mpModel->getCompartments()[i];

      if (!comp) return info;

      switch (comp ->getStatus())
        {
          case CModelEntity::FIXED:

            break;

          case CModelEntity::ASSIGNMENT:

            if (!mergeInExpression(toKey, key, comp->getExpressionPtr())) return info;

            break;

          case CModelEntity::ODE:

            if (!mergeInExpression(toKey, key, comp->getExpressionPtr())) return info;

            if (comp->getInitialExpression() != "")
              if (!mergeInExpression(toKey, key, comp->getInitialExpressionPtr())) return info;

            break;

          default:
            return info;
            break;
        }
    }

  imax = mpModel->getModelValues().size();

  for (i = 0; i < imax; ++i)
    {
      CModelValue* modval = &mpModel->getModelValues()[i];

      if (!modval) return info;

      switch (modval ->getStatus())
        {
          case CModelEntity::FIXED:

            break;

          case CModelEntity::ASSIGNMENT:

            if (!mergeInExpression(toKey, key, modval->getExpressionPtr())) return info;

            break;

          case CModelEntity::ODE:

            if (!mergeInExpression(toKey, key, modval->getExpressionPtr())) return info;

            if (modval->getInitialExpression() != "")
              if (!mergeInExpression(toKey, key, modval->getInitialExpressionPtr())) return info;

            break;

          default:
            return info;
            break;
        }
    }

  return true;
}
Ejemplo n.º 10
0
int main()
{
  // initialize the backend library
  // since we are not interested in the arguments
  // that are passed to main, we pass 0 and NULL to
  // init
  CCopasiRootContainer::init(0, NULL);
  assert(CCopasiRootContainer::getRoot() != NULL);
  // create a new datamodel
  CCopasiDataModel* pDataModel = CCopasiRootContainer::addDatamodel();
  assert(CCopasiRootContainer::getDatamodelList()->size() == 1);
  // get the model from the datamodel
  CModel* pModel = pDataModel->getModel();
  assert(pModel != NULL);
  // set the units for the model
  // we want seconds as the time unit
  // microliter as the volume units
  // and nanomole as the substance units
  pModel->setTimeUnit(CModel::s);
  pModel->setVolumeUnit(CModel::microl);
  pModel->setQuantityUnit(CModel::nMol);

  // we have to keep a set of all the initial values that are changed during
  // the model building process
  // They are needed after the model has been built to make sure all initial
  // values are set to the correct initial value
  std::set<const CCopasiObject*> changedObjects;

  // create a compartment with the name cell and an initial volume of 5.0
  // microliter
  CCompartment* pCompartment = pModel->createCompartment("cell", 5.0);
  const CCopasiObject* pObject = pCompartment->getValueReference();
  assert(pObject != NULL);
  changedObjects.insert(pObject);
  assert(pCompartment != NULL);
  assert(pModel->getCompartments().size() == 1);
  // create a new metabolite with the name S and an inital
  // concentration of 10 nanomol
  // the metabolite belongs to the compartment we created and is is to be
  // fixed
  CMetab* pS = pModel->createMetabolite("S", pCompartment->getObjectName(), 10.0, CMetab::FIXED);
  pObject = pS->getInitialConcentrationReference();
  assert(pObject != NULL);
  changedObjects.insert(pObject);
  assert(pCompartment != NULL);
  assert(pS != NULL);
  assert(pModel->getMetabolites().size() == 1);
  // create a second metabolite called P with an initial
  // concentration of 0. This metabolite is to be changed by reactions
  CMetab* pP = pModel->createMetabolite("P", pCompartment->getObjectName(), 0.0, CMetab::REACTIONS);
  assert(pP != NULL);
  pObject = pP->getInitialConcentrationReference();
  assert(pObject != NULL);
  changedObjects.insert(pObject);
  assert(pModel->getMetabolites().size() == 2);
  // now we create a reaction
  CReaction* pReaction = pModel->createReaction("reaction");
  assert(pReaction != NULL);
  assert(pModel->getReactions().size() == 1);
  // reaction converts S to P
  // we can set these on the chemical equation of the reaction
  CChemEq* pChemEq = &pReaction->getChemEq();
  // S is a substrate with stoichiometry 1
  pChemEq->addMetabolite(pS->getKey(), 1.0, CChemEq::SUBSTRATE);
  // P is a product with stoichiometry 1
  pChemEq->addMetabolite(pP->getKey(), 1.0, CChemEq::PRODUCT);
  assert(pChemEq->getSubstrates().size() == 1);
  assert(pChemEq->getProducts().size() == 1);
  // this reaction is to be irreversible
  pReaction->setReversible(false);
  assert(pReaction->isReversible() == false);

  CModelValue* pMV = pModel->createModelValue("K", 42.0);
  // set the status to FIXED
  pMV->setStatus(CModelValue::FIXED);
  assert(pMV != NULL);
  pObject = pMV->getInitialValueReference();
  assert(pObject != NULL);
  changedObjects.insert(pObject);
  assert(pModel->getModelValues().size() == 1);

  // now we ned to set a kinetic law on the reaction
  // for this we create a user defined function
  CFunctionDB* pFunDB = CCopasiRootContainer::getFunctionList();
  assert(pFunDB != NULL);

  CKinFunction* pFunction = new CKinFunction("My Rate Law");

  pFunDB->add(pFunction, true);
  CFunction* pRateLaw = dynamic_cast<CFunction*>(pFunDB->findFunction("My Rate Law"));

  assert(pRateLaw != NULL);

  // now we create the formula for the function and set it on the function
  std::string formula = "(1-0.4/(EXPONENTIALE^(temp-37)))*0.00001448471257*1.4^(temp-37)*substrate";

  bool result = pFunction->setInfix(formula);
  assert(result == true);
  // make the function irreversible
  pFunction->setReversible(TriFalse);
  // the formula string should have been parsed now
  // and COPASI should have determined that the formula string contained 2 parameters (temp and substrate)
  CFunctionParameters& variables = pFunction->getVariables();
  // per default the usage of those parameters will be set to VARIABLE
  size_t index = pFunction->getVariableIndex("temp");
  assert(index != C_INVALID_INDEX);
  CFunctionParameter* pParam = variables[index];
  assert(pParam->getUsage() == CFunctionParameter::VARIABLE);
  // This is correct for temp, but substrate should get the usage SUBSTRATE in order
  // for us to use the function with the reaction created above
  // So we need to set the usage for "substrate" manually
  index = pFunction->getVariableIndex("substrate");
  assert(index != C_INVALID_INDEX);
  pParam = variables[index];
  pParam->setUsage(CFunctionParameter::SUBSTRATE);

  // set the rate law for the reaction
  pReaction->setFunction(pFunction);
  assert(pReaction->getFunction() != NULL);

  // COPASI also needs to know what object it has to assocuiate with the individual function parameters
  // In our case we need to tell COPASI that substrate is to be replaced by the substrate of the reaction
  // and temp is to be replaced by the global parameter K
  pReaction->setParameterMapping("substrate", pS->getKey());
  pReaction->setParameterMapping("temp", pMV->getKey());

  // finally compile the model
  // compile needs to be done before updating all initial values for
  // the model with the refresh sequence
  pModel->compileIfNecessary(NULL);

  // now that we are done building the model, we have to make sure all
  // initial values are updated according to their dependencies
  std::vector<Refresh*> refreshes = pModel->buildInitialRefreshSequence(changedObjects);
  std::vector<Refresh*>::iterator it2 = refreshes.begin(), endit2 = refreshes.end();

  while (it2 != endit2)
    {
      // call each refresh
      (**it2)();
      ++it2;
    }

  // save the model to a COPASI file
  // we save to a file named example1.cps, we don't want a progress report
  // and we want to overwrite any existing file with the same name
  // Default tasks are automatically generated and will always appear in cps
  // file unless they are explicitley deleted before saving.
  pDataModel->saveModel("example7.cps", NULL, true);

  // export the model to an SBML file
  // we save to a file named example1.xml, we want to overwrite any
  // existing file with the same name and we want SBML L2V3
  pDataModel->exportSBML("example7.xml", true, 2, 3);

  // destroy the root container once we are done
  CCopasiRootContainer::destroy();
}
Ejemplo n.º 11
0
void CQCompartment::addCompartment(UndoCompartmentData *pSData)
{
  assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
  CCopasiDataModel* pDataModel = (*CCopasiRootContainer::getDatamodelList())[0];
  assert(pDataModel != NULL);

  CModel * pModel = pDataModel->getModel();
  assert(pModel != NULL);

  //reinsert all the Compartments
  CCompartment *pCompartment =  pModel->createCompartment(pSData->getName());
  pCompartment->setInitialValue(pSData->getInitialValue());
  pCompartment->setStatus(pSData->getStatus());
  std::string key = pCompartment->getKey();
  protectedNotify(ListViews::COMPARTMENT, ListViews::ADD, key);

  //restore all the dependencies
  //reinsert all the species
  QList <UndoSpecieData *> *pSpecieData = pSData->getSpecieDependencyObjects();
  QList <UndoSpecieData *>::const_iterator i;

  for (i = pSpecieData->begin(); i != pSpecieData->end(); ++i)
    {
      UndoSpecieData * data = *i;
      //  beginInsertRows(QModelIndex(), 1, 1);
      CMetab *pSpecie =  pModel->createMetabolite(data->getName(), data->getCompartment(), data->getIConc(), data->getStatus());
      protectedNotify(ListViews::METABOLITE, ListViews::ADD, pSpecie->getKey());
      //endInsertRows();
    }

  //reinsert the dependency reaction
  QList <UndoReactionData *> *pReactionData = pSData->getReactionDependencyObjects();
  QList <UndoReactionData *>::const_iterator j;

  for (j = pReactionData->begin(); j != pReactionData->end(); ++j)
    {

      //UndoReactionData * rData = dynamic_cast<UndoReactionData*>(*j);
      UndoReactionData * rData = *j;

      //TODO check if reaction already exist in the model, better idea may be implemented in the future
      bool exist = false;

      for (int ii = 0; ii < (int)pModel->getReactions().size(); ++ii)
        {
          if (pModel->getReactions()[ii]->getObjectName() == rData->getName())
            {
              exist = true;
              ii = ii + pModel->getReactions().size() + 1; //jump out of the loop reaction exist already
            }
          else
            {
              exist = false;
            }
        }

      if (!exist)
        {
          protectedNotify(ListViews::METABOLITE, ListViews::ADD, ""); //Refresh all dependency species.
          CReaction *pRea =  pModel->createReaction(rData->getName());
          rData->getRi()->writeBackToReaction(pRea);
          protectedNotify(ListViews::REACTION, ListViews::ADD, pRea->getKey());
        }
    }

  mpListView->switchToOtherWidget(C_INVALID_INDEX, key);
}
Ejemplo n.º 12
0
/*static*/
void CChemEqInterface::setChemEqFromString(CModel * model, CReaction & rea, const std::string & ces)
{
  CChemEqInterface cei(model);
  cei.setChemEqString(ces);
  cei.writeToChemEq(rea.getChemEq());
}
Ejemplo n.º 13
0
/*static*/
std::string CChemEqInterface::getChemEqString(CModel * model, const CReaction & rea, bool expanded)
{
  CChemEqInterface cei(model);
  cei.loadFromChemEq(rea.getChemEq());
  return cei.getChemEqString(expanded);
}
Ejemplo n.º 14
0
void CFixLocalReactionParameters::changeModel()
{
  CCopasiParameter * pParameter = NULL;
  CModelValue * pModelValue = NULL;
  CReaction * pReaction = NULL;

  std::stringstream NameStream;
  std::stringstream Message;

  std::string OldCN;
  std::string NewCNBase;
  std::string NewCN;
  std::string Infix;

  std::string::size_type Start;

  // Loop through all changes.
  std::multimap< CCopasiParameter *, const CExpression * >::const_iterator itChanges = mChanges.begin();
  std::multimap< CCopasiParameter *, const CExpression * >::const_iterator endChanges = mChanges.end();

  for (; itChanges != endChanges; ++itChanges)
    {
      if (pParameter != itChanges->first)
        {
          // We have a new parameter
          pParameter = itChanges->first;
          OldCN = "<" + pParameter->getCN() + ",Reference=";

          // Create a global quantity of type FIXED.
          std::string Name = pParameter->getObjectName();
          pReaction = static_cast< CReaction * >(pParameter->getObjectAncestor("Reaction"));
          Name += "{" + pReaction->getObjectName() + "}";

          pModelValue = mpModel->createModelValue(Name, pParameter->getValue< C_FLOAT64 >());

          // In case the created name is not unique we append _n with increasing n
          // until we succeed;
          C_INT32 index = 0;

          while (pModelValue == NULL)
            {
              NameStream.str("");
              NameStream << Name << "_" << index++;
              pModelValue = mpModel->createModelValue(NameStream.str(), pParameter->getValue< C_FLOAT64 >());
            }

          NewCNBase = "<" + pModelValue->getCN() + ",Reference=";

          // If the parameter is actually used in the reaction
          // it is changed to the global quantity.
          if (pReaction->isLocalParameter(pParameter->getObjectName()))
            pReaction->setParameterMapping(pParameter->getObjectName(), pModelValue->getKey());

          Message << "  " << pParameter->getObjectName() << " in " << pReaction->getObjectName()
                  << " is replaced by " << pModelValue->getObjectName() << std::endl;
        }

      // We need to distinguish between initial and other expressions.
      if (itChanges->second->getObjectName().compare(0, 7, "Initial") == 0)
        NewCN = NewCNBase + "Initial";
      else
        NewCN = NewCNBase;

      // Replace the OldCN of the parameter with the NewCN of global quantity in all expressions.
      Infix = itChanges->second->getInfix();

      // There may be more than one occurrence.
      Start = 0;

      while ((Start = Infix.find(OldCN), Start) != std::string::npos)
        Infix.replace(Start, OldCN.length(), NewCN);

      const_cast< CExpression * >(itChanges->second)->setInfix(Infix);
    }

  CCopasiMessage(CCopasiMessage::WARNING, MCXML + 14, Message.str().c_str());
}
Ejemplo n.º 15
0
void CModelExpansion::duplicateReaction(const CReaction* source, const std::string & index, const SetOfModelElements & sourceSet, ElementsMap & emap)
{
  //if the source object has already been duplicated: do nothing
  if (emap.exists(source))
    return;

  //try creating the object until we find a name that is not yet used
  CReaction* newObj;
  std::ostringstream infix;

  do
    {
      std::ostringstream name;
      name << source->getObjectName() << infix.str() << index;
      newObj = mpModel->createReaction(name.str());
      infix << "_";
    }
  while (!newObj);

  //add duplicated object to the map
  emap.add(source, newObj);

  //now copy the chemical equation
  size_t i;

  for (i = 0; i < source->getChemEq().getSubstrates().size(); ++i)
    {
      const CChemEqElement * sourceElement = source->getChemEq().getSubstrates()[i];
      const CMetab* pMetab = NULL;

      if (sourceSet.contains(sourceElement->getMetabolite()))
        {
          if (!emap.exists(sourceElement->getMetabolite()))
            duplicateMetab(sourceElement->getMetabolite(), index, sourceSet, emap);

          pMetab = dynamic_cast<const CMetab*>(emap.getDuplicatePtr(sourceElement->getMetabolite()));
        }
      else //add the original metab
        {
          pMetab = sourceElement->getMetabolite();
        }

      if (pMetab)
        newObj->addSubstrate(pMetab->getKey(), sourceElement->getMultiplicity());
    }

  for (i = 0; i < source->getChemEq().getProducts().size(); ++i)
    {
      const CChemEqElement * sourceElement = source->getChemEq().getProducts()[i];
      const CMetab* pMetab = NULL;

      if (sourceSet.contains(sourceElement->getMetabolite()))
        {
          if (!emap.exists(sourceElement->getMetabolite()))
            duplicateMetab(sourceElement->getMetabolite(), index, sourceSet, emap);

          pMetab = dynamic_cast<const CMetab*>(emap.getDuplicatePtr(sourceElement->getMetabolite()));
        }
      else //add the original metab
        {
          pMetab = sourceElement->getMetabolite();
        }

      if (pMetab)
        newObj->addProduct(pMetab->getKey(), sourceElement->getMultiplicity());
    }

  for (i = 0; i < source->getChemEq().getModifiers().size(); ++i)
    {
      const CChemEqElement * sourceElement = source->getChemEq().getModifiers()[i];
      const CMetab* pMetab = NULL;

      if (sourceSet.contains(sourceElement->getMetabolite()))
        {
          if (!emap.exists(sourceElement->getMetabolite()))
            duplicateMetab(sourceElement->getMetabolite(), index, sourceSet, emap);

          pMetab = dynamic_cast<const CMetab*>(emap.getDuplicatePtr(sourceElement->getMetabolite()));
        }
      else //add the original metab
        {
          pMetab = sourceElement->getMetabolite();
        }

      if (pMetab)
        newObj->addModifier(pMetab->getKey());
    }

  newObj->setReversible(source->isReversible());

  //set the kinetic function
  newObj->setFunction(const_cast<CFunction*>(source->getFunction()));

  //mapping and local parameters
  for (i = 0; i < newObj->getFunctionParameters().size(); ++i)
    {
      switch (newObj->getFunctionParameters()[i]->getUsage())
        {
          case CFunctionParameter::SUBSTRATE:
          case CFunctionParameter::PRODUCT:
          case CFunctionParameter::MODIFIER:
          {
            bool isVector = (newObj->getFunctionParameters()[i]->getType() == CFunctionParameter::VFLOAT64);

            if (isVector)
              newObj->clearParameterMapping(i);

            size_t k;

            for (k = 0; k < source->getParameterMappings()[i].size(); ++k)
              {
                //we assume that by now the metab was copied if necessary.
                //therefore we only need to check the map.
                std::string targetKey;

                if (emap.exists(source->getParameterMappings()[i][k]))
                  targetKey = emap.getDuplicateKey(source->getParameterMappings()[i][k]);
                else
                  targetKey = source->getParameterMappings()[i][k];

                if (isVector)
                  newObj->addParameterMapping(i, targetKey);
                else
                  newObj->setParameterMapping(i, targetKey);
              }
          }
          break;

          case CFunctionParameter::TIME:
            newObj->setParameterMapping(i, source->getParameterMappings()[i][0]);
            break;

          case CFunctionParameter::VOLUME:
            if (sourceSet.contains(source->getParameterMappings()[i][0]))
              {
                if (!emap.exists(source->getParameterMappings()[i][0]))
                  {
                    const CCompartment* pSource = dynamic_cast<const CCompartment*>(
                                                    (CCopasiRootContainer::getKeyFactory()->get(source->getParameterMappings()[i][0])));
                    duplicateCompartment(pSource, index, sourceSet, emap);
                  }

                newObj->setParameterMapping(i, emap.getDuplicateKey(source->getParameterMappings()[i][0]));
              }
            else //add the original metab
              {
                newObj->setParameterMapping(i, source->getParameterMappings()[i][0]);
              }

            break;

          case CFunctionParameter::PARAMETER:
            if (newObj->isLocalParameter(i))
              {
                //just copy the value
                newObj->setParameterValue(newObj->getFunctionParameters()[i]->getObjectName(),
                                          source->getParameterValue(newObj->getFunctionParameters()[i]->getObjectName()));
              }
            else
              {
                if (sourceSet.contains(source->getParameterMappings()[i][0]))
                  {
                    if (!emap.exists(source->getParameterMappings()[i][0]))
                      {
                        const CModelValue* pSource = dynamic_cast<const CModelValue*>(
                                                       (CCopasiRootContainer::getKeyFactory()->get(source->getParameterMappings()[i][0])));
                        duplicateGlobalQuantity(pSource, index, sourceSet, emap);
                      }

                    newObj->setParameterMapping(i, emap.getDuplicateKey(source->getParameterMappings()[i][0]));
                  }
                else //add the original global quantity
                  {
                    newObj->setParameterMapping(i, source->getParameterMappings()[i][0]);
                  }
              }

            break;

          default:
            break;
        }
    }

  newObj->setNotes(source->getNotes());
  newObj->setMiriamAnnotation(source->getMiriamAnnotation(), newObj->getKey(), source->getKey());
}
Ejemplo n.º 16
0
bool CQRDFTreeView::enterProtected()
{
  clear();

  CCopasiObject *pObject = dynamic_cast< CCopasiObject * >(CCopasiRootContainer::getKeyFactory()->get(mKey));

  if (pObject != NULL)
    {
      CModelEntity * pEntity = NULL;
      CEvent * pEvent = NULL;
      CReaction * pReaction = NULL;
      CFunction * pFunction = NULL;
      const std::string * pMiriamAnnotation = NULL;

      if ((pEntity = dynamic_cast< CModelEntity * >(pObject)) != NULL)
        pMiriamAnnotation = &pEntity->getMiriamAnnotation();
      else if ((pEvent = dynamic_cast< CEvent * >(pObject)) != NULL)
        pMiriamAnnotation = &pEvent->getMiriamAnnotation();
      else if ((pReaction = dynamic_cast< CReaction * >(pObject)) != NULL)
        pMiriamAnnotation = &pReaction->getMiriamAnnotation();
      else if ((pFunction = dynamic_cast< CFunction * >(pObject)) != NULL)
        pMiriamAnnotation = &pFunction->getMiriamAnnotation();

      if (pMiriamAnnotation && *pMiriamAnnotation != "")
        mpGraph = CRDFParser::graphFromXml(*pMiriamAnnotation);
    }

  CCopasiMessage::clearDeque();

  if (CCopasiMessage::size() != 0)
    {
      QString Message = FROM_UTF8(CCopasiMessage::getAllMessageText());
      CQMessageBox::warning(this, QString("RDF Warning"), Message,
                            QMessageBox::Ok, QMessageBox::Ok);
    }

  if (mpGraph == NULL)
    mpGraph = new CRDFGraph;

  // We make sure that we always have an about node.
  mpGraph->createAboutNode(mKey);

  // We iterate of all triplets
  std::set< CRDFTriplet >::const_iterator it = mpGraph->getTriplets().begin();
  std::set< CRDFTriplet >::const_iterator end = mpGraph->getTriplets().end();

  for (; it != end; ++it)
    {
      CQRDFTreeViewItem * pSubjectItem = find(it->pSubject);

      if (pSubjectItem == NULL)
        {
          pSubjectItem = new CQRDFTreeViewItem(mpTreeWidget, NULL);
          insert(it->pSubject, pSubjectItem);
          // Display the subject information

          const CRDFSubject & Subject = it->pSubject->getSubject();

          switch (Subject.getType())
            {
              case CRDFSubject::RESOURCE:
                pSubjectItem->setText(COL_SUBJECT, FROM_UTF8(Subject.getResource()));
                break;

              case CRDFSubject::BLANK_NODE:
                pSubjectItem->setText(COL_SUBJECT, FROM_UTF8(Subject.getBlankNodeID()));
                break;
            }
        }

      CQRDFTreeViewItem * pObjectItem = NULL;

      if (it->Predicate.getURI() == "http://www.w3.org/1999/02/22-rdf-syntax-ns#subject")
        {
          pObjectItem = new CQRDFTreeViewItem(pSubjectItem, NULL);
          insert(it->pObject, pObjectItem);
        }
      else
        pObjectItem = find(it->pObject);

      if (pObjectItem == NULL)
        {
          pObjectItem = new CQRDFTreeViewItem(pSubjectItem, NULL);
          insert(it->pObject, pObjectItem);
        }
      else
        {
          QTreeWidgetItem * pParent = pObjectItem->parent();

          if (pParent == NULL)
            {
              mpTreeWidget->invisibleRootItem()->removeChild(pObjectItem);
              pSubjectItem->addChild(pObjectItem);
            }
          else
            {
              pParent->removeChild(pObjectItem);
              pSubjectItem->addChild(pObjectItem);
            }
        }

      pObjectItem->setTriplet(*it);
    }

  mpTreeWidget->setFocus();

  return true;
}
Ejemplo n.º 17
0
bool CReactionInterface::loadMappingAndValues(const CReaction & rea)
{
  bool success = true;
  std::vector< std::vector<std::string> >::const_iterator it;
  std::vector< std::vector<std::string> >::const_iterator iEnd;
  std::vector<std::string>::const_iterator jt;
  std::vector<std::string>::const_iterator jEnd;
  size_t i;

  std::string metabName;
  const CModelEntity* pObj;

  std::vector<std::string> SubList;
  SubList.resize(1);
  SubList[0] = "unknown";

  mNameMap.resize(size());

  for (i = 0; i != size(); ++i)
    {
      mNameMap[i] = SubList;
    }

  mValues.resize(size(), 0.1);
  mIsLocal.resize(size(), false);

  it = rea.getParameterMappings().begin();
  iEnd = rea.getParameterMappings().end();

  for (i = 0; it != iEnd; ++it, ++i)
    {

      if (isVector(i))
        {
          assert((getUsage(i) == CFunctionParameter::SUBSTRATE)
                 || (getUsage(i) == CFunctionParameter::PRODUCT)
                 || (getUsage(i) == CFunctionParameter::MODIFIER));

          SubList.clear();

          for (jt = it->begin(), jEnd = it->end(); jt != jEnd; ++jt)
            {
              metabName = CMetabNameInterface::getDisplayName(mpModel, *jt, true);
              assert(metabName != "");
              SubList.push_back(metabName);
            }
        }
      else
        {
          assert(it->size() == 1);
          SubList.resize(1); SubList[0] = "unknown";

          switch (getUsage(i))
            {
              case CFunctionParameter::SUBSTRATE:
              case CFunctionParameter::PRODUCT:
              case CFunctionParameter::MODIFIER:
                metabName = CMetabNameInterface::getDisplayName(mpModel, *(it->begin()), true);
                // assert(metabName != "");
                SubList[0] = metabName;
                //TODO: check if the metabolite is in the chemical equation with the correct rule
                break;

              case CFunctionParameter::VOLUME:
                pObj = dynamic_cast<const CCompartment*>(CCopasiRootContainer::getKeyFactory()->get(*(it->begin())));
                assert(pObj);
                SubList[0] = pObj->getObjectName();
                break;

              case CFunctionParameter::TIME:
                pObj = dynamic_cast<const CModel*>(CCopasiRootContainer::getKeyFactory()->get(*(it->begin())));
                assert(pObj);
                SubList[0] = pObj->getObjectName();
                break;

              case CFunctionParameter::PARAMETER:
              {
                const CCopasiParameter * pParameter = rea.getParameters().getParameter(getParameterName(i));

                if (pParameter != NULL)
                  {
                    mValues[i] = * pParameter->getValue().pDOUBLE;
                  }
                else
                  {
                    mValues[i] = std::numeric_limits< C_FLOAT64 >::quiet_NaN();
                  }

                mIsLocal[i] = rea.isLocalParameter(i);

                if (!mIsLocal[i])
                  {
                    pObj = dynamic_cast<const CModelValue*>(CCopasiRootContainer::getKeyFactory()->get(*(it->begin())));

                    if (pObj)
                      {
                        SubList[0] = pObj->getObjectName();
                        mValues[i] = pObj->getInitialValue();
                      }
                  }
              }
              break;

              default:
                break;
            }
        }

      mNameMap[i] = SubList;
    }

  return success;
}
Ejemplo n.º 18
0
void MakeModel(char *Title, char *comments, CCopasiVector < CGene > &gene, C_INT32 n, C_INT32 k, CModel &model, C_INT32 specific)
{
  C_INT32 i, j, r, s, pos, neg;
  char strname[512], strname2[512], streq[512];
  string compname = "cell", rname, rchemeq, kiname;
  CReaction *react;
  std::vector <std::string> subnames;
  subnames.resize(1);
  // two reactions per gene
  r = 2 * n;
  // set the title and comments
  model.setTitle(Title);
  model.setComments(comments);
  // add one compartment to the model
  model.addCompartment(compname, 1.0);
  // create one metabolite for each gene
  for (i = 0; i < n; i++)
    model.addMetabolite(gene[i]->getName(), compname, 1.0, 1);
  model.initializeMetabolites();
  // create two reactions for each gene
  for (i = 0; i < n; i++)
    {
      // transcription
      sprintf(strname, "%s synthesis", gene[i]->getName().data());
      sprintf(streq, "-> %s", gene[i]->getName().data());
      rname = strname;
      rchemeq = streq;
      react = new CReaction(rname);
      if (react == NULL)
        {
          fprintf(stderr, "Failed to create a CReaction object");
          abort();
        }
      react->setChemEq(streq);
      s = gene[i]->getModifierNumber();
      for (j = 0; j < s; j++)
        {
          react->addModifier(gene[i]->getModifier(j)->getName());
        }
      if (specific)
        sprintf(strname, "basal %ld inh %ld spec act (indp)", gene[i]->getNegativeModifiers(),
                gene[i]->getPositiveModifiers());
      else
        sprintf(strname, "transcr %ld inh %ld act (indp)", gene[i]->getNegativeModifiers(),
                gene[i]->getPositiveModifiers());
      kiname = strname;
      react->setFunction(kiname);
      for (j = 0, pos = 1; j < s; j++)
        {
          if (gene[i]->getModifierType(j) == 1)
            {
              sprintf(strname, "A%ld", pos++);
              react->setParameterMapping(strname, gene[i]->getModifier(j)->getName());
            }
        }
      for (j = 0, neg = 1; j < s; j++)
        {
          if (gene[i]->getModifierType(j) == 0)
            {
              sprintf(strname, "I%ld", neg++);
              react->setParameterMapping(strname, gene[i]->getModifier(j)->getName());
            }
        }
      // first the basal rate
      sprintf(strname, "V");
      react->setParameterValue(strname, gene[i]->getRate());
      // we have two more constants per modifier
      for (j = 0, pos = neg = 1; j < s; j++)
        {
          if (gene[i]->getModifierType(j) == 0)
            {
              sprintf(strname, "Ki%ld", neg);
              sprintf(strname2, "ni%ld", neg++);
            }
          else
            {
              sprintf(strname, "Ka%ld", pos);
              sprintf(strname2, "na%ld", pos++);
            }
          react->setParameterValue(strname, gene[i]->getK(j));
          react->setParameterValue(strname2, gene[i]->getn(j));
        }
      model.addReaction(*react);
      // mRNA degradation
      sprintf(strname, "%s degradation", gene[i]->getName().data());
      sprintf(streq, "%s ->", gene[i]->getName().data());
      rname = strname;
      rchemeq = streq;
      react = new CReaction(rname);
      if (react == NULL)
        {
          fprintf(stderr, "Failed to create a CReaction object");
          abort();
        }
      react->setChemEq(streq);
      kiname = "Mass action (irreversible)";
      react->setFunction(kiname);
      // first the kinetic constant
      sprintf(strname, "k1");
      react->setParameterValue(strname, gene[i]->getDegradationRate());
      // now the substrate
      sprintf(strname, "substrate_0");
      subnames[0] = gene[i]->getName();
      react->setParameterMapping(strname, subnames);
      model.addReaction(*react);
    }
  // structural analysis (moieties, etc.)
  model.compile();
}
Ejemplo n.º 19
0
// virtual
bool CModelParameter::updateModel()
{
    bool success = true;

    if (mpObject != NULL)
    {
        switch (mType)
        {
        case Model:
        {
            CModel * pModel = static_cast< CModel * >(mpObject);

            if (!pModel->isAutonomous())
            {
                pModel->setInitialValue(mValue);
            }
            else
            {
                pModel->setInitialValue(0.0);
            }
        }
        break;

        case Compartment:
        case Species:
        case ModelValue:
        {
            CModelEntity * pEntity = static_cast< CModelEntity * >(mpObject);

            if (pEntity->getStatus() != CModelEntity::ASSIGNMENT)
            {
                pEntity->setInitialValue(mValue);

                if (mIsInitialExpressionValid)
                {
                    pEntity->setInitialExpression(getInitialExpression());
                }
            }
        }
        break;

        case ReactionParameter:
        {
            CCopasiParameter * pParameter = static_cast< CCopasiParameter * >(mpObject);
            CReaction * pReaction = static_cast< CReaction * >(mpObject->getObjectAncestor("Reaction"));

            if (mIsInitialExpressionValid &&
                    getInitialExpression() != "")
            {
                CModel * pModel = mpParent->getModel();

                assert(pModel != NULL);

                std::vector< CCopasiContainer * > ListOfContainer;
                ListOfContainer.push_back(pModel);

                CCopasiObjectName CN = static_cast< CEvaluationNodeObject * >(mpInitialExpression->getRoot())->getObjectCN();
                CCopasiObject * pObject = pModel->getObjectDataModel()->ObjectFromName(ListOfContainer, CN);

                assert(pObject != NULL);

                // We assign the object value
                pParameter->setValue(* (C_FLOAT64 *) pObject->getValuePointer());

                // We map the parameter to the global quantity
                pReaction->setParameterMapping(pParameter->getObjectName(), pObject->getObjectParent()->getKey());
            }
            else
            {
                pParameter->setValue(mValue);

                // We need to remove the existing mapping to a global quantity1.
                pReaction->setParameterMapping(pParameter->getObjectName(), pParameter->getKey());
            }
        }
        break;

        default:
            success = false;
            break;
        }
    }

    return success;
}
Ejemplo n.º 20
0
bool CModelAdd::addReactions(std::string name)
{

  bool info = false;

  //create copies of the relevant reactions

  size_t i, imax = mmModel->getReactions().size();

  size_t ic, icmax = mmModel->getCompartments().size();

  for (ic = 0; ic < icmax; ++ic)
    {
      const CCompartment* sourceComp = &mmModel->getCompartments()[ic];

      if (!sourceComp) return info;

      for (i = 0; i < imax; ++i)
        {
          CReaction * sourceReac = &mmModel->getReactions()[i];

          if (reactionInvolvesCompartment(sourceReac, sourceComp))
            {

              std::string newName = sourceReac->getObjectName() + "_" + name;

              CReaction* newReac = mpModel->createReaction(newName);

              if (!newReac) return info;

              //copy the chemical equation. If the involved metabs are among those that
              //were copied with the compartment, replace them. Otherwise keep the original metab
              newReac->setReversible(sourceReac->isReversible());
              std::map<std::string, std::string>::const_iterator mapIt;
              std::string targetKey;
              size_t j, jmax = sourceReac->getChemEq().getSubstrates().size();

              for (j = 0; j < jmax; ++j)
                {
                  const CChemEqElement * sourceElement = &sourceReac->getChemEq().getSubstrates()[j];
                  //check if the metab is in the map. If yes, translate it, otherwise not.
                  mapIt = keyMap.find(sourceElement->getMetaboliteKey());

                  if (mapIt == keyMap.end())
                    {
                      targetKey = sourceElement->getMetaboliteKey();
                    }
                  else
                    targetKey = mapIt->second;

                  newReac->addSubstrate(targetKey, sourceElement->getMultiplicity());
                }

              jmax = sourceReac->getChemEq().getProducts().size();

              for (j = 0; j < jmax; ++j)
                {
                  const CChemEqElement * sourceElement = &sourceReac->getChemEq().getProducts()[j];
                  //check if the metab is in the map. If yes, translate it, otherwise not.
                  mapIt = keyMap.find(sourceElement->getMetaboliteKey());

                  if (mapIt == keyMap.end())
                    {
                      targetKey = sourceElement->getMetaboliteKey();
                    }
                  else
                    targetKey = mapIt->second;

                  newReac->addProduct(targetKey, sourceElement->getMultiplicity());
                }

              jmax = sourceReac->getChemEq().getModifiers().size();

              for (j = 0; j < jmax; ++j)
                {
                  const CChemEqElement * sourceElement = &sourceReac->getChemEq().getModifiers()[j];
                  //check if the metab is in the map. If yes, translate it, otherwise not.

                  mapIt = keyMap.find(sourceElement->getMetaboliteKey());

                  if (mapIt == keyMap.end())
                    {
                      targetKey = sourceElement->getMetaboliteKey();
                    }
                  else
                    targetKey = mapIt->second;

                  newReac->addModifier(targetKey);
                }

              //set the kinetic function
              newReac->setFunction(const_cast<CFunction*>(sourceReac->getFunction()));

              //mapping and local parameters
              for (j = 0; j < newReac->getFunctionParameters().size(); ++j)
                {
                  switch (newReac->getFunctionParameters()[j]->getUsage())
                    {
                      case CFunctionParameter::SUBSTRATE:
                      case CFunctionParameter::PRODUCT:
                      case CFunctionParameter::MODIFIER:
                        //translate the metab keys
                      {
                        bool isVector = (newReac->getFunctionParameters()[j]->getType() == CFunctionParameter::VFLOAT64);

                        //we assume that only SUBSTRATE, PRODUCT, MODIFIER can be vectors
                        if (isVector)
                          newReac->clearParameterMapping(j);

                        size_t k;

                        for (k = 0; k < sourceReac->getParameterMappings()[j].size(); ++k)
                          {
                            mapIt = keyMap.find(sourceReac->getParameterMappings()[j][k]);

                            if (mapIt == keyMap.end())
                              {
                                targetKey = sourceReac->getParameterMappings()[j][k];
                              }
                            else
                              targetKey = mapIt->second;

                            if (isVector)
                              newReac->addParameterMapping(j, targetKey);
                            else
                              newReac->setParameterMapping(j, targetKey);
                          }
                      }
                      break;

                      case CFunctionParameter::TIME:
                        //just copy the key
                      {
                        mapIt = keyMap.find(sourceReac->getParameterMappings()[j][0]);

                        if (mapIt == keyMap.end())
                          {
                            targetKey = sourceReac->getParameterMappings()[j][0];
                          }
                        else
                          targetKey = mapIt->second;

                        newReac->setParameterMapping(j, targetKey);
                      }
                      break;

                      case CFunctionParameter::VOLUME:

                        //translate the compartment key if necessary
                        if (sourceReac->getParameterMappings()[j][0] == sourceComp->getKey())
                          newReac->setParameterMapping(j, keyMap[sourceComp->getKey()]);
                        else
                          {
                            mapIt = keyMap.find(sourceReac->getParameterMappings()[j][0]);

                            if (mapIt == keyMap.end())
                              {
                                targetKey = sourceReac->getParameterMappings()[j][0];
                              }
                            else
                              targetKey = mapIt->second;

                            newReac->setParameterMapping(j, targetKey);
                          }

                        //TODO: this needs to be adapted when sets of compartments will be copied
                        break;

                      case CFunctionParameter::PARAMETER:

                        if (sourceReac->isLocalParameter(j))
                          newReac->setParameterValue(newReac->getFunctionParameters()[j]->getObjectName(),
                                                     sourceReac->getParameterValue(newReac->getFunctionParameters()[j]->getObjectName()));
                        else
                          {
                            mapIt = keyMap.find(sourceReac->getParameterMappings()[j][0]);

                            if (mapIt == keyMap.end())
                              {
                                targetKey = sourceReac->getParameterMappings()[j][0];
                              }
                            else
                              targetKey = mapIt->second;

                            newReac->setParameterMapping(j,  targetKey);
                          }

                        break;

                      default:
                        return info;
                        break;
                    }
                }
            }
        }
    }

  return true;
}