Ejemplo n.º 1
0
END_TEST

START_TEST(test_parseModel_basic)
{
	doc = parseModel(EXAMPLES_FILENAME("basic.xml"), 0, 1);
	ck_assert(doc != NULL);
	model = SBMLDocument_getModel(doc);
	ck_assert(model != NULL);
	ck_assert(Model_getNumFunctionDefinitions(model) == 0);
	ck_assert(Model_getNumUnitDefinitions(model) == 0);
	ck_assert(Model_getNumCompartmentTypes(model) == 0);
	ck_assert(Model_getNumSpeciesTypes(model) == 0);
	ck_assert(Model_getNumCompartments(model) == 1);
	ck_assert(Model_getNumSpecies(model) == 2);
	ck_assert(Model_getNumSpeciesWithBoundaryCondition(model) == 0);
	ck_assert(Model_getNumParameters(model) == 1);
	ck_assert(Model_getNumInitialAssignments(model) == 0);
	ck_assert(Model_getNumRules(model) == 0);
	ck_assert(Model_getNumConstraints(model) == 0);
	ck_assert(Model_getNumReactions(model) == 2);
	ck_assert(Model_getNumEvents(model) == 0);
	CHECK_PARAMETER(model, 0, "k_1");
	CHECK_REACTION(model, 0, "R1", "k_1 * S1");
	CHECK_REACTION(model, 1, "R2", "k_2 * S2");
}
Ejemplo n.º 2
0
void
printMath (Model_t *m)
{
  unsigned int  n;


  for (n = 0; n < Model_getNumFunctionDefinitions(m); ++n)
  {
    printFunctionDefinition(n + 1, Model_getFunctionDefinition(m, n));
  }

  for (n = 0; n < Model_getNumRules(m); ++n)
  {
    printRuleMath(n + 1, Model_getRule(m, n));
  }

  printf("\n");

  for (n = 0; n < Model_getNumReactions(m); ++n)
  {
    printReactionMath(n + 1, Model_getReaction(m, n));
  }

  printf("\n");

  for (n = 0; n < Model_getNumEvents(m); ++n)
  {
    printEventMath(n + 1, Model_getEvent(m, n));
  }
}
Ejemplo n.º 3
0
END_TEST

START_TEST(test_parseModel_repressilator)
{
	doc = parseModel(EXAMPLES_FILENAME("repressilator.xml"), 0, 1);
	ck_assert(doc != NULL);
	model = SBMLDocument_getModel(doc);
	ck_assert(model != NULL);
	ck_assert(Model_getNumFunctionDefinitions(model) == 0);
	ck_assert(Model_getNumUnitDefinitions(model) == 0);
	ck_assert(Model_getNumCompartmentTypes(model) == 0);
	ck_assert(Model_getNumSpeciesTypes(model) == 0);
	ck_assert(Model_getNumCompartments(model) == 1);
	ck_assert(Model_getNumSpecies(model) == 6);
	ck_assert(Model_getNumSpeciesWithBoundaryCondition(model) == 0);
	ck_assert(Model_getNumParameters(model) == 3);
	ck_assert(Model_getNumInitialAssignments(model) == 0);
	ck_assert(Model_getNumRules(model) == 6);
	ck_assert(Model_getNumConstraints(model) == 0);
	ck_assert(Model_getNumReactions(model) == 0);
	ck_assert(Model_getNumEvents(model) == 0);
	CHECK_PARAMETER(model, 0, "alpha");
	CHECK_PARAMETER(model, 1, "beta");
	CHECK_PARAMETER(model, 2, "rho");
	CHECK_RULE(model, 0, "beta * (y1 - x1)");
	CHECK_RULE(model, 1, "beta * (y2 - x2)");
	CHECK_RULE(model, 2, "beta * (y3 - x3)");
	CHECK_RULE(model, 3, "alpha * x1 / (1 + x1 + rho * x3) - y1");
	CHECK_RULE(model, 4, "alpha * x2 / (1 + x2 + rho * x1) - y2");
	CHECK_RULE(model, 5, "alpha * x3 / (1 + x3 + rho * x2) - y3");
}
Ejemplo n.º 4
0
int main(int argc, char** argv)
{
    myspecies_t* species;	//pinakas ximikon stoixeion
    reaction_t *reaction;	//20 ximikes antidraseis
    int i,j,k,num_species, num_reactions;
    double V;
    FILE *pf1, *pf2, *pf3, *pf4, *pf5, *pf6;

    SBMLDocument_t *d;
    Model_t        *m;
    ListOf_t    *lo;
    Species_t   *sp;
    Reaction_t  *re;
    Parameter_t *p;
    KineticLaw_t *kin;
    SpeciesReference_t *sr;
    Compartment_t *c;

	if(argc != 2)
    {
        printf("Ektelesi: %s <SBML xml>\n", argv[0]);
        exit(-1);
    }

    //anoigo to SBML arxeio
    d = readSBML(argv[1]);
    //d=readSBML("C:/home/orsalia/BIOMD0000000001");
    m = SBMLDocument_getModel(d);
    num_species = Model_getNumSpecies(m);
    num_reactions = Model_getNumReactions(m);

    printf("M: %d\n", num_species);
    printf("R: %d\n", num_reactions);
}
Ejemplo n.º 5
0
int
main (int argc, char *argv[])
{
  const char *filename;

  SBMLDocument_t *d;
  Model_t        *m;

  unsigned int level, version;


  if (argc != 2)
  {
    printf("Usage: printSBML filename\n");
    return 2;
  }


  filename = argv[1];
  d        = readSBML(filename);

  SBMLDocument_printErrors(d, stdout);

  m = SBMLDocument_getModel(d);

  level   = SBMLDocument_getLevel  (d);
  version = SBMLDocument_getVersion(d);

  printf("\n");
  printf("File: %s (Level %u, version %u)\n", filename, level, version);

  if (m == NULL)
  {
    printf("No model present.");
    return 1;
  }

  printf("         ");
  printf("  model id: %s\n",  Model_isSetId(m) ? Model_getId(m) : "(empty)");

  printf( "functionDefinitions: %d\n",  Model_getNumFunctionDefinitions(m) );
  printf( "    unitDefinitions: %d\n",  Model_getNumUnitDefinitions    (m) );
  printf( "   compartmentTypes: %d\n",  Model_getNumCompartmentTypes   (m) );
  printf( "        specieTypes: %d\n",  Model_getNumSpeciesTypes       (m) );
  printf( "       compartments: %d\n",  Model_getNumCompartments       (m) );
  printf( "            species: %d\n",  Model_getNumSpecies            (m) );
  printf( "         parameters: %d\n",  Model_getNumParameters         (m) );
  printf( " initialAssignments: %d\n",  Model_getNumInitialAssignments (m) );
  printf( "              rules: %d\n",  Model_getNumRules              (m) );
  printf( "        constraints: %d\n",  Model_getNumConstraints        (m) );
  printf( "          reactions: %d\n",  Model_getNumReactions          (m) );
  printf( "             events: %d\n",  Model_getNumEvents             (m) );
  printf( "\n" );

  SBMLDocument_free(d);
  return 0;
}
void prepare_reversible_fast_reaction(Model_t *m, myReaction *re[], mySpecies *sp[], myParameter *param[], myCompartment *comp[], double sim_time, double dt, double *time, myInitialAssignment *initAssign[], char *time_variant_target_id[], unsigned int num_of_time_variant_targets, timeVariantAssignments *timeVarAssign, allocated_memory *mem, copied_AST *cp_AST){
  unsigned int i;
  unsigned int num_of_reactions = Model_getNumReactions(m);
  ASTNode_t *node, *cp_node1, *cp_node2;
  myASTNode *myNode = NULL;
  myASTNode *copied_myAST[MAX_COPIED_AST];
  unsigned int num_of_copied_myAST = 0;
  for(i=0; i<num_of_reactions; i++){
    if(re[i]->is_fast && re[i]->is_reversible){
      node = (ASTNode_t*)KineticLaw_getMath(Reaction_getKineticLaw(re[i]->origin));
      node = ASTNode_deepCopy(node);
      TRACE(("original math of %s: ", Reaction_getId(re[i]->origin)));
      check_AST(node, NULL);
      /* alter_tree_structure(m, &node, cp_AST); */
      alter_tree_structure(m, &node, NULL, 0, cp_AST);
      set_local_para_as_value(node, Reaction_getKineticLaw(re[i]->origin));
      TRACE(("alterated math of %s : ", Reaction_getId(re[i]->origin)));
      check_AST(node, NULL);
      cp_node1 = ASTNode_deepCopy(node);
      cp_node2 = ASTNode_deepCopy(node);
      /* get products numerator */
      myNode = (myASTNode*)malloc(sizeof(myASTNode));
      copied_myAST[num_of_copied_myAST++] = myNode;
      myNode->origin = cp_node1;
      myNode->parent = NULL;
      myNode->left = NULL;
      myNode->right = NULL;
      myASTNode_create(myNode, cp_node1, copied_myAST, &num_of_copied_myAST);
      re[i]->products_equili_numerator = (equation*)malloc(sizeof(equation));
      TRACE(("target_id is %s\n", Species_getId(re[i]->reactants[0]->mySp->origin)));
      check_AST(cp_node1, NULL);
      _prepare_reversible_fast_reaction(m, myNode, re[i], sp, param, comp, re, sim_time, dt, time, initAssign, time_variant_target_id, num_of_time_variant_targets, timeVarAssign, (char*)Species_getId(re[i]->reactants[0]->mySp->origin), 0, mem);
      /* get reactants numerator */
      myNode = (myASTNode*)malloc(sizeof(myASTNode));
      copied_myAST[num_of_copied_myAST++] = myNode;
      myNode->origin = cp_node2;
      myNode->parent = NULL;
      myNode->left = NULL;
      myNode->right = NULL;
      re[i]->reactants_equili_numerator = (equation*)malloc(sizeof(equation));
      myASTNode_create(myNode, cp_node2, copied_myAST, &num_of_copied_myAST);
      TRACE(("target_id is %s\n", Species_getId(re[i]->products[0]->mySp->origin)));
      check_AST(cp_node2, NULL);
      _prepare_reversible_fast_reaction(m, myNode, re[i], sp, param, comp, re, sim_time, dt, time, initAssign, time_variant_target_id, num_of_time_variant_targets, timeVarAssign, (char*)Species_getId(re[i]->products[0]->mySp->origin), 1, mem);
      myASTNode_free(copied_myAST, num_of_copied_myAST);
    }
  }
}
Ejemplo n.º 7
0
void printModel(Model_t *m, FILE *f)
{
  fprintf(f, "\n");
  fprintf(f, "Model Statistics:\n");
  fprintf(f, " Model id:     %s\n",
	 Model_isSetId(m) ? Model_getId(m) : "(not set)");
  fprintf(f, " Model name:   %s\n",
	 Model_isSetName(m) ? Model_getName(m) : "(not set)"); 
  fprintf(f, "\n");
  fprintf(f, " Compartments: %d\n",  Model_getNumCompartments(m)); 
  fprintf(f, " Species:      %d\n",  Model_getNumSpecies(m));
  fprintf(f, " Reactions:    %d\n",  Model_getNumReactions(m));
  fprintf(f, " Rules:        %d\n",  Model_getNumRules(m));
  fprintf(f, " Events:       %d\n",  Model_getNumEvents(m));
  fprintf(f, " Functions:    %d\n",  Model_getNumFunctionDefinitions(m) ); 
  fprintf(f, "\n");
}
Ejemplo n.º 8
0
/**
 * \fn void SBML_compute_simulation_mean(FILE *debugFile, pScore result, pScore result_temp, Model_t *mod, double *reactions_ratio, gsl_rng * r, char **banned, int nbBanned, int nb_simulation)
 * \author Amine Ghozlane
 * \brief  X time simulation of metabolic network
 * \param  debugFile File use for debug
 * \param  result Struct Score used for all the simulation
 * \param  result_temp Struct Score used at each simulation step
 * \param  mod Model of the SBML file
 * \param  reactions_ratio List of computed reaction ratio
 * \param  r Random number generator
 * \param  banned List of banned compound
 * \param  nbBanned Number of banned compound
 * \param  nb_simulation Number of simulation step
 */
void SBML_compute_simulation_mean(FILE *debugFile, pScore result, pScore result_temp, Model_t *mod, double *reactions_ratio, gsl_rng * r, char **banned, int nbBanned, int nb_simulation)
{
  /* Simulation du reseau metabolique  */
  int i, j,nbReactions = 0, nbEspeces = 0, temp = 1, tempo=0;
  pEspeces molecules=NULL;
  pTestReaction TR=NULL;

  /* Allocation memoire */
  TR=(pTestReaction)malloc(1*sizeof(TestReaction));
  assert(TR!=NULL);

  /* File information */
  nbReactions = (int) Model_getNumReactions(mod);
  nbEspeces = (int)Model_getNumSpecies(mod);
  molecules = Especes_alloc(nbEspeces);

  /* Initialisation de la quantite des especes */
  SBML_initEspeceAmounts(mod, molecules, nbEspeces);

  /* Initialisation des reactions et des ratios*/
  SBML_setReactions(mod, molecules, result_temp, reactions_ratio, nbReactions, nbEspeces);

  /* SIMULATION */
  for(j=0;j<nb_simulation;j++){
      /* Simulation des reactions */
      while (temp > END) {
          temp = 0;
          for (i = 0; i < nbEspeces; i++) {
              tempo= SBML_simulate(mod, molecules, r, TR,  banned, nbBanned, nbEspeces, i);
              temp +=tempo;
          }
      }
      temp=1;
      tempo=0;

      /*Score */
      SBML_score(mod, molecules, result_temp, reactions_ratio, nbReactions, nbEspeces);
      SBML_score_add(result,result_temp,debugFile);
      SBML_initEspeceAmounts(mod, molecules, nbEspeces);
  }
  SBML_score_mean(result,nb_simulation);

  /* Liberation de la memoire de la structure Especes */
  Especes_free(molecules, nbEspeces);
  if(TR!=NULL) free(TR);
}
Ejemplo n.º 9
0
void
printMath (Model_t *m)
{
  unsigned int  n;

  /* a digraph must have a name thus
   * need to check that Model_getId does not return NULL
   * and provide a name if it does
   */

  if (Model_getId(m) != NULL) {
    fprintf(fout, "digraph %s {\n", Model_getId(m));
  }
  else {
    fprintf(fout, "digraph example {\n");
  }
  fprintf(fout, "compound=true;\n");

  for (n = 0; n < Model_getNumFunctionDefinitions(m); ++n)
  {
    printFunctionDefinition(n + 1, Model_getFunctionDefinition(m, n));
  }

  for (n = 0; n < Model_getNumRules(m); ++n)
  {
    printRuleMath(n + 1, Model_getRule(m, n));
  }

  printf("\n");

  for (n = 0; n < Model_getNumReactions(m); ++n)
  {
    printReactionMath(n + 1, Model_getReaction(m, n));
  }

  printf("\n");

  for (n = 0; n < Model_getNumEvents(m); ++n)
  {
    printEventMath(n + 1, Model_getEvent(m, n));
  }

  fprintf(fout, "}\n");
}
Ejemplo n.º 10
0
END_TEST

START_TEST(test_parseModel_huang96)
{
	doc = parseModel(EXAMPLES_FILENAME("huang96.xml"), 0, 1);
	ck_assert(doc != NULL);
	model = SBMLDocument_getModel(doc);
	ck_assert(model != NULL);
	ck_assert(Model_getNumFunctionDefinitions(model) == 0);
	ck_assert(Model_getNumUnitDefinitions(model) == 0);
	ck_assert(Model_getNumCompartmentTypes(model) == 0);
	ck_assert(Model_getNumSpeciesTypes(model) == 0);
	ck_assert(Model_getNumCompartments(model) == 1);
	ck_assert(Model_getNumSpecies(model) == 22);
	ck_assert(Model_getNumSpeciesWithBoundaryCondition(model) == 0);
	ck_assert(Model_getNumParameters(model) == 0);
	ck_assert(Model_getNumInitialAssignments(model) == 0);
	ck_assert(Model_getNumRules(model) == 0);
	ck_assert(Model_getNumConstraints(model) == 0);
	ck_assert(Model_getNumReactions(model) == 20);
	ck_assert(Model_getNumEvents(model) == 0);
	CHECK_REACTION(model, 0, "r1a", "a1 * E1 * KKK - d1 * E1_KKK");
	CHECK_REACTION(model, 1, "r1b", "k2 * E1_KKK");
	CHECK_REACTION(model, 2, "r2a", "a2 * E2 * P_KKK - d2 * E2_P_KKK");
	CHECK_REACTION(model, 3, "r2b", "k2 * E2_P_KKK");
	CHECK_REACTION(model, 4, "r3a", "a3 * KK * P_KKK - d3 * P_KKK_KK");
	CHECK_REACTION(model, 5, "r3b", "k3 * P_KKK_KK");
	CHECK_REACTION(model, 6, "r4a", "a4 * P_KK * KKPase - d4 * KKPase_P_KK");
	CHECK_REACTION(model, 7, "r4b", "k4 * KKPase_P_KK");
	CHECK_REACTION(model, 8, "r5a", "a5 * P_KK * P_KKK - d5 * P_KKK_P_KK");
	CHECK_REACTION(model, 9, "r5b", "k5 * P_KKK_P_KK");
	CHECK_REACTION(model, 10, "r6a", "a6 * PP_KK * KKPase - d6 * KKPase_PP_KK");
	CHECK_REACTION(model, 11, "r6b", "k6 * KKPase_PP_KK");
	CHECK_REACTION(model, 12, "r7a", "a7 * K * PP_KK - d7 * PP_KK_K");
	CHECK_REACTION(model, 13, "r7b", "k7 * PP_KK_K");
	CHECK_REACTION(model, 14, "r8a", "a8 * P_K * KPase - d8 * KPase_P_K");
	CHECK_REACTION(model, 15, "r8b", "k8 * KPase_P_K");
	CHECK_REACTION(model, 16, "r9a", "a9 * P_K * PP_KK - d9 * PP_KK_P_K");
	CHECK_REACTION(model, 17, "r9b", "k9 * PP_KK_P_K");
	CHECK_REACTION(model, 18, "r10a", "a10 * PP_K * KPase - d10 * KPase_PP_K");
	CHECK_REACTION(model, 19, "r10b", "k10 * KPase_PP_K");
	/* TODO */
}
Ejemplo n.º 11
0
END_TEST

START_TEST(test_parseModel_events_1_event_1_assignment_l2)
{
	doc = parseModel(EXAMPLES_FILENAME("events-1-event-1-assignment-l2.xml"), 0, 1);
	ck_assert(doc != NULL);
	model = SBMLDocument_getModel(doc);
	ck_assert(model != NULL);
	ck_assert(Model_getNumFunctionDefinitions(model) == 0);
	ck_assert(Model_getNumUnitDefinitions(model) == 0);
	ck_assert(Model_getNumCompartmentTypes(model) == 0);
	ck_assert(Model_getNumSpeciesTypes(model) == 0);
	ck_assert(Model_getNumCompartments(model) == 1);
	ck_assert(Model_getNumSpecies(model) == 2);
	ck_assert(Model_getNumSpeciesWithBoundaryCondition(model) == 0);
	ck_assert(Model_getNumParameters(model) == 0);
	ck_assert(Model_getNumInitialAssignments(model) == 0);
	ck_assert(Model_getNumRules(model) == 0);
	ck_assert(Model_getNumConstraints(model) == 0);
	ck_assert(Model_getNumReactions(model) == 1);
	ck_assert(Model_getNumEvents(model) == 1);
	CHECK_REACTION(model, 0, "R", "S1");
	/* TODO */
}
int
main (int argc, char *argv[])
{

  SBMLDocument_t* d;
  Model_t* m;
  unsigned int  errors, n;
  Reaction_t *r;

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


  d      = readSBML(argv[1]);
  errors = SBMLDocument_getNumErrors(d);

  if (errors > 0)
  {
    printf("Read Error(s):\n");
    SBMLDocument_printErrors(d, stdout);	 
    printf("Correct the above and re-run.\n");
  }
  else
  {
  
    m = SBMLDocument_getModel(d);
    n =  Model_getNumReactions(m);
    
    if (n <= 0)
    {
      printf( "Model has no reactions.\n Cannot add CV terms\n");
    }
    else
    {      
      CVTerm_t *cv1, *cv2;
      r = Model_getReaction(m, 0);

      /* check that the reaction has a metaid
       * no CVTerms will be added if there is no metaid to reference
       */
      if (SBase_isSetMetaId((SBase_t*)r))
        SBase_setMetaId((SBase_t*)r, "metaid_0000052");

      cv1 = CVTerm_createWithQualifierType(BIOLOGICAL_QUALIFIER);
      CVTerm_setBiologicalQualifierType(cv1, BQB_IS_DESCRIBED_BY);
      CVTerm_addResource(cv1, "urn:miriam:obo.eco:ECO%3A0000183");

      SBase_addCVTerm((SBase_t*)r, cv1);

      cv2 = CVTerm_createWithQualifierType(BIOLOGICAL_QUALIFIER);
      CVTerm_setBiologicalQualifierType(cv2, BQB_IS);
      CVTerm_addResource(cv2, "urn:miriam:kegg.reaction:R00756");
      CVTerm_addResource(cv2, "urn:miriam:reactome:REACT_736");
      
      SBase_addCVTerm((SBase_t*)r, cv2);

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

  SBMLDocument_free(d);
  return errors;
}
Ejemplo n.º 13
0
void printReactions(Model_t *m, FILE *f)
{
  
  int i,j,k;
  Reaction_t *r;
  SpeciesReference_t *sref;
  KineticLaw_t *kl;
  Rule_t *rl;
  AssignmentRule_t *asr;
  AlgebraicRule_t *alr;
  RateRule_t *rr;
  Event_t *e;
  EventAssignment_t *ea;
  Parameter_t *p;
  FunctionDefinition_t *fd;
  SBMLTypeCode_t type;
  const ASTNode_t *math;

  math = NULL;
  
  fprintf(f, "\n");
  for(i=0;i<Model_getNumParameters(m);i++){
    if(i==0)
      fprintf(f, "# Global parameters:\n");
    p = Model_getParameter(m,i);
    if(Parameter_isSetId(p))
      fprintf(f, "%s ",  Parameter_getId(p));
    if(Parameter_isSetName(p))
      fprintf(f, "(%s) ", Parameter_getName(p));
    if(Parameter_isSetValue(p))
      fprintf(f, "= %g; ", Parameter_getValue(p));
    if(Parameter_isSetUnits(p))
      fprintf(f, "[%s]; ", Parameter_getUnits(p));
    if(!Parameter_getConstant(p))
      fprintf(f, "(variable);");
    fprintf(f, "\n");
    
    if ( i==Model_getNumParameters(m)-1 )
      fprintf(f, "\n");
  }

  fprintf(f, "# Reactions:\n");
  for ( i=0; i<Model_getNumReactions(m); i++ ) {    
    r = Model_getReaction(m,i);
  
    fprintf(f, "%s: %s",
	   Reaction_isSetName(r) ? Reaction_getName(r) : Reaction_getId(r),
	   Reaction_getFast(r) ? "(fast)" : "");
    for ( k=0; k<Reaction_getNumReactants(r); k++ ) {
      sref = Reaction_getReactant(r,k);

      if ( SpeciesReference_isSetStoichiometryMath(sref) )	
	fprintf(f, "%s ",
		SBML_formulaToString(\
		SpeciesReference_getStoichiometryMath(sref)));
      else 
	if ( SpeciesReference_getStoichiometry(sref) != 1. )
	  fprintf(f, "%g ",  SpeciesReference_getStoichiometry(sref));
	
      fprintf(f, "%s", SpeciesReference_getSpecies(sref));
      if(k+1<Reaction_getNumReactants(r))
	fprintf(f, "%s", " + ");
    }
    
    fprintf(f, "%s", Reaction_getReversible(r) ? " <-> " : " -> ");
    for ( k=0; k<Reaction_getNumProducts(r); k++ ) {
      sref = Reaction_getProduct(r,k);
      if ( SpeciesReference_isSetStoichiometryMath(sref) )
	fprintf(f, "%s ",
	       SBML_formulaToString(\
		   SpeciesReference_getStoichiometryMath(sref)));
      else
	if ( SpeciesReference_getStoichiometry(sref) != 1. )
	  fprintf(f, "%g ", SpeciesReference_getStoichiometry(sref));
      
      fprintf(f, "%s", SpeciesReference_getSpecies(sref));
      if(k+1<Reaction_getNumProducts(r))
	fprintf(f, "%s", " + ");
    }
    fprintf(f, ";  ");
    if(Reaction_isSetKineticLaw(r)){
      kl = Reaction_getKineticLaw(r);
      math = KineticLaw_getMath(kl);
      fprintf(f, "%s;", SBML_formulaToString(math));
      for(k=0;k<KineticLaw_getNumParameters(kl);k++){
	
	p = KineticLaw_getParameter(kl,k);
	fprintf(f, " %s",  Parameter_getId(p));
	if(Parameter_isSetName(p))
	  fprintf(f, " (%s)", Parameter_getName(p));
	if(Parameter_isSetValue(p))
	  fprintf(f, " = %g", Parameter_getValue(p));
	if(Parameter_isSetUnits(p))
	  fprintf(f, " [%s]", Parameter_getUnits(p));
	if ( !Parameter_getConstant(p) )
	  fprintf(f, " (variable)");
	fprintf(f, ";");
      }
     /*  fprintf(f, "\n"); */
    }else
      fprintf(f, "#   no rate law is set for this reaction.");
    fprintf(f, "\n");
  }
    
  for(i=0;i<Model_getNumRules(m);i++){
    rl = Model_getRule(m,i);
    if ( i == 0 ) {
      fprintf(f, "# Rules:\n");
    }
    type = SBase_getTypeCode((SBase_t *)rl);
     
     
    if ( type == SBML_RATE_RULE ) {
      rr =  (RateRule_t *) rl;
      fprintf(f, " rateRule:       d%s/dt = ", RateRule_getVariable(rr));
    }
    if ( type == SBML_ALGEBRAIC_RULE ) {
      alr = (AlgebraicRule_t *) rl;
      fprintf(f, " algebraicRule:       0 = ");
    }
    if ( type == SBML_ASSIGNMENT_RULE ) {
      asr = (AssignmentRule_t *) rl;
      fprintf(f, " assignmentRule (%s): %s = ",
	     RuleType_toString(AssignmentRule_getType(asr)),
	     AssignmentRule_getVariable(asr));
    }
    if(!Rule_isSetMath(rl)){
      if(Rule_isSetFormula(rl)){
	Rule_setMathFromFormula(rl);
	
      }
    }
    if(Rule_isSetMath(rl))
      fprintf(f, "%s\n", SBML_formulaToString(Rule_getMath(rl)));
	     
  }
  fprintf(f, "\n");

  for(i=0;i<Model_getNumEvents(m);i++){
    if(i==0)
      fprintf(f, "# Events:\n");
    e = Model_getEvent(m,i);
    if(Event_isSetId(e))
      fprintf(f, "%s: ", Event_getId(e));
    if(Event_isSetName(e))
      fprintf(f, "(%s) ", Event_getName(e));   
    if(Event_isSetTrigger(e)) {
      math = Event_getTrigger(e);
      fprintf(f, "trigger: %s\n", SBML_formulaToString(math));
    }
    if(Event_isSetDelay(e))
      fprintf(f, "delay: %s;\n", SBML_formulaToString(Event_getDelay(e)));
    if(Event_isSetTimeUnits(e))
      fprintf(f, "time Units: %s;\n", Event_getTimeUnits(e));
    for(k=0;k<Event_getNumEventAssignments(e);k++){      
      ea = Event_getEventAssignment(e,k);
      if(EventAssignment_isSetVariable(ea))
	fprintf(f, "  event:  %s = %s;\n",
	       EventAssignment_getVariable(ea),
	       EventAssignment_isSetMath(ea) ?
	       SBML_formulaToString(EventAssignment_getMath(ea)) :
	       "# no math set;\n");
    }

    if(i==Model_getNumEvents(m)-1)
       fprintf(f, "\n"); 
  }  


  for ( i=0; i<Model_getNumFunctionDefinitions(m); i++ ) {

    if ( i==0 ) fprintf(f, "# Functions:\n");

    fd = Model_getFunctionDefinition(m,i);
    if ( FunctionDefinition_isSetName(fd) )
      fprintf(f, "%s: ", FunctionDefinition_getName(fd));
    if(FunctionDefinition_isSetId(fd) && FunctionDefinition_isSetMath(fd)){
      fprintf(f, "%s( ", FunctionDefinition_getId(fd));
      math = FunctionDefinition_getMath(fd);
	for(j=0;j<ASTNode_getNumChildren(math)-1;j++){
	  fprintf(f, "%s", SBML_formulaToString(ASTNode_getChild(math, j)));
	  if(j<ASTNode_getNumChildren(math)-2)
	    fprintf(f, ", ");
	  if(j==ASTNode_getNumChildren(math)-2)
	    fprintf(f, ") = ");
	}
      fprintf(f, "%s;", SBML_formulaToString(ASTNode_getRightChild(math)));
    }
    fprintf(f, "\n");
  } 
  
}
Ejemplo n.º 14
0
myResult* simulate_implicit(Model_t *m, myResult *result, mySpecies *sp[], myParameter *param[], myCompartment *comp[], myReaction *re[], myRule *rule[], myEvent *event[], myInitialAssignment *initAssign[], myAlgebraicEquations *algEq, timeVariantAssignments *timeVarAssign, double sim_time, double dt, int print_interval, double *time, int order, int use_lazy_method, int print_amount, allocated_memory *mem){
  unsigned int i, j;
  int cycle;
  int error;
  int end_cycle = get_end_cycle(sim_time, dt);
  double reverse_time;
  double *value_time_p = result->values_time;
  double *value_sp_p = result->values_sp;
  double *value_param_p = result->values_param;
  double *value_comp_p = result->values_comp;
  double **coefficient_matrix = NULL;
  double *constant_vector = NULL;
  int *alg_pivot = NULL;
  double reactants_numerator, products_numerator;
  double min_value;
  double *init_val;
  /* for implicit */
  double **jacobian;
  int is_convergence = 0;
  double *b;
  double *pre_b;
  int    *p; /* for pivot selection */
  boolean flag;
  double delta = 1.0e-8;
  double tolerance = 1.0e-4; /* error tolerance of neuton method */
  unsigned int loop;
  double *delta_value;
  double k_next; /* speculated k value : k(t+1) */
  double *k_t;   /* k(t) */

  /* num of SBase objects */
  unsigned int num_of_species = Model_getNumSpecies(m);
  unsigned int num_of_parameters = Model_getNumParameters(m);
  unsigned int num_of_compartments = Model_getNumCompartments(m);
  unsigned int num_of_reactions = Model_getNumReactions(m);
  unsigned int num_of_rules = Model_getNumRules(m);
  unsigned int num_of_events = Model_getNumEvents(m);
  unsigned int num_of_initialAssignments = Model_getNumInitialAssignments(m);

  /* num of variables whose quantity is not a constant */
  unsigned int num_of_all_var_species = 0;
  unsigned int num_of_all_var_parameters = 0;
  unsigned int num_of_all_var_compartments = 0;
  unsigned int num_of_all_var_species_reference = 0;
  /* num of variables (which is NOT changed by assignment nor algebraic rule) */
  unsigned int num_of_var_species = 0;
  unsigned int num_of_var_parameters = 0;
  unsigned int num_of_var_compartments = 0;
  unsigned int num_of_var_species_reference = 0;
  unsigned int sum_num_of_vars;
  /* All variables (whose quantity is not a constant) */
  mySpecies **all_var_sp;           /* all variable species */
  myParameter **all_var_param;      /* all variable parameters */
  myCompartment **all_var_comp;     /* all variable compartments */
  mySpeciesReference **all_var_spr; /* all varialbe SpeciesReferences */
  /* variables (which is NOT changed by assignment nor algebraic rule) */
  mySpecies **var_sp;
  myParameter **var_param;
  myCompartment **var_comp;
  mySpeciesReference **var_spr;

  set_seed();

  check_num(num_of_species, num_of_parameters, num_of_compartments, num_of_reactions, &num_of_all_var_species, &num_of_all_var_parameters, &num_of_all_var_compartments, &num_of_all_var_species_reference, &num_of_var_species, &num_of_var_parameters, &num_of_var_compartments, &num_of_var_species_reference, sp, param, comp, re);

  /* create objects */
  all_var_sp = (mySpecies **)malloc(sizeof(mySpecies *) * num_of_all_var_species);
  all_var_param = (myParameter **)malloc(sizeof(myParameter *) * num_of_all_var_parameters);
  all_var_comp = (myCompartment **)malloc(sizeof(myCompartment *) * num_of_all_var_compartments);
  all_var_spr = (mySpeciesReference **)malloc(sizeof(mySpeciesReference *) * num_of_all_var_species_reference);
  var_sp = (mySpecies **)malloc(sizeof(mySpecies *) * num_of_var_species);
  var_param = (myParameter **)malloc(sizeof(myParameter *) * num_of_var_parameters);
  var_comp = (myCompartment **)malloc(sizeof(myCompartment *) * num_of_var_compartments);
  var_spr = (mySpeciesReference **)malloc(sizeof(mySpeciesReference *) * num_of_var_species_reference);
  /* mySpecies *all_var_sp[num_of_all_var_species]; */
  /* myParameter *all_var_param[num_of_all_var_parameters]; */
  /* myCompartment *all_var_comp[num_of_all_var_compartments]; */
  /* mySpeciesReference *all_var_spr[num_of_all_var_species_reference]; */
  /* mySpecies *var_sp[num_of_var_species]; */
  /* myParameter *var_param[num_of_var_parameters]; */
  /* myCompartment *var_comp[num_of_var_compartments]; */
  /* mySpeciesReference *var_spr[num_of_var_species_reference]; */

  create_calc_object_list(num_of_species, num_of_parameters, num_of_compartments, num_of_reactions, all_var_sp, all_var_param, all_var_comp, all_var_spr, var_sp, var_param, var_comp, var_spr, sp, param, comp, re);

  sum_num_of_vars = num_of_var_species + num_of_var_parameters +
                    num_of_var_compartments + num_of_var_species_reference;

  jacobian = (double**)malloc(sizeof(double*)*(sum_num_of_vars));
  for(i=0; i<sum_num_of_vars; i++){
    jacobian[i] = (double*)malloc(sizeof(double)*(sum_num_of_vars));
  }

  b = (double *)malloc(sizeof(double) * (sum_num_of_vars));
  pre_b = (double *)malloc(sizeof(double) * (sum_num_of_vars));
  p = (int *)malloc(sizeof(int) * (sum_num_of_vars));
  delta_value = (double *)malloc(sizeof(double) * (sum_num_of_vars));
  k_t = (double *)malloc(sizeof(double) * (sum_num_of_vars));
  /*
  double b[sum_num_of_vars];
  double pre_b[sum_num_of_vars];
  int p[sum_num_of_vars];
  double delta_value[sum_num_of_vars];
  double k_t[sum_num_of_vars];
  */

  if(algEq != NULL){
    coefficient_matrix = (double**)malloc(sizeof(double*)*(algEq->num_of_algebraic_variables));
    for(i=0; i<algEq->num_of_algebraic_variables; i++){
      coefficient_matrix[i] = (double*)malloc(sizeof(double)*(algEq->num_of_algebraic_variables));
    }
    constant_vector = (double*)malloc(sizeof(double)*(algEq->num_of_algebraic_variables));
    alg_pivot = (int*)malloc(sizeof(int)*(algEq->num_of_algebraic_variables));
  }

  PRG_TRACE(("Simulation for [%s] Starts!\n", Model_getId(m)));
  cycle = 0;

  /* initialize delay_val */
  initialize_delay_val(sp, num_of_species, param, num_of_parameters, comp, num_of_compartments, re, num_of_reactions, sim_time, dt, 0);

  /* calc temp value by assignment */
  for(i=0; i<num_of_all_var_species; i++){
    if(all_var_sp[i]->depending_rule != NULL && all_var_sp[i]->depending_rule->is_assignment){
      all_var_sp[i]->temp_value = calc(all_var_sp[i]->depending_rule->eq, dt, cycle, &reverse_time, 0);
    }
  }
  for(i=0; i<num_of_all_var_parameters; i++){
    if(all_var_param[i]->depending_rule != NULL && all_var_param[i]->depending_rule->is_assignment){
      all_var_param[i]->temp_value = calc(all_var_param[i]->depending_rule->eq, dt, cycle, &reverse_time, 0);
    }
  }
  for(i=0; i<num_of_all_var_compartments; i++){
    if(all_var_comp[i]->depending_rule != NULL && all_var_comp[i]->depending_rule->is_assignment){
      all_var_comp[i]->temp_value = calc(all_var_comp[i]->depending_rule->eq, dt, cycle, &reverse_time, 0);
    }
  }
  for(i=0; i<num_of_all_var_species_reference; i++){
    if(all_var_spr[i]->depending_rule != NULL && all_var_spr[i]->depending_rule->is_assignment){
      all_var_spr[i]->temp_value = calc(all_var_spr[i]->depending_rule->eq, dt, cycle, &reverse_time, 0);
    }
  }
  /* forwarding value */
  forwarding_value(all_var_sp, num_of_all_var_species, all_var_param, num_of_all_var_parameters, all_var_comp, num_of_all_var_compartments, all_var_spr, num_of_all_var_species_reference);

  /* initialize delay_val */
  initialize_delay_val(sp, num_of_species, param, num_of_parameters, comp, num_of_compartments, re, num_of_reactions, sim_time, dt, 0);

  /* calc InitialAssignment */
  calc_initial_assignment(initAssign, num_of_initialAssignments, dt, cycle, &reverse_time);

  /* initialize delay_val */
  initialize_delay_val(sp, num_of_species, param, num_of_parameters, comp, num_of_compartments, re, num_of_reactions, sim_time, dt, 0);

  /* rewriting for explicit delay */
  for(i=0; i<num_of_initialAssignments; i++){
    for(j=0; j<initAssign[i]->eq->math_length; j++){
      if(initAssign[i]->eq->number[j] == time){
        TRACE(("time is replaced with reverse time\n"));
        initAssign[i]->eq->number[j] = &reverse_time;
      }else if(initAssign[i]->eq->number[j] != NULL){
        init_val = (double*)malloc(sizeof(double));
        *init_val = *initAssign[i]->eq->number[j];
        mem->memory[mem->num_of_allocated_memory++] = init_val;
        initAssign[i]->eq->number[j] = init_val;
      }
    }
  }
  for(i=0; i<timeVarAssign->num_of_time_variant_assignments; i++){
    for(j=0; j<timeVarAssign->eq[i]->math_length; j++){
      if(timeVarAssign->eq[i]->number[j] == time){
        TRACE(("time is replaced with reverse time\n"));
        timeVarAssign->eq[i]->number[j] = &reverse_time;
      }else if(timeVarAssign->eq[i]->number[j] != NULL){
        init_val = (double*)malloc(sizeof(double));
        *init_val = *timeVarAssign->eq[i]->number[j];
        mem->memory[mem->num_of_allocated_memory++] = init_val;
        timeVarAssign->eq[i]->number[j] = init_val;
      }
    }
  }

  /* initialize delay_val */
  initialize_delay_val(sp, num_of_species, param, num_of_parameters, comp, num_of_compartments, re, num_of_reactions, sim_time, dt, 0);

  /* calc temp value by assignment */
  for(i=0; i<num_of_all_var_species; i++){
    if(all_var_sp[i]->depending_rule != NULL && all_var_sp[i]->depending_rule->is_assignment){
      all_var_sp[i]->temp_value = calc(all_var_sp[i]->depending_rule->eq, dt, cycle, &reverse_time, 0);
    }
  }
  for(i=0; i<num_of_all_var_parameters; i++){
    if(all_var_param[i]->depending_rule != NULL && all_var_param[i]->depending_rule->is_assignment){
      all_var_param[i]->temp_value = calc(all_var_param[i]->depending_rule->eq, dt, cycle, &reverse_time, 0);
    }
  }
  for(i=0; i<num_of_all_var_compartments; i++){
    if(all_var_comp[i]->depending_rule != NULL && all_var_comp[i]->depending_rule->is_assignment){
      all_var_comp[i]->temp_value = calc(all_var_comp[i]->depending_rule->eq, dt, cycle, &reverse_time, 0);
    }
  }
  for(i=0; i<num_of_all_var_species_reference; i++){
    if(all_var_spr[i]->depending_rule != NULL && all_var_spr[i]->depending_rule->is_assignment){
      all_var_spr[i]->temp_value = calc(all_var_spr[i]->depending_rule->eq, dt, cycle, &reverse_time, 0);
    }
  }
  /* forwarding value */
  forwarding_value(all_var_sp, num_of_all_var_species, all_var_param, num_of_all_var_parameters, all_var_comp, num_of_all_var_compartments, all_var_spr, num_of_all_var_species_reference);

  /* initialize delay_val */
  initialize_delay_val(sp, num_of_species, param, num_of_parameters, comp, num_of_compartments, re, num_of_reactions, sim_time, dt, 0);

  /* calc temp value algebraic by algebraic */
  if(algEq != NULL){
    if(algEq->num_of_algebraic_variables > 1){
      /* initialize pivot */
      for(i=0; i<algEq->num_of_algebraic_variables; i++){
        alg_pivot[i] = i;
      }
      for(i=0; i<algEq->num_of_algebraic_variables; i++){
        for(j=0; j<algEq->num_of_algebraic_variables; j++){
          coefficient_matrix[i][j] = calc(algEq->coefficient_matrix[i][j], dt, cycle, &reverse_time, 0);
          /* TRACE(("coefficient matrix[%d][%d] = %lf\n", i, j, coefficient_matrix[i][j])); */
        }
      }
      for(i=0; i<algEq->num_of_algebraic_variables; i++){
        constant_vector[i] = -calc(algEq->constant_vector[i], dt, cycle, &reverse_time, 0);
        /* TRACE(("constant vector[%d] = %lf\n", i, constant_vector[i])); */
      }
      /* LU decompostion */
      error = lu_decomposition(coefficient_matrix, alg_pivot, algEq->num_of_algebraic_variables);
      if(error == 0){/* failure in LU decomposition */
        return NULL;
      }
      /* forward substitution & backward substitution */
      lu_solve(coefficient_matrix, alg_pivot, algEq->num_of_algebraic_variables, constant_vector);
      /*       for(i=0; i<algEq->num_of_algebraic_variables; i++){ */
      /*  TRACE(("ans[%d] = %lf\n", i, constant_vector[i])); */
      /*       } */
      for(i=0; i<algEq->num_of_alg_target_sp; i++){
        algEq->alg_target_species[i]->target_species->temp_value = constant_vector[algEq->alg_target_species[i]->order];
      }    
      for(i=0; i<algEq->num_of_alg_target_param; i++){
        algEq->alg_target_parameter[i]->target_parameter->temp_value = constant_vector[algEq->alg_target_parameter[i]->order];
      }    
      for(i=0; i<algEq->num_of_alg_target_comp; i++){
        /* new code */
        for(j=0; j<algEq->alg_target_compartment[i]->target_compartment->num_of_including_species; j++){
          if(algEq->alg_target_compartment[i]->target_compartment->including_species[j]->is_concentration){
            algEq->alg_target_compartment[i]->target_compartment->including_species[j]->temp_value = algEq->alg_target_compartment[i]->target_compartment->including_species[j]->temp_value*algEq->alg_target_compartment[i]->target_compartment->temp_value/constant_vector[algEq->alg_target_compartment[i]->order];
          }
        }
       /* new code end */
        algEq->alg_target_compartment[i]->target_compartment->temp_value = constant_vector[algEq->alg_target_compartment[i]->order];
      }
    }else{
      if(algEq->target_species != NULL){
        algEq->target_species->temp_value = -calc(algEq->constant, dt, cycle, &reverse_time, 0)/calc(algEq->coefficient, dt, cycle, &reverse_time, 0);
      }
      if(algEq->target_parameter != NULL){
        algEq->target_parameter->temp_value = -calc(algEq->constant, dt, cycle, &reverse_time, 0)/calc(algEq->coefficient, dt, cycle, &reverse_time, 0);
      }
      if(algEq->target_compartment != NULL){
        /* new code */
        for(i=0; i<algEq->target_compartment->num_of_including_species; i++){
          if(algEq->target_compartment->including_species[i]->is_concentration){
            algEq->target_compartment->including_species[i]->temp_value = algEq->target_compartment->including_species[i]->temp_value*algEq->target_compartment->temp_value/(-calc(algEq->constant, dt, cycle, &reverse_time, 0)/calc(algEq->coefficient, dt, cycle, &reverse_time, 0));
          }
        }
       /* new code end */
        algEq->target_compartment->temp_value = -calc(algEq->constant, dt, cycle, &reverse_time, 0)/calc(algEq->coefficient, dt, cycle, &reverse_time, 0);
      }
    }
    /* forwarding value */
    forwarding_value(all_var_sp, num_of_all_var_species, all_var_param, num_of_all_var_parameters, all_var_comp, num_of_all_var_compartments, all_var_spr, num_of_all_var_species_reference);
  }

  /* initialize delay_val */
  initialize_delay_val(sp, num_of_species, param, num_of_parameters, comp, num_of_compartments, re, num_of_reactions, sim_time, dt, 1);

  /* cycle start */
  for(cycle=0; cycle<=end_cycle; cycle++){
    /* calculate unreversible fast reaction */
    for(i=0; i<num_of_reactions; i++){
      if(re[i]->is_fast && !re[i]->is_reversible){
        if(calc(re[i]->eq, dt, cycle, &reverse_time, 0) > 0){
          min_value = DBL_MAX;
          for(j=0; j<re[i]->num_of_reactants; j++){
            if(min_value > re[i]->reactants[j]->mySp->value/calc(re[i]->reactants[j]->eq, dt, cycle, &reverse_time, 0)){
              min_value = re[i]->reactants[j]->mySp->value/calc(re[i]->reactants[j]->eq, dt, cycle, &reverse_time, 0);
            }
          }
          for(j=0; j<re[i]->num_of_products; j++){
            if(!Species_getBoundaryCondition(re[i]->products[j]->mySp->origin)){
              re[i]->products[j]->mySp->value += calc(re[i]->products[j]->eq, dt, cycle, &reverse_time, 0)*min_value;
              re[i]->products[j]->mySp->temp_value = re[i]->products[j]->mySp->value;
            }
          }
          for(j=0; j<re[i]->num_of_reactants; j++){
            if(!Species_getBoundaryCondition(re[i]->reactants[j]->mySp->origin)){
              re[i]->reactants[j]->mySp->value -= calc(re[i]->reactants[j]->eq, dt, cycle, &reverse_time, 0)*min_value;
              re[i]->reactants[j]->mySp->temp_value = re[i]->reactants[j]->mySp->value;
            }
          }
        }
      }
    }
    /* calculate reversible fast reactioin */
    for(i=0; i<num_of_reactions; i++){
      if(re[i]->is_fast && re[i]->is_reversible){
        if(!(Species_getBoundaryCondition(re[i]->products[0]->mySp->origin) 
              && Species_getBoundaryCondition(re[i]->reactants[0]->mySp->origin))){
          products_numerator = calc(re[i]->products_equili_numerator, dt, cycle, &reverse_time, 0);
          reactants_numerator = calc(re[i]->reactants_equili_numerator, dt, cycle, &reverse_time, 0);
          if(products_numerator > 0 || reactants_numerator > 0){
            if(Species_getBoundaryCondition(re[i]->products[0]->mySp->origin)){
              re[i]->reactants[0]->mySp->value = (reactants_numerator/products_numerator)*re[i]->products[0]->mySp->value;
              re[i]->reactants[0]->mySp->temp_value = re[i]->reactants[0]->mySp->value;
            }else if(Species_getBoundaryCondition(re[i]->reactants[0]->mySp->origin)){
              re[i]->products[0]->mySp->value = (products_numerator/reactants_numerator)*re[i]->reactants[0]->mySp->value;
              re[i]->products[0]->mySp->temp_value = re[i]->products[0]->mySp->value;	    
            }else{
              re[i]->products[0]->mySp->value = (products_numerator/(products_numerator+reactants_numerator))*(re[i]->products[0]->mySp->temp_value+re[i]->reactants[0]->mySp->temp_value);
              re[i]->reactants[0]->mySp->value = (reactants_numerator/(products_numerator+reactants_numerator))*(re[i]->products[0]->mySp->temp_value+re[i]->reactants[0]->mySp->temp_value);
              re[i]->products[0]->mySp->temp_value = re[i]->products[0]->mySp->value;
              re[i]->reactants[0]->mySp->temp_value = re[i]->reactants[0]->mySp->value;
            }
          }
        }
      }
    }

    /* event */
    calc_event(event, num_of_events, dt, *time, cycle, &reverse_time);    

    /* substitute delay val */
    substitute_delay_val(sp, num_of_species, param, num_of_parameters, comp, num_of_compartments, re, num_of_reactions, cycle);

    /* progress */
    if(cycle%(int)(end_cycle/10) == 0){
      PRG_TRACE(("%3d %%\n", (int)(100*((double)cycle/(double)end_cycle))));
      PRG_TRACE(("\x1b[1A"));
      PRG_TRACE(("\x1b[5D"));
    }
    /* print result */
    if(cycle%print_interval == 0){
      /*  Time */
      *value_time_p = *time;
      value_time_p++;
      /*  Species */
      for(i=0; i<num_of_species; i++){
        /*         if(!(Species_getConstant(sp[i]->origin) && Species_getBoundaryCondition(sp[i]->origin))){ // XXX must remove this */
        if(print_amount){
          if(sp[i]->is_concentration){
            *value_sp_p = sp[i]->value*sp[i]->locating_compartment->value;
          }else{
            *value_sp_p = sp[i]->value;
          }
        }else{
          if(sp[i]->is_amount){
            *value_sp_p = sp[i]->value/sp[i]->locating_compartment->value;
          }else{
            *value_sp_p = sp[i]->value;
          }
        }
        value_sp_p++;
        /*         } */
      }
      /*  Parameter */
      for(i=0; i<num_of_parameters; i++){
        /*         if(!Parameter_getConstant(param[i]->origin)){ // XXX must remove this */
        *value_param_p = param[i]->value;
        /*         } */
        value_param_p++;
      }
      /*  Compartment */
      for(i=0; i<num_of_compartments; i++){
        /*         if(!Compartment_getConstant(comp[i]->origin)){ // XXX must remove this */
        *value_comp_p = comp[i]->value;
        /*         } */
        value_comp_p++;
      }
    }

    /* time increase */
    *time = (cycle+1)*dt;

    /* implicit method */
    /* define init value by Euler start */
    calc_k(all_var_sp, num_of_all_var_species, all_var_param, num_of_all_var_parameters, all_var_comp, num_of_all_var_compartments, all_var_spr, num_of_all_var_species_reference, re, num_of_reactions, rule, num_of_rules, cycle, dt, &reverse_time, 0, 1);

    /* preserve k(t) value */
    for(i=0; i<sum_num_of_vars; i++){
      if(i < num_of_var_species){
        k_t[i] = var_sp[i]->k[0];
      }else if(i < num_of_var_species+num_of_var_parameters){
        k_t[i] = var_param[i-num_of_var_species]->k[0];
      }else if(i < num_of_var_species+num_of_var_parameters+num_of_var_compartments){
        k_t[i] = var_comp[i-num_of_var_species-num_of_var_parameters]->k[0];
      }else{
        k_t[i] = var_spr[i-num_of_var_species-num_of_var_parameters-num_of_var_compartments]->k[0];
      }
    }

    calc_temp_value(all_var_sp, num_of_all_var_species, all_var_param, num_of_all_var_parameters, all_var_comp, num_of_all_var_compartments, all_var_spr, num_of_all_var_species_reference, dt, 0);
    /* define init value by Euler end */

    /* newton method */
    if(use_lazy_method){
      is_convergence = 0;
      for(i=0; i<sum_num_of_vars; i++){
        pre_b[i] = 0;
      }
    }
    flag = 1;
    while(flag){
      /* calc b */
      calc_k(var_sp, num_of_var_species, var_param, num_of_var_parameters, var_comp, num_of_var_compartments, var_spr, num_of_var_species_reference, re, num_of_reactions, rule, num_of_rules, cycle, dt, &reverse_time, 0, 0);
      for(i=0; i<num_of_var_species; i++){
        k_next = var_sp[i]->k[0];
        b[i] = calc_implicit_formula(order, var_sp[i]->temp_value, var_sp[i]->value, var_sp[i]->prev_val[0], var_sp[i]->prev_val[1], var_sp[i]->prev_val[2], k_next, k_t[i], var_sp[i]->prev_k[0], var_sp[i]->prev_k[1], dt);
      }
      for(i=0; i<num_of_var_parameters; i++){
        b[num_of_var_species+i] = calc_implicit_formula(order, var_param[i]->temp_value, var_param[i]->value, var_param[i]->prev_val[0], var_param[i]->prev_val[1], var_param[i]->prev_val[2], var_param[i]->k[0], k_t[num_of_var_species+i], var_param[i]->prev_k[0], var_param[i]->prev_k[1], dt);
      }
      for(i=0; i<num_of_var_compartments; i++){
        b[num_of_var_species+num_of_var_parameters+i] = calc_implicit_formula(order, var_comp[i]->temp_value, var_comp[i]->value, var_comp[i]->prev_val[0], var_comp[i]->prev_val[1], var_comp[i]->prev_val[2], var_comp[i]->k[0], k_t[num_of_var_species+num_of_var_parameters+i], var_comp[i]->prev_k[0], var_comp[i]->prev_k[1], dt);
      }
      for(i=0; i<num_of_var_species_reference; i++){
        b[num_of_var_species+num_of_var_parameters+num_of_var_compartments+i] = calc_implicit_formula(order, var_spr[i]->temp_value, var_spr[i]->value, var_spr[i]->prev_val[0], var_spr[i]->prev_val[1], var_spr[i]->prev_val[2], var_spr[i]->k[0], k_t[num_of_var_species+num_of_var_parameters+num_of_var_compartments+i], var_spr[i]->prev_k[0], var_spr[i]->prev_k[1], dt);
      }

      if(!use_lazy_method || !is_convergence){
        /* calc jacobian by numerical differentiation */
        for(loop=0; loop<sum_num_of_vars; loop++){
          if(loop < num_of_var_species){
            var_sp[loop]->temp_value += delta;
          }else if(loop < num_of_var_species+num_of_var_parameters){
            var_param[loop-num_of_var_species]->temp_value += delta;
          }else if(loop < num_of_var_species+num_of_var_parameters+num_of_var_compartments){
            var_comp[loop-num_of_var_species-num_of_var_parameters]->temp_value += delta;
          }else{
            var_spr[loop-num_of_var_species-num_of_var_parameters-num_of_var_compartments]->temp_value += delta;
          }
          calc_k(var_sp, num_of_var_species, var_param, num_of_var_parameters, var_comp, num_of_var_compartments, var_spr, num_of_var_species_reference, re, num_of_reactions, rule, num_of_rules, cycle, dt, &reverse_time, 0, 0);
          for(i=0; i<num_of_var_species; i++){
            k_next = var_sp[i]->k[0];
            delta_value[i] = calc_implicit_formula(order, var_sp[i]->temp_value, var_sp[i]->value, var_sp[i]->prev_val[0], var_sp[i]->prev_val[1], var_sp[i]->prev_val[2], k_next, k_t[i], var_sp[i]->prev_k[0], var_sp[i]->prev_k[1], dt);
            /* numerical differentiation */
            jacobian[i][loop] = (delta_value[i]-b[i])/delta;
          }
          for(i=0; i<num_of_var_parameters; i++){
            delta_value[num_of_var_species+i] = calc_implicit_formula(order, var_param[i]->temp_value, var_param[i]->value, var_param[i]->prev_val[0], var_param[i]->prev_val[1], var_param[i]->prev_val[2], var_param[i]->k[0], k_t[num_of_var_species+i], var_param[i]->prev_k[0], var_param[i]->prev_k[1], dt);
            /* numerical differentiation */
            jacobian[num_of_var_species+i][loop] = (delta_value[num_of_var_species+i]-b[num_of_var_species+i])/delta;
          }
          for(i=0; i<num_of_var_compartments; i++){
            delta_value[num_of_var_species+num_of_var_parameters+i] = calc_implicit_formula(order, var_comp[i]->temp_value, var_comp[i]->value, var_comp[i]->prev_val[0], var_comp[i]->prev_val[1], var_comp[i]->prev_val[2], var_comp[i]->k[0], k_t[num_of_var_species+num_of_var_parameters+i], var_comp[i]->prev_k[0], var_comp[i]->prev_k[1], dt);
            /* numerical differentiation */
            jacobian[num_of_var_species+num_of_var_parameters+i][loop] = (delta_value[num_of_var_species+num_of_var_parameters+i]-b[num_of_var_species+num_of_var_parameters+i])/delta;
          }
          for(i=0; i<num_of_var_species_reference; i++){
            delta_value[num_of_var_species+num_of_var_parameters+num_of_var_compartments+i] = calc_implicit_formula(order, var_spr[i]->temp_value, var_spr[i]->value, var_spr[i]->prev_val[0], var_spr[i]->prev_val[1], var_spr[i]->prev_val[2], var_spr[i]->k[0], k_t[num_of_var_species+num_of_var_parameters+num_of_var_compartments+i], var_spr[i]->prev_k[0], var_spr[i]->prev_k[1], dt);
            /* numerical differentiation */
            jacobian[num_of_var_species+num_of_var_parameters+num_of_var_compartments+i][loop] = (delta_value[num_of_var_species+num_of_var_parameters+num_of_var_compartments+i]-b[num_of_var_species+num_of_var_parameters+num_of_var_compartments+i])/delta;
          }
          if(loop < num_of_var_species){
            var_sp[loop]->temp_value -= delta;
          }else if(loop < num_of_var_species+num_of_var_parameters){
            var_param[loop-num_of_var_species]->temp_value -= delta;
          }else if(loop < num_of_var_species+num_of_var_parameters+num_of_var_compartments){
            var_comp[loop-num_of_var_species-num_of_var_parameters]->temp_value -= delta;
          }else{
            var_spr[loop-num_of_var_species-num_of_var_parameters-num_of_var_compartments]->temp_value -= delta;
          }
        }
      }

      /* initialize p */
      for(i=0; i<sum_num_of_vars; i++){
        p[i] = i;
      }

      /* LU decomposition */
      error = lu_decomposition(jacobian, p, sum_num_of_vars);
      if(error == 0){/* failure in LU decomposition */
        return NULL;
      }

      /* forward substitution & backward substitution */
      lu_solve(jacobian, p, sum_num_of_vars, b);

      /* calculate next temp value */
      for(i=0; i<sum_num_of_vars; i++){
        if(i < num_of_var_species){
          var_sp[i]->temp_value -= b[i];
        }else if(i < num_of_var_species+num_of_var_parameters){
          var_param[i-num_of_var_species]->temp_value -= b[i];
        }else if(i < num_of_var_species+num_of_var_parameters+num_of_var_compartments){
          var_comp[i-num_of_var_species-num_of_var_parameters]->temp_value -= b[i];
        }else{
          var_spr[i-num_of_var_species-num_of_var_parameters-num_of_var_compartments]->temp_value -= b[i];
        }
      }

      /* convergence judgement */
      if(use_lazy_method){
        is_convergence = 1;
        for(i=0; i<sum_num_of_vars; i++){
          if(fabs(b[i]) > fabs(pre_b[i])){
            is_convergence = 0;
          }
        }
        for(i=0; i<sum_num_of_vars; i++){
          pre_b[i] = b[i];
        }
      }

      /* error judgement */
      flag = 0;
      for(i=0; i<sum_num_of_vars; i++){
        if(fabs(b[i]) > tolerance){
          flag = 1;
        }
      }
    }

    /* calc temp value by assignment */
    for(i=0; i<num_of_all_var_species; i++){
      if(all_var_sp[i]->depending_rule != NULL && all_var_sp[i]->depending_rule->is_assignment){
        all_var_sp[i]->temp_value = calc(all_var_sp[i]->depending_rule->eq, dt, cycle, &reverse_time, 0);
      }
    }
    for(i=0; i<num_of_all_var_parameters; i++){
      if(all_var_param[i]->depending_rule != NULL && all_var_param[i]->depending_rule->is_assignment){
        all_var_param[i]->temp_value = calc(all_var_param[i]->depending_rule->eq, dt, cycle, &reverse_time, 0);
      }
    }
    for(i=0; i<num_of_all_var_compartments; i++){
      if(all_var_comp[i]->depending_rule != NULL && all_var_comp[i]->depending_rule->is_assignment){
        all_var_comp[i]->temp_value = calc(all_var_comp[i]->depending_rule->eq, dt, cycle, &reverse_time, 0);
      }
    }
    for(i=0; i<num_of_all_var_species_reference; i++){
      if(all_var_spr[i]->depending_rule != NULL && all_var_spr[i]->depending_rule->is_assignment){
        all_var_spr[i]->temp_value = calc(all_var_spr[i]->depending_rule->eq, dt, cycle, &reverse_time, 0);
      }
    }

    /* calc temp value algebraic by algebraic */
    if(algEq != NULL){
      if(algEq->num_of_algebraic_variables > 1){
        /* initialize pivot */
        for(i=0; i<algEq->num_of_algebraic_variables; i++){
          alg_pivot[i] = i;
        }
        for(i=0; i<algEq->num_of_algebraic_variables; i++){
          for(j=0; j<algEq->num_of_algebraic_variables; j++){
            coefficient_matrix[i][j] = calc(algEq->coefficient_matrix[i][j], dt, cycle, &reverse_time, 0);
          }
        }
        for(i=0; i<algEq->num_of_algebraic_variables; i++){
          constant_vector[i] = -calc(algEq->constant_vector[i], dt, cycle, &reverse_time, 0);
        }
        /* LU decompostion */
        error = lu_decomposition(coefficient_matrix, alg_pivot, algEq->num_of_algebraic_variables);
        if(error == 0){/* failure in LU decomposition */
          return NULL;
        }
        /* forward substitution & backward substitution */
        lu_solve(coefficient_matrix, alg_pivot, algEq->num_of_algebraic_variables, constant_vector);
        for(i=0; i<algEq->num_of_alg_target_sp; i++){
          algEq->alg_target_species[i]->target_species->temp_value = constant_vector[algEq->alg_target_species[i]->order];
        }    
        for(i=0; i<algEq->num_of_alg_target_param; i++){
          algEq->alg_target_parameter[i]->target_parameter->temp_value = constant_vector[algEq->alg_target_parameter[i]->order];
        }    
        for(i=0; i<algEq->num_of_alg_target_comp; i++){
          /* new code */
          for(j=0; j<algEq->alg_target_compartment[i]->target_compartment->num_of_including_species; j++){
            if(algEq->alg_target_compartment[i]->target_compartment->including_species[j]->is_concentration){
              algEq->alg_target_compartment[i]->target_compartment->including_species[j]->temp_value = algEq->alg_target_compartment[i]->target_compartment->including_species[j]->temp_value*algEq->alg_target_compartment[i]->target_compartment->temp_value/constant_vector[algEq->alg_target_compartment[i]->order];
            }
          }
         /* new code end */
          algEq->alg_target_compartment[i]->target_compartment->temp_value = constant_vector[algEq->alg_target_compartment[i]->order];
        }    
      }else{
        if(algEq->target_species != NULL){
          algEq->target_species->temp_value = -calc(algEq->constant, dt, cycle, &reverse_time, 0)/calc(algEq->coefficient, dt, cycle, &reverse_time, 0);
        }
        if(algEq->target_parameter != NULL){
          algEq->target_parameter->temp_value = -calc(algEq->constant, dt, cycle, &reverse_time, 0)/calc(algEq->coefficient, dt, cycle, &reverse_time, 0);
        }
        if(algEq->target_compartment != NULL){
          /* new code */
          for(i=0; i<algEq->target_compartment->num_of_including_species; i++){
            if(algEq->target_compartment->including_species[i]->is_concentration){
              algEq->target_compartment->including_species[i]->temp_value = algEq->target_compartment->including_species[i]->temp_value*algEq->target_compartment->temp_value/(-calc(algEq->constant, dt, cycle, &reverse_time, 0)/calc(algEq->coefficient, dt, cycle, &reverse_time, 0));
            }
          }
         /* new code end */
          algEq->target_compartment->temp_value = -calc(algEq->constant, dt, cycle, &reverse_time, 0)/calc(algEq->coefficient, dt, cycle, &reverse_time, 0);
        }
      }
    }

    /* preserve prev_value and prev_k for multistep solution */
    for(i=0; i<num_of_var_species; i++){
      var_sp[i]->prev_val[2] = var_sp[i]->prev_val[1];
      var_sp[i]->prev_val[1] = var_sp[i]->prev_val[0];
      var_sp[i]->prev_val[0] = var_sp[i]->value;
      var_sp[i]->prev_k[2] = var_sp[i]->prev_k[1];
      var_sp[i]->prev_k[1] = var_sp[i]->prev_k[0];
      var_sp[i]->prev_k[0] = k_t[i];
    }
    for(i=0; i<num_of_var_parameters; i++){
      var_param[i]->prev_val[2] = var_param[i]->prev_val[1];
      var_param[i]->prev_val[1] = var_param[i]->prev_val[0];
      var_param[i]->prev_val[0] = var_param[i]->value;
      var_param[i]->prev_k[2] = var_param[i]->prev_k[1];
      var_param[i]->prev_k[1] = var_param[i]->prev_k[0];
      var_param[i]->prev_k[0] = k_t[num_of_var_species+i];
    }
    for(i=0; i<num_of_var_compartments; i++){
      var_comp[i]->prev_val[2] = var_comp[i]->prev_val[1];
      var_comp[i]->prev_val[1] = var_comp[i]->prev_val[0];
      var_comp[i]->prev_val[0] = var_comp[i]->value;
      var_comp[i]->prev_k[2] = var_comp[i]->prev_k[1];
      var_comp[i]->prev_k[1] = var_comp[i]->prev_k[0];
      var_comp[i]->prev_k[0] = k_t[num_of_var_species+num_of_var_parameters+i];
    }
    for(i=0; i<num_of_var_species_reference; i++){
      var_spr[i]->prev_val[2] = var_spr[i]->prev_val[1];
      var_spr[i]->prev_val[1] = var_spr[i]->prev_val[0];
      var_spr[i]->prev_val[0] = var_spr[i]->value;
      var_spr[i]->prev_k[2] = var_spr[i]->prev_k[1];
      var_spr[i]->prev_k[1] = var_spr[i]->prev_k[0];
      var_spr[i]->prev_k[0] = k_t[num_of_var_species+num_of_var_parameters+i];
    }

    /* forwarding value */
    forwarding_value(all_var_sp, num_of_all_var_species, all_var_param, num_of_all_var_parameters, all_var_comp, num_of_all_var_compartments, all_var_spr, num_of_all_var_species_reference);
  }
  PRG_TRACE(("Simulation for [%s] Ends!\n", Model_getId(m)));
  if(algEq != NULL){
    for(i=0; i<algEq->num_of_algebraic_variables; i++){
      free(coefficient_matrix[i]);
    }
    free(coefficient_matrix);
    free(constant_vector);
    free(alg_pivot);
  }
  for(i=0; i<sum_num_of_vars; i++){
    free(jacobian[i]);
  }
  free(all_var_sp);
  free(all_var_param);
  free(all_var_comp);
  free(all_var_spr);
  free(var_sp);
  free(var_param);
  free(var_comp);
  free(var_spr);
  /* for implicit */
  free(jacobian);
  return result;
}
Ejemplo n.º 15
0
int
main (int argc, char* argv[])
{
  unsigned int i,j,errors;
  const char* filename   = argv[1];
  SBMLDocument_t* document;
  Model_t* m;

  if (argc != 3)
  {
    printf("\nUsage: unsetNotes <input-filename> <output-filename>\n");
    return 1;
  }

  filename = argv[1];  
  document = readSBML(filename);

  errors =  SBMLDocument_getNumErrors(document);

  if(errors > 0)
  {
    SBMLDocument_printErrors(document, stderr);
    SBMLDocument_free(document);
    return errors;
  }

  m = SBMLDocument_getModel( document );
  SBase_unsetNotes((SBase_t*)m);

  for(i=0; i < Model_getNumReactions(m); i++)
  {
    Reaction_t* re = Model_getReaction(m, i);
    SBase_unsetNotes((SBase_t*)re);

    for(j=0; j < Reaction_getNumReactants(re); j++)
    {
      SpeciesReference_t* rt = Reaction_getReactant(re,j);
      SBase_unsetNotes((SBase_t*)rt);
    }

    for(j=0; j < Reaction_getNumProducts(re); j++)
    {
      SpeciesReference_t* rt = Reaction_getProduct(re,j);
      SBase_unsetNotes((SBase_t*)rt);
    }

    for(j=0; j < Reaction_getNumModifiers(re); j++)
    {
      SpeciesReference_t* md = Reaction_getModifier(re,j);
      SBase_unsetNotes((SBase_t*)md);
    }

    if(Reaction_isSetKineticLaw(re))
    {
      KineticLaw_t* kl =  Reaction_getKineticLaw(re);
      SBase_unsetNotes((SBase_t*)kl);

      for(j=0; j < KineticLaw_getNumParameters(kl); j++)
      {
        Parameter_t* pa = KineticLaw_getParameter(kl, j);
        SBase_unsetNotes((SBase_t*)pa);
      }
    }

  }

  for(i=0; i < Model_getNumSpecies(m); i++)
  {
    Species_t* sp = Model_getSpecies(m, i);
    SBase_unsetNotes((SBase_t*)sp);
  }

  for(i=0; i < Model_getNumCompartments(m); i++)
  {
    Compartment_t* sp = Model_getCompartment(m,i);
    SBase_unsetNotes((SBase_t*)sp);
  }

  for(i=0; i < Model_getNumFunctionDefinitions(m); i++)
  {
    FunctionDefinition_t* sp = Model_getFunctionDefinition(m,i);
    SBase_unsetNotes((SBase_t*)sp);
  }

  for(i=0; i < Model_getNumUnitDefinitions(m); i++)
  {
    UnitDefinition_t* sp = Model_getUnitDefinition(m, i);
    SBase_unsetNotes((SBase_t*)sp);
  }

  for(i=0; i < Model_getNumParameters(m); i++)
  {
    Parameter_t* sp = Model_getParameter(m, i);
    SBase_unsetNotes((SBase_t*)sp);
  }

  for(i=0; i < Model_getNumRules(m); i++)
  {
    Rule_t* sp = Model_getRule(m, i);
    SBase_unsetNotes((SBase_t*)sp);
  }

  for(i=0; i < Model_getNumInitialAssignments(m); i++)
  {
    InitialAssignment_t* sp = Model_getInitialAssignment(m, i);
    SBase_unsetNotes((SBase_t*)sp);
  }

  for(i=0; i < Model_getNumEvents(m); i++)
  {
    Event_t* sp = Model_getEvent(m, i);
    SBase_unsetNotes((SBase_t*)sp);

    for(j=0; j < Event_getNumEventAssignments(sp); j++)
    {
      EventAssignment_t* ea = Event_getEventAssignment(sp, j);
      SBase_unsetNotes((SBase_t*)ea);
    }
  }

  for(i=0; i < Model_getNumSpeciesTypes(m); i++)
  {
    SpeciesType_t* sp = Model_getSpeciesType(m, i);
    SBase_unsetNotes((SBase_t*)sp);
  }

  for(i=0; i < Model_getNumConstraints(m); i++)
  {
    Constraint_t* sp = Model_getConstraint(m, i);
    SBase_unsetNotes((SBase_t*)sp);
  }

  writeSBML(document, argv[2]);

  SBMLDocument_free(document);
  return errors;
}
Ejemplo n.º 16
0
void printReactionTimeCourse(cvodeData_t *data, Model_t *m, FILE *f)
{
  int i, j;
  cvodeResults_t *results;
  Reaction_t *r;
  KineticLaw_t *kl;
  ASTNode_t **kls;

  if ( data == NULL || data->results == NULL ) {
    Warn(stderr, "No results, please integrate first.\n");
    return;
  }

#if USE_GRACE
  if ( Opt.Xmgrace == 1 ) {
    printXMGReactionTimeCourse(data);
    return;
  }
#endif  
  
  results = data->results;
  if ( Opt.PrintMessage )
    fprintf(stderr,
	    "\nPrinting time course of the reactions (kinetic laws).\n\n");

  if(!(kls =
       (ASTNode_t **)calloc(Model_getNumReactions(m),
			    sizeof(ASTNode_t *)))) {
    fprintf(stderr, "failed!\n");
  }

  fprintf(f, "#t ");
  for ( i=0; i<Model_getNumReactions(m); i++ ) {
    r = Model_getReaction(m, i);
    kl = Reaction_getKineticLaw(r);
    kls[i] = copyAST(KineticLaw_getMath(kl));
    AST_replaceNameByParameters(kls[i], KineticLaw_getListOfParameters(kl));
    AST_replaceConstants(m, kls[i]);
    fprintf(f, "%s ", Reaction_getId(r));
  }
  fprintf(f, "\n");
  fprintf(f, "##REACTION RATES\n"); 
  for ( i=0; i<=results->nout; ++i ) {
    fprintf(f, "%g ", results->time[i]);
    data->currenttime = results->time[i];
    for ( j=0; j<data->model->neq; j++ ) {
      data->value[j] = results->value[j][i];
    }
    for ( j=0; j<Model_getNumReactions(m); j++ ) {      
      
      fprintf(f, "%g ", evaluateAST(kls[j], data));
    }
    fprintf(f, "\n");
  }
  fprintf(f, "##REACTION RATES\n"); 
  fprintf(f, "#t ");
  for ( i=0; i<Model_getNumReactions(m); i++ ) {
    r = Model_getReaction(m, i);
    fprintf(f, "%s ", Reaction_getId(r));
    ASTNode_free(kls[i]);
  }
  free(kls);
  fprintf(f, "\n");
  fflush(f);
  
#if !USE_GRACE
  if ( Opt.Xmgrace == 1 ) {
    fprintf(stderr,
	    "odeSolver has been compiled without XMGRACE functionality.\n");
    fprintf(stderr,
	    "The requested data have been printed to stdout instead.\n");
  }
#endif
  
}
Ejemplo n.º 17
0
int
main (int argc, char* argv[])
{
  unsigned int i,j,errors;
  const char* filename;
  SBMLDocument_t* document;
  Model_t* m;

  if (argc != 2)
  {
    printf("\nUsage: printNotes filename\n\n");
    return 1;
  }

  filename  = argv[1];
  document  = readSBML(filename);

  errors = SBMLDocument_getNumErrors( document);

  printf("\n%s\n\n", filename);

  if(errors > 0)
  {
    SBMLDocument_printErrors(document, stderr);
    SBMLDocument_free(document);
    return errors;
  }


  /* Model */

  m = SBMLDocument_getModel(document);
  printNotes((SBase_t*)m, Model_getId(m));

  for(i=0; i < Model_getNumReactions(m); i++)
  {
    Reaction_t* re = Model_getReaction( m, i);
    printNotes((SBase_t*)re, Reaction_getId(re));

    /* SpeciesReference (Reactant) */

    for(j=0; j < Reaction_getNumReactants( re); j++)
    {
      SpeciesReference_t* rt =  Reaction_getReactant(re, j);
      if (SBase_isSetNotes((SBase_t*) rt)) printf("   ");
      printNotes((SBase_t*)rt, SpeciesReference_getSpecies( rt ) );
    }

    /* SpeciesReference (Product) */

    for(j=0; j < Reaction_getNumProducts( re ); j++)
    {
      SpeciesReference_t* rt = Reaction_getProduct( re, j);
      if (SBase_isSetNotes((SBase_t*) rt)) printf("   ");
      printNotes((SBase_t*)rt, SpeciesReference_getSpecies( rt ) );
    }

    /* ModifierSpeciesReference (Modifiers) */

    for(j=0; j < Reaction_getNumModifiers( re ); j++)
    {
      SpeciesReference_t* md = Reaction_getModifier(re, j);
      if (SBase_isSetNotes((SBase_t*) md)) printf("   ");
      printNotes((SBase_t*)md, SpeciesReference_getSpecies( md ) );
    }

    /* KineticLaw */

    if(Reaction_isSetKineticLaw( re ))
    {
      KineticLaw_t* kl = Reaction_getKineticLaw( re );
      if (SBase_isSetNotes((SBase_t*) kl)) printf("   ");
      printNotes((SBase_t*)kl, "");

      /* Parameter */

      for(j=0; j < KineticLaw_getNumParameters( kl ); j++)
      {
        Parameter_t* pa = KineticLaw_getParameter( kl, j);
        if (SBase_isSetNotes((SBase_t*) pa)) printf("   ");
        printNotes((SBase_t*)pa, Parameter_getId(pa));
      }
    }

  }

  /* Species */

  for(i=0; i < Model_getNumSpecies(m); i++)
  {
    Species_t* sp = Model_getSpecies(m, i);
    printNotes((SBase_t*)sp, Species_getId(sp));
  }

  /* Compartments */

  for(i=0; i < Model_getNumCompartments( m ); i++)
  {
    Compartment_t* sp = Model_getCompartment(m, i);
    printNotes((SBase_t*)sp, Compartment_getId(sp));
  }

  /* FunctionDefinition */

  for(i=0; i < Model_getNumFunctionDefinitions(m); i++)
  {
    FunctionDefinition_t* sp = Model_getFunctionDefinition(m, i);
    printNotes((SBase_t*)sp, FunctionDefinition_getId(sp));
  }

  /* UnitDefinition */

  for(i=0; i < Model_getNumUnitDefinitions(m); i++)
  {
    UnitDefinition_t* sp = Model_getUnitDefinition( m, i);
    printNotes((SBase_t*)sp, UnitDefinition_getId(sp));
  }

  /* Parameter */

  for(i=0; i < Model_getNumParameters( m ); i++)
  {
    Parameter_t* sp = Model_getParameter( m, i);
    printNotes((SBase_t*)sp, Parameter_getId(sp));
  }

  /* Rule */

  for(i=0; i < Model_getNumReactions( m ); i++)
  {
    Rule_t* sp = Model_getRule(m, i);
    printNotes((SBase_t*)sp, "");
  }

  /* InitialAssignment */

  for(i=0; i < Model_getNumInitialAssignments(m); i++)
  {
    InitialAssignment_t* sp = Model_getInitialAssignment(m, i);
    printNotes((SBase_t*)sp, "");
  }

  /* Event */

  for(i=0; i < Model_getNumEvents(m); i++)
  {
    Event_t* sp = Model_getEvent(m, i);
    printNotes((SBase_t*)sp, Event_getId(sp));

    /* Trigger */

    if(Event_isSetTrigger( sp ))
    {
      Trigger_t* tg = Event_getTrigger(sp);
      if (SBase_isSetNotes( (SBase_t*) tg)) printf( "   " );
      printNotes((SBase_t*)tg, "");
    }

    /* Delay */

    if(Event_isSetDelay(sp))
    {
      Delay_t* dl = Event_getDelay(sp);
      if (SBase_isSetNotes( (SBase_t*) dl)) printf( "   " );
      printNotes((SBase_t*) dl, "");
    }

    /* EventAssignment */

    for(j=0; j < Event_getNumEventAssignments(sp); j++)
    {
      EventAssignment_t* ea = Event_getEventAssignment(sp, j);
      if (SBase_isSetNotes( (SBase_t*) ea)) printf( "   " );      
      printNotes((SBase_t*)ea, "");
    }
  }

  /* SpeciesType */

  for(i=0; i < Model_getNumSpeciesTypes(m); i++)
  {
    SpeciesType_t* sp = Model_getSpeciesType(m, i);
    printNotes((SBase_t*)sp, SpeciesType_getId(sp));
  }

  /* Constraints */

  for(i=0; i < Model_getNumConstraints(m); i++)
  {
    Constraint_t* sp = Model_getConstraint(m, i);
    printNotes((SBase_t*)sp, "");
  }

  SBMLDocument_free( document );
  return errors;
}
Ejemplo n.º 18
0
static int printXMGReactionTimeCourse ( cvodeData_t *data )
{

  int i, j, k, n;
  double maxY, minY, result;
  
  Model_t *m;
  Reaction_t *r;
  KineticLaw_t *kl;
  ASTNode_t **kls;
  
  odeModel_t *om = data->model;
  cvodeResults_t *results = data->results;

  maxY = 0.0;
  minY = 0.0;

  fprintf(stderr,
	  "Printing time development of reaction fluxes to XMGrace!\n");


  if ( om->m == NULL ) {
    fprintf(stderr, "Error: No reaction model availabe\n");
    return 1;
  }
  else m = om->m;

  if ( openXMGrace(data) > 0 ) {
    fprintf(stderr,  "Error: Couldn't open XMGrace\n");
    return 1;
  }
  
  GracePrintf("yaxis label \"%s\"", "flux [substance/time]");
  if ( Model_isSetName(m) )
    GracePrintf("subtitle \"%s, %s\"", Model_getName(m),
		"reaction flux time courses");
  else if  ( Model_isSetId(m) )
    GracePrintf("subtitle \"%s, %s\"", Model_getId(m),
		"reaction flux time courses");
  else 
    GracePrintf("subtitle \"model has no name, %s/id\"",
		"reaction flux time courses");


  /* print legend */  
  for ( i=0; i<Model_getNumReactions(m); i++ ) {
    r = Model_getReaction(m, i);
    if ( Reaction_isSetName(r) )
      GracePrintf("g0.s%d legend  \"%s: %s \"\n", i+1,
		  Reaction_getId(r), Reaction_getName(r));
    else
      GracePrintf("g0.s%d legend  \"%s \"\n", i+1, Reaction_getId(r));      
  }  
  GracePrintf("legend 1.155, 0.85");
  GracePrintf("legend font 8");
  GracePrintf("legend char size 0.6");

  if(!(kls = (ASTNode_t **)calloc(Model_getNumReactions(m),
				  sizeof(ASTNode_t *)))) 
    fprintf(stderr, "failed!\n");
  
  for ( i=0; i<Model_getNumReactions(m); i++ ) {
    r = Model_getReaction(m, i);
    kl = Reaction_getKineticLaw(r);
    kls[i] = copyAST(KineticLaw_getMath(kl));
    AST_replaceNameByParameters(kls[i], KineticLaw_getListOfParameters(kl));
    AST_replaceConstants(m, kls[i]);
  }
  
  /* evaluate flux for each time point and print to XMGrace */
  
  for ( i=0; i<=results->nout; i++ ) {  
    n = 1;
    /* set time and variable values to values at time[k] */
    data->currenttime = results->time[i];
    for ( j=0; j<data->model->neq; j++ )
      data->value[j] = results->value[j][i];

    /* evaluate kinetic law expressions */
    for ( j=0; j<Model_getNumReactions(m); j++ ) {
      result = evaluateAST(kls[j], data);
      if ( result > maxY ) {
	maxY = result;
	GracePrintf("world ymax %g", 1.25*maxY);
      }
      if ( result < minY ) {
	minY = result;
	GracePrintf("world ymin %g", 1.25*minY);
      }
      GracePrintf("g0.s%d point %g, %g",
		  n, results->time[i], result);
      n++;
    }
  }

  GracePrintf("yaxis tick major %g", 1.25*(fabs(maxY)+fabs(minY))/10);
  GracePrintf("redraw");
  closeXMGrace(data, "flux");

  /* free temporary ASTNodes */
  for ( i=0; i<Model_getNumReactions(m); i++ ) 
    ASTNode_free(kls[i]);
  free(kls);

  return 0;
  
}
Ejemplo n.º 19
0
static int
drawModelTxt(Model_t *m, char *file) {

  Species_t *s;
  Reaction_t *re;
  const ASTNode_t *math;
  SpeciesReference_t *sref;
  ModifierSpeciesReference_t *mref;
  int i,j;
  int reversible;
  char filename[WORDSIZE];
  FILE *f;
  
  sprintf(filename, "%s.dot", file);
  f = fopen(filename, "w");

  fprintf(f ,"digraph reactionnetwork {\n");
  fprintf(f ,"label=\"%s\";\n",
	  Model_isSetName(m) ?
	  Model_getName(m) : (Model_isSetId(m) ? Model_getId(m) : "noId") );
  fprintf(f ,"overlap=scale;\n");
 
  for ( i=0; i<Model_getNumReactions(m); i++ ) {
    
    re = Model_getReaction(m,i);
    reversible = Reaction_getReversible(re);
    
    for ( j=0; j<Reaction_getNumModifiers(re); j++ ) {
      mref = Reaction_getModifier(re,j);
      fprintf(f ,"%s->%s [style=dashed arrowhead=odot];\n",
	      ModifierSpeciesReference_getSpecies(mref), Reaction_getId(re));
    }
    for ( j=0; j<Reaction_getNumReactants(re); j++ ) {
      sref = Reaction_getReactant(re,j);
      fprintf(f ,"%s->%s [label=\"",
	      SpeciesReference_getSpecies(sref), Reaction_getId(re));
      
      if ( (SpeciesReference_isSetStoichiometryMath(sref)) ) {
	math = SpeciesReference_getStoichiometryMath(sref);
	if ( (strcmp(SBML_formulaToString(math),"1") !=
	      0) ) {
	  fprintf(f ,"%s", SBML_formulaToString(math));
	}	
      }
      else {
	if ( SpeciesReference_getStoichiometry(sref) != 1) {
	  fprintf(f ,"%g",SpeciesReference_getStoichiometry(sref));
	}
      }
      if ( reversible == 1 ) {
	fprintf(f ,"\" arrowtail=onormal];\n");
      }
      else {
	fprintf(f ,"\" ];\n");
      }
    }
    for ( j=0; j<Reaction_getNumProducts(re); j++ ) {
      sref = Reaction_getProduct(re,j);
      fprintf(f ,"%s->%s [label=\"",
	      Reaction_getId(re), SpeciesReference_getSpecies(sref));
      if ( (SpeciesReference_isSetStoichiometryMath(sref)) ) {
	math = SpeciesReference_getStoichiometryMath(sref);
	if ( (strcmp(SBML_formulaToString(math),"1") !=
	      0) ) {
	  fprintf(f ,"%s ", SBML_formulaToString(math));
	}
      }
      else {
	if ( SpeciesReference_getStoichiometry(sref) != 1) {
	  fprintf(f ,"%g ",SpeciesReference_getStoichiometry(sref));
	}
      }
      if ( reversible == 1 ) {
	fprintf(f ,"\" arrowtail=onormal];\n");
      }
      else {
	fprintf(f ,"\" ];\n");
      }    

    }
    
  }
  for ( i=0; i<Model_getNumReactions(m); i++ ) {
    re = Model_getReaction(m,i);
    fprintf(f ,"%s [label=\"%s\" shape=box];\n",
	    Reaction_getId(re),
	    Reaction_isSetName(re) ?
	    Reaction_getName(re) : Reaction_getId(re));
  }

  for ( i=0; i<Model_getNumSpecies(m); i++) {
    s = Model_getSpecies(m, i);
    fprintf(f ,"%s [label=\"%s\"];",
	    Species_getId(s),
	    Species_isSetName(s) ? Species_getName(s) : Species_getId(s));
  }  
  fprintf(f ,"}\n");
  return 1;
}
Ejemplo n.º 20
0
SBML_ODESOLVER_API int drawModel(Model_t *m, char* file, char *format) {
  
#if !USE_GRAPHVIZ

  SolverError_error(
		    WARNING_ERROR_TYPE,
		    SOLVER_ERROR_NO_GRAPHVIZ,
		    "odeSolver has been compiled without GRAPHIZ functionality. ",
		    "Graphs are printed to stdout in the graphviz' .dot format.");
  drawModelTxt(m, file);
  
#else

  GVC_t *gvc;
  Agraph_t *g;
  Agnode_t *r;
  Agnode_t *s;  
  Agedge_t *e;
  Agsym_t *a;
  Species_t *sp;
  Reaction_t *re;
  const ASTNode_t *math;  
  SpeciesReference_t *sref;
  ModifierSpeciesReference_t *mref;
  char *output[4];
  char *command = "dot";
  char *formatopt;
  char *outfile;
  int i,j;
  int reversible;
  char name[WORDSIZE];
  char label[WORDSIZE];

  /* setting name of outfile */
  ASSIGN_NEW_MEMORY_BLOCK(outfile, strlen(file)+ strlen(format)+7, char, 0);
  sprintf(outfile, "-o%s_rn.%s", file, format);

  /* setting output format */
  ASSIGN_NEW_MEMORY_BLOCK(formatopt, strlen(format)+3, char, 0);
  sprintf(formatopt, "-T%s", format);

  /* construct command-line */
  output[0] = command;
  output[1] = formatopt;
  output[2] = outfile;
  output[3] = NULL;

  /* set up renderer context */
  gvc = (GVC_t *) gvContext();
#if GRAPHVIZ_MAJOR_VERSION == 2 && GRAPHVIZ_MINOR_VERSION < 4
  dotneato_initialize(gvc, 3, output);
#elif GRAPHVIZ_MAJOR_VERSION == 2 && GRAPHVIZ_MINOR_VERSION == 4
  parse_args(gvc, 3, output);
#elif GRAPHVIZ_MAJOR_VERSION == 2 && GRAPHVIZ_MINOR_VERSION >= 6 || GRAPHVIZ_MAJOR_VERSION >= 3
  gvParseArgs(gvc, 3, output);  
#endif  

  g = agopen("G", AGDIGRAPH);
  
  /* avoid overlapping nodes, for graph embedding by neato */ 
  a = agraphattr(g, "overlap", "");
  agxset(g, a->index, "scale");

  for ( i=0; i<Model_getNumReactions(m); i++ ) {

    re = Model_getReaction(m,i);
    reversible = Reaction_getReversible(re);
    sprintf(name, "%s", Reaction_getId(re));
    r = agnode(g,name);
    a = agnodeattr(g, "shape", "ellipse");    
    agxset(r, a->index, "box");
    
    sprintf(label, "%s", Reaction_isSetName(re) ?
	    Reaction_getName(re) : Reaction_getId(re));
    agset(r, "label", label);
    
    sprintf(label, "%s.htm", Reaction_getId(re));
    a = agnodeattr(g, "URL", "");
    agxset(r, a->index, label);
    
    for ( j=0; j<Reaction_getNumModifiers(re); j++ ) {

      mref = Reaction_getModifier(re,j);
      sp = Model_getSpeciesById(m, ModifierSpeciesReference_getSpecies(mref));
      
      sprintf(name,"%s", Species_getId(sp));
      s = agnode(g,name);
      sprintf(label, "%s", Species_isSetName(sp) ? 
	      Species_getName(sp) : Species_getId(sp));
      agset(s, "label", label);

      if ( Species_getBoundaryCondition(sp) ) {
	a = agnodeattr(g, "color", "");
	agxset(s, a->index, "blue");
      }
      if ( Species_getConstant(sp) ) {
	a = agnodeattr(g, "color", "");
	agxset(s, a->index, "green4");
      }

      sprintf(label, "%s.htm", Species_getId(sp));
      a = agnodeattr(g, "URL", "");
      agxset(s, a->index, label);
	
      e = agedge(g,s,r);
      a = agedgeattr(g, "style", "");
      agxset(e, a->index, "dashed");
      a = agedgeattr(g, "arrowhead", "");
      agxset(e, a->index, "odot");
    }

    for ( j=0; j<Reaction_getNumReactants(re); j++ ) {

      sref = Reaction_getReactant(re,j);
      sp = Model_getSpeciesById(m, SpeciesReference_getSpecies(sref));
      
      sprintf(name,"%s", Species_getId(sp));
      s = agnode(g, name);
      sprintf(label, "%s", Species_isSetName(sp) ? 
	      Species_getName(sp) : Species_getId(sp));
      agset(s, "label", label);

      if ( Species_getBoundaryCondition(sp) ) {
	a = agnodeattr(g, "color", "");
	agxset(s, a->index, "blue");
      }
      if ( Species_getConstant(sp) ) {
	a = agnodeattr(g, "color", "");
	agxset(s, a->index, "green4");
      }

      sprintf(label, "%s.htm", Species_getId(sp));
      a = agnodeattr(g, "URL", "");
      agxset(s, a->index, label);
      
      e = agedge(g,s,r);
      a = agedgeattr(g, "label", "");
      
      if ( (SpeciesReference_isSetStoichiometryMath(sref)) ) {
	math = SpeciesReference_getStoichiometryMath(sref);
	if ( (strcmp(SBML_formulaToString(math),"1") !=
	      0) ) {
	  agxset (e, a->index, SBML_formulaToString(math));
	}
      }
      else {
	if ( SpeciesReference_getStoichiometry(sref) != 1 ) {
	  sprintf(name, "%g", SpeciesReference_getStoichiometry(sref));
	  agxset (e, a->index, name);
	}
      }
      if ( reversible == 1 ) {
	a = agedgeattr(g, "arrowtail", "");
	agxset(e, a->index, "onormal");
      }      
    }
    
    for ( j=0; j<Reaction_getNumProducts(re); j++ ) {
      sref = Reaction_getProduct(re,j);
      sp = Model_getSpeciesById(m, SpeciesReference_getSpecies(sref));
      sprintf(name,"%s", Species_getId(sp));
      s = agnode(g,name);
      sprintf(label, "%s", Species_isSetName(sp) ? 
	      Species_getName(sp) : Species_getId(sp));
      agset(s, "label", label);

      if ( Species_getBoundaryCondition(sp) ) {
	a = agnodeattr(g, "color", "");
	agxset(s, a->index, "blue");
      }
      if ( Species_getConstant(sp) ) {
	a = agnodeattr(g, "color", "");
	agxset(s, a->index, "green4");
      }

      sprintf(label, "%s.htm", Species_getId(sp));
      a = agnodeattr(g, "URL", "");
      agxset(s, a->index, label);
            
      e = agedge(g,r,s);
      a = agedgeattr(g, "label", "");
      if ( SpeciesReference_isSetStoichiometryMath(sref) ) {
	math = SpeciesReference_getStoichiometryMath(sref);
	if ( (strcmp(SBML_formulaToString(math),"1") !=
	      0) ) {
	  agxset (e, a->index, SBML_formulaToString(math));
	}
      }
      else {
	if ( SpeciesReference_getStoichiometry(sref) != 1 ) {
	  sprintf(name, "%g",SpeciesReference_getStoichiometry(sref));
	  agxset (e, a->index,name);
	}
      }
      if ( reversible == 1 ) {
	a = agedgeattr(g, "arrowtail", "");
	agxset(e, a->index, "onormal");
      }      
    }   
  }

  /* Compute a layout */
#if GRAPHVIZ_MAJOR_VERSION == 2 && GRAPHVIZ_MINOR_VERSION <= 2
  gvBindContext(gvc, g);
  dot_layout(g);
#elif GRAPHVIZ_MAJOR_VERSION == 2 && GRAPHVIZ_MINOR_VERSION == 4
  gvlayout_layout(gvc, g);
#elif GRAPHVIZ_MAJOR_VERSION == 2 && GRAPHVIZ_MINOR_VERSION >= 6 || GRAPHVIZ_MAJOR_VERSION >= 3
  gvLayoutJobs(gvc, g);
#endif

  /* Write the graph according to -T and -o options */
#if GRAPHVIZ_MAJOR_VERSION == 2 && GRAPHVIZ_MINOR_VERSION <= 2
  dotneato_write(gvc);
#elif GRAPHVIZ_MAJOR_VERSION == 2 && GRAPHVIZ_MINOR_VERSION == 4
  emit_jobs(gvc, g);
#elif GRAPHVIZ_MAJOR_VERSION == 2 && GRAPHVIZ_MINOR_VERSION >= 6 || GRAPHVIZ_MAJOR_VERSION >= 3
  gvRenderJobs(gvc, g);
#endif
  
  /* Clean out layout data */
#if GRAPHVIZ_MAJOR_VERSION == 2 && GRAPHVIZ_MINOR_VERSION <= 2
  dot_cleanup(g);
#elif GRAPHVIZ_MAJOR_VERSION == 2 && GRAPHVIZ_MINOR_VERSION == 4
  gvlayout_cleanup(gvc, g);
#elif GRAPHVIZ_MAJOR_VERSION == 2 && GRAPHVIZ_MINOR_VERSION >= 6 || GRAPHVIZ_MAJOR_VERSION >= 3
  gvFreeLayout(gvc, g);
#endif
  
  /* Free graph structures */
#if GRAPHVIZ_MAJOR_VERSION == 2 && GRAPHVIZ_MINOR_VERSION <= 2
  dot_cleanup(g);
#else
  agclose(g);
#endif

  /* Clean up output file and errors */
#if GRAPHVIZ_MAJOR_VERSION == 2 && GRAPHVIZ_MINOR_VERSION <= 2
  gvFREEcontext(gvc);
  dotneato_eof(gvc);
#elif GRAPHVIZ_MAJOR_VERSION == 2 && GRAPHVIZ_MINOR_VERSION == 4
  dotneato_terminate(gvc);
#elif GRAPHVIZ_MAJOR_VERSION == 2 && GRAPHVIZ_MINOR_VERSION >= 6 || GRAPHVIZ_MAJOR_VERSION >= 3
  gvFreeContext(gvc); 
#endif  

  xfree(formatopt);  
  xfree(outfile);
  
#endif
  
  return 1;

}
Ejemplo n.º 21
0
int main(int argc, char** argv)
{
    myspecies_t* species;	//pinakas ximikon stoixeion
    reaction_t *reaction;	//20 ximikes antidraseis
    int i,j,k,num_species, num_reactions;
    double V;
    FILE *pf1, *pf2, *pf3, *pf4, *pf5, *pf6, *fsize;

    SBMLDocument_t *d;
    Model_t        *m;
    ListOf_t    *lo;
    Species_t   *sp;
    Reaction_t  *re;
    Parameter_t *p;
    KineticLaw_t *kin;
    SpeciesReference_t *sr;
    Compartment_t *c;

	//an den exei 2 argument
	if(argc != 2)
    {
        printf("Ektelesi: %s <SBML xml>\n", argv[0]);
        exit(-1);
    }

    //arxeia results
    if((pf1 = fopen("RT_reactant.txt", "w")) == NULL)
    {
        printf("Error create file %s\n","RT_reactant.txt");
        exit(-1);
    }
    
    if((pf2 = fopen("RT_product.txt", "w")) == NULL)
    {
        printf("Error create file %s\n","RT_product.txt");
        fclose(pf1);
        exit(-1);
    }
    
    if((pf3 = fopen("VT_reactant.txt", "w")) == NULL)
    {
        printf("Error create file %s\n","VT_reactant.txt");
        fclose(pf1);
        fclose(pf2);
        exit(-1);
    }
    
    if((pf4 = fopen("VT_product.txt", "w")) == NULL)
    {
        printf("Error create file %s\n","VT_product.txt");
        fclose(pf1);
        fclose(pf2);
        fclose(pf3);
        exit(-1);
    }
    
    if((pf5 = fopen("ST.txt", "w")) == NULL)
    {
        printf("Error create file %s\n","ST.txt");
        fclose(pf1);
        fclose(pf2);
        fclose(pf3);
        fclose(pf4);
        exit(-1);
    }
    
    if((pf6 = fopen("k_parameter.txt", "w")) == NULL)
    {
        printf("Error create file %s\n","k_parameter.txt");
        fclose(pf1);
        fclose(pf2);
        fclose(pf3);
        fclose(pf4);
        fclose(pf5);
        exit(-1);
    }

    fsize = fopen("fsize.txt", "w");

    //anoigo to SBML arxeio
    d = readSBML(argv[1]);
    //d=readSBML("C:/home/orsalia/BIOMD0000000001");
    m = SBMLDocument_getModel(d);
    num_species = Model_getNumSpecies(m);
    num_reactions = Model_getNumReactions(m);

    fprintf(fsize,"%d\n",num_species);
    fprintf(fsize,"%d\n",num_reactions);
    
    //Pairnoume ton ogko
    c = Model_getCompartment(m,0);
    V = Compartment_getVolume(c);


    //Desmeysi pinakon domon gia stoixeia kai reaction
    species =  (myspecies_t*) malloc(num_species*sizeof(myspecies_t));
    reaction = (reaction_t*) malloc(num_reactions*sizeof(reaction_t));

    //gemizo ton pinaka me tis arxikes sigkentroseis ton stoixeion
    for(i=0;i<num_species;i++)
    {
        sp = Model_getSpecies(m,i);
        species[i].conc = Species_getInitialConcentration(sp)?Species_getInitialConcentration(sp):Species_getInitialAmount(sp);
        species[i].name = malloc(50*sizeof(char));
        strcpy(species[i].name,Species_getId(sp));
        strcpy(species[i].name2,Species_getName(sp));
    }

    ///gemizo ton pinaka domon ton reaction
    for(i=0;i<num_reactions;i++)
    {
        re = Model_getReaction(m,i);
        kin = Reaction_getKineticLaw(re);
        p = KineticLaw_getParameter(kin,0);

        reaction[i].react_num = Reaction_getNumReactants(re);
        reaction[i].product_num = Reaction_getNumProducts(re);
        reaction[i].react = (x_vector_t*) malloc(reaction[i].react_num*sizeof(x_vector_t));
        reaction[i].product = (x_vector_t*) malloc(reaction[i].product_num*sizeof(x_vector_t));

		for(j=0;j<reaction[i].react_num;j++)
        {
            sr = Reaction_getReactant(re,j);

            for(k=0;k<num_species;k++)
            {
                //an vrei to stoixeio ston megalo pinaka krata ti thesi tou
                if (strcmp(SpeciesReference_getSpecies(sr),species[k].name) == 0)
                {
                    reaction[i].react[j].x = k;		//ithesi ston pinaka species
                    reaction[i].react[j].v = (-1) * SpeciesReference_getStoichiometry(sr);
                    break;
                }
            }
        }
        
        for(j=0;j<reaction[i].product_num;j++)
        {
            sr = Reaction_getProduct(re,j);

            for(k=0;k<num_species;k++)
            {
                //an vrei to stoixeio ston megalo pinaka krata ti thesi tou
                if (strcmp(SpeciesReference_getSpecies(sr),species[k].name) == 0)
                {
                    reaction[i].product[j].x = k;	//ithesi ston pinaka species
                    reaction[i].product[j].v = SpeciesReference_getStoichiometry(sr);
                    break;
                }
            }
        }
        
        reaction[i].k = Parameter_getValue(p);

        //vlepo tin eidos antidraseis einai kai vazo to c tis kathe antidrasis
        if(reaction[i].react_num == 3)
        {
        	reaction[i].type = 7;
            reaction[i].c = Parameter_getValue(p)/(V*V);	//mallon
        }
        else if(reaction[i].react_num == 2)
        {	
          	sr = Reaction_getReactant(re,0);
          	
          	if (SpeciesReference_getStoichiometry(sr) == 2 )
        	{
        		reaction[i].type = 5;
            	reaction[i].c = 2*Parameter_getValue(p)/(V*V);	//oute kan
        	}
        	else
        	{
        		sr = Reaction_getReactant(re,1);
        	
        		if (SpeciesReference_getStoichiometry(sr) == 2 )
		    	{
		    		reaction[i].type = 6;
		        	reaction[i].c = 2*Parameter_getValue(p)/(V*V);	//oute kan
		    	}
		    	else
		    	{
		    		reaction[i].type = 2;
		        	reaction[i].c = Parameter_getValue(p)/V;	
		    	}
		    }
            
        }
        else //if(reaction[i].react_num == 1)
        {	
        	sr = Reaction_getReactant(re,0);
        	
            if (SpeciesReference_getStoichiometry(sr) == 2 )		//an einai bimolecular me to idio stoixeio
            {
                reaction[i].type = 3;
                reaction[i].c = 2*Parameter_getValue(p)/V;
            }
            else if(SpeciesReference_getStoichiometry(sr) == 3 )
            {
            	reaction[i].type = 4;
                reaction[i].c = 3*Parameter_getValue(p)/(V*V);	//mallon
            }
            else 
            {
                reaction[i].type = 1;
            	reaction[i].c = Parameter_getValue(p);
            }
        }
    }

	for(i=0;i<num_species;i++)
	{
		//fprintf(pf5,"%d\t%s\n",(int)species[i].conc,species[i].name2);
		fprintf(pf5,"%d\t\n",(int)species[i].conc);
	}

	for(i=0;i<num_reactions;i++)
	{
		for(k=0;k<reaction[i].react_num;k++)
		{
			fprintf(pf1,"%d\t",reaction[i].react[k].x+1);
			fprintf(pf3,"%d\t",reaction[i].react[k].v);
		}
		
		for(k=0;k<reaction[i].product_num;k++)
		{
			fprintf(pf2,"%d\t",reaction[i].product[k].x+1);
			fprintf(pf4,"%d\t",reaction[i].product[k].v);
		}

		fprintf(pf1,"\n");
		fprintf(pf3,"\n");
		fprintf(pf2,"\n");
		fprintf(pf4,"\n");
		
		fprintf(pf6,"%f\n",reaction[i].k);
		
		
		
	}
	
	
    fclose(pf1);
    fclose(pf2);
    fclose(pf3);
    fclose(pf4);
    fclose(pf5);
    fclose(pf6);
    fclose(fsize);

}