void PatchParser::parseMatrix(parser::DefTokeniser& tok, IPatch& patch) const { tok.assertNextToken("("); // For each row for (std::size_t c = 0; c < patch.getWidth(); c++) { tok.assertNextToken("("); // For each column for (std::size_t r=0; r < patch.getHeight(); r++) { tok.assertNextToken("("); // Parse vertex coordinates patch.ctrlAt(r, c).vertex[0] = strToDouble(tok.nextToken()); patch.ctrlAt(r, c).vertex[1] = strToDouble(tok.nextToken()); patch.ctrlAt(r, c).vertex[2] = strToDouble(tok.nextToken()); // Parse texture coordinates patch.ctrlAt(r, c).texcoord[0] = strToDouble(tok.nextToken()); patch.ctrlAt(r, c).texcoord[1] = strToDouble(tok.nextToken()); tok.assertNextToken(")"); } tok.assertNextToken(")"); } tok.assertNextToken(")"); }
boost::shared_ptr<HazardRateStructure> qlHazardRateFactory::hazardRateTS(TiXmlNode* node) { boost::shared_ptr<HazardRateStructure> hazardCurve; Date referenceDate = Settings::instance().evaluationDate(); std::vector<boost::shared_ptr<DefaultProbabilityHelper> > instruments; qlCalendarFactory calFactory = qlCalendarFactory(); qlTimeUnitFactory timeUnitFactory = qlTimeUnitFactory(); qlYieldTermStructureFactory tsFactory = qlYieldTermStructureFactory(); Calendar calendar = calFactory.calendar(node->FirstChildElement("calendar")->GetText()); Real recoveryRate = strToDouble(node->FirstChildElement("recoveryRate")->GetText()); TiXmlElement* rateNode = node->FirstChildElement("rateData"); std::vector<Period> periods; std::vector<Real> spreadRates; if(rateNode) { for(rateNode; rateNode; rateNode = rateNode->NextSiblingElement("rateData")) { periods.push_back(timeUnitFactory.timeUnit(rateNode)); spreadRates.push_back(strToDouble(rateNode->FirstChildElement("data")->GetText())); } } for (Size i=0; i<periods.size(); i++) { instruments.push_back(boost::shared_ptr<DefaultProbabilityHelper>( new SpreadCdsHelper( Handle<Quote>(boost::shared_ptr<Quote>( new SimpleQuote(spreadRates[i]))), periods[i], 0, calendar, Quarterly, Following, DateGeneration::TwentiethIMM, Actual365Fixed(), recoveryRate, tsCurve_))); } // Bootstrap hazard rates std::string curveType = "HazardRate"; std::string interpolationType = "BackwardFlat"; boost::shared_ptr<PiecewiseDefaultCurve<HazardRate, BackwardFlat> > hazardRateStructure( new PiecewiseDefaultCurve<HazardRate, BackwardFlat>( referenceDate, instruments, Actual365Fixed())); return hazardCurve; }
/** * Convert parameter to double (64 bit) * @param context * @param parameter * @param value result * @return TRUE if succesful */ scpi_bool_t SCPI_ParamToDouble(scpi_t * context, scpi_parameter_t * parameter, double * value) { scpi_bool_t result; uint64_t valint; if (!value) { SCPI_ErrorPush(context, SCPI_ERROR_SYSTEM_ERROR); return FALSE; } switch (parameter->type) { case SCPI_TOKEN_HEXNUM: case SCPI_TOKEN_OCTNUM: case SCPI_TOKEN_BINNUM: result = SCPI_ParamToUInt64(context, parameter, &valint); *value = valint; break; case SCPI_TOKEN_DECIMAL_NUMERIC_PROGRAM_DATA: case SCPI_TOKEN_DECIMAL_NUMERIC_PROGRAM_DATA_WITH_SUFFIX: result = strToDouble(parameter->ptr, value) > 0 ? TRUE : FALSE; break; default: result = FALSE; } return result; }
// Get Widget data as an double (entry, textview) bool GtkAReViWidget::getWidgetDouble(const StlString &propName,double &propValueOut) { StlString strValue; if (!getWidgetString(propName,strValue)) return false; return strToDouble(propValueOut,strValue); }
ASTNode* CEvaluationNodeNumber::toAST(const CDataModel* /* pDataModel */) const { SubType subType = (SubType)this->subType(); ASTNode* node = new ASTNode(); double num1; double num2; const char * end; const char * str = mData.c_str(); switch (subType) { case SubType::DOUBLE: node->setType(AST_REAL); node->setValue(*mpValue); break; case SubType::INTEGER: node->setType(AST_INTEGER); node->setValue((long)*mpValue); break; case SubType::ENOTATION: node->setType(AST_REAL_E); num2 = floor(log10(*mpValue)); num1 = pow(10.0, log10(*mpValue) - num2); node->setValue(num1, (long)num2); break; case SubType::RATIONALE: node->setType(AST_RATIONAL); str++; // Skip the '(' num1 = strToDouble(str, &end); end++; // Skip the '/' num2 = strToDouble(end, NULL); node->setValue((long)num1, (long)num2); break; case SubType::INVALID: break; } return node; }
double Parser::evaluateToNumber(Expr* e) { switch (e->tag()) { case TAG_literalUndefined: return MathUtils::kNaN; case TAG_literalNull: return 0.0; case TAG_literalBoolean: return ((LiteralBoolean*)e)->value ? 1.0 : 0.0; case TAG_literalDouble: return ((LiteralDouble*)e)->value; case TAG_literalInt: return (double)(((LiteralInt*)e)->value); case TAG_literalUInt: return (double)(((LiteralUInt*)e)->value); case TAG_literalString: return strToDouble(((LiteralString*)e)->value); default: failNonConstant(e); return 0; } }
CEvaluationNodeNumber::CEvaluationNodeNumber(const SubType & subType, const Data & data): CEvaluationNode(MainType::NUMBER, subType, data) { mPrecedence = PRECEDENCE_NUMBER; mValueType = ValueType::Number; const char * end; const char * str = mData.c_str(); switch (subType) { case SubType::DOUBLE: case SubType::INTEGER: case SubType::ENOTATION: { //mValue = strToDouble(str, NULL); std::istringstream in; in.imbue(std::locale::classic()); in.str(str); in >> mValue; } break; case SubType::RATIONALE: str++; // Skip the '(' mValue = strToDouble(str, &end); end++; // Skip the '/' mValue /= strToDouble(end, NULL); break; case SubType::INVALID: fatalError(); break; } }
CDatum::operator double () const // double cast operator { switch (m_dwData & AEON_TYPE_MASK) { case AEON_TYPE_STRING: return (m_dwData == 0 ? 0.0 : strToDouble(raw_GetString())); case AEON_TYPE_NUMBER: switch (m_dwData & AEON_NUMBER_TYPE_MASK) { case AEON_NUMBER_CONSTANT: { switch (m_dwData) { case constTrue: return 1.0; default: ASSERT(false); return 0.0; } } case AEON_NUMBER_28BIT: return (double)((int)(m_dwData & AEON_NUMBER_MASK) >> 4); case AEON_NUMBER_32BIT: return (double)(int)g_IntAlloc.Get(GetNumberIndex()); case AEON_NUMBER_DOUBLE: return g_DoubleAlloc.Get(GetNumberIndex()); default: ASSERT(false); return 0.0; } case AEON_TYPE_COMPLEX: return 0.0; default: ASSERT(false); return 0.0; } }
bool CDatum::CreateFromStringValue (const CString &sValue, CDatum *retdDatum) // CreateFromStringValue // // Creates either a string or a number depending on the value. { CDatum dDatum; switch (GetStringValueType(sValue)) { case typeNil: break; case typeInteger32: dDatum = CDatum(strToInt(sValue, 0)); break; case typeIntegerIP: { CIPInteger Value; Value.InitFromString(sValue); CDatum::CreateIPIntegerFromHandoff(Value, &dDatum); break; } case typeDouble: dDatum = CDatum(strToDouble(sValue)); break; case typeString: dDatum = CDatum(sValue); break; default: return false; } if (retdDatum) *retdDatum = dDatum; return true; }
/** * Parse double parameter * @param context * @param value * @param mandatory * @return */ scpi_bool_t SCPI_ParamDouble(scpi_t * context, double * value, scpi_bool_t mandatory) { const char * param; size_t param_len; size_t num_len; if (!value) { return FALSE; } if (!SCPI_ParamString(context, ¶m, ¶m_len, mandatory)) { return FALSE; } num_len = strToDouble(param, value); if (num_len != param_len) { SCPI_ErrorPush(context, SCPI_ERROR_SUFFIX_NOT_ALLOWED); return FALSE; } return TRUE; }
/** * Parse parameter as number, number with unit or special value (min, max, default, ...) * @param context * @param value return value * @param mandatory if the parameter is mandatory * @return */ scpi_bool_t SCPIParser::SCPI_ParamNumber(scpi_number_t * value, scpi_bool_t mandatory) { scpi_bool_t result; const char * param; size_t len; size_t numlen; /* read parameter and shift to the next one */ result = SCPI_ParamString(¶m, &len, mandatory); /* value not initializes */ if (!value) { return FALSE; } value->type = SCPI_NUM_DEF; /* if parameter was not found, return TRUE or FALSE according * to fact that parameter was mandatory or not */ if (!result) { return mandatory ? FALSE : TRUE; } /* convert string to special number type */ if (translateSpecialNumber(context.special_numbers, param, len, value)) { /* found special type */ return TRUE; } /* convert text from double - no special type */ numlen = strToDouble(param, &value->value); /* transform units of value */ if (numlen <= len) { return transformNumber(param + numlen, len - numlen, value); } return FALSE; }
/** * Parses the postfix expression for the given code line in the parameter. * While doing this, prints the intermediate states of the number stack * using printNumberStackContent function. * @param codeLine The code line which will be calculated. * @param destination The name of destination variable. */ void parsePostfixExpression(struct code_line *codeLine, char destination) { int i = 0; while (i < codeLine->lineContentPostfix.postfixLength) { if (isspace(codeLine->lineContentPostfix.postfixExpression[i])) { i++; } else { if (isNumberOrVariable( codeLine->lineContentPostfix.postfixExpression[i])) { if (isalpha( (codeLine->lineContentPostfix.postfixExpression[i]))) { // if the character is a variable pushNumber( variableValues[tolower( codeLine->lineContentPostfix.postfixExpression[i++]) - 'a']); } else { // if the character is a number char numberString[NUMBER_LENGTH]; size_t j = 0; while (!isspace( codeLine->lineContentPostfix.postfixExpression[i])) { numberString[j++] = codeLine->lineContentPostfix.postfixExpression[i++]; } numberString[j] = '\0'; double numberValue = strToDouble(numberString, j); pushNumber(numberValue); } } else { // if the character is an operation sign character double number1, number2; number2 = popNumber(); number1 = popNumber(); switch (codeLine->lineContentPostfix.postfixExpression[i++]) { case '+': pushNumber(number1 + number2); break; case '-': pushNumber(number1 - number2); break; case '*': pushNumber(number1 * number2); break; case '/': if (number2 == 0) { fprintf(stderr, "ERROR: You can not divide by zero."); exit(EXIT_FAILURE); } pushNumber(number1 / number2); break; default: fprintf(stderr, "ERROR: Unexpected character in the postfix expression."); exit(EXIT_FAILURE); break; } } printf("Stack: "); printNumberStackContent(); printf("\n"); } } double finalValue = popNumber(); variableValues[tolower(destination) - 'a'] = finalValue; codeLine->finalValue = finalValue; }
std::string stringCalc(std::string expression) { std::string subExpression, subExpression2, result, result2; int startPos, endPos; double val1, val2; if (expression.compare(varNotFound) == 0) return ""; do // Searches for (), calculates the expression inside, then { // replaces the () with the result. Will start from the startPos = -1; // innermost (). Repeats until there are no more (). endPos = -1; for(register int i = 0 ; unsigned(i) < expression.length() ; i++) { if (expression[i] == '(') { startPos = i; for (register int j = i; unsigned(j) < expression.length() ; j++) { if (expression[j] == ')') { endPos = j; break; } } } } if (startPos != -1) // () found { subExpression = expression.substr(startPos+1, endPos-startPos-1); result = stringCalc(subExpression); // Calls same function with expression inside () expression.erase(startPos, endPos-startPos+1); expression.insert(startPos, result); } } while(startPos != -1); // At this point the expression will have no ( or ) and only numbers, +, -, *, / do // Searches for + and - then calculates the rest of the expression { // Will calculate last the + or - that is most to the right startPos = -1; for(register int i = 0 ; unsigned(i) < expression.length() ; i++) { if ((expression[i] == '+')||(expression[i] == '-')) { startPos = i; } } // Expression[startPos] is the last + or - found in the entire string if (startPos != -1) { if(expression[startPos]=='-') // Special case for negative numbers { if(startPos > 0) { if(!isdigit(expression[startPos-1])) { endPos = startPos; for(register int i = 0 ; unsigned(i) < startPos ; i++) { if ((expression[i] == '+')||(expression[i] == '-')) { startPos = i; } } if (startPos == endPos) { break; } } } else { break; } } // Separates the 2 expressions before and after the + or - subExpression = expression.substr(0, startPos); subExpression2 = expression.substr(startPos+1, expression.length()-startPos); result = stringCalc(subExpression); // Calls the same function for result2 = stringCalc(subExpression2); // each of the new expressions val1 = strToDouble(result); val2 = strToDouble(result2); if (expression[startPos] == '+') { expression = doubleToStr(val1 + val2); } else { expression = doubleToStr(val1 - val2); } } } while(startPos != -1); do // Searches for * and / then calculates the rest of the expression { // Same logic as the +- block startPos = -1; for(register int i = 0 ; unsigned(i) < expression.length() ; i++) { if ((expression[i] == '*')||(expression[i] == '/')) { startPos = i; } } if (startPos != -1) { subExpression = expression.substr(0, startPos); subExpression2 = expression.substr(startPos+1, expression.length()-startPos); result = stringCalc(subExpression); result2 = stringCalc(subExpression2); val1 = strToDouble(result); val2 = strToDouble(result2); if(expression[startPos] == '*') { expression = doubleToStr(val1 * val2); } else { expression = doubleToStr(val1 / val2); } } } while(startPos != -1); return expression; }
//hacky code for week 10 checkoffs SensorData CrashDetectionThread::parseData(char *buffer){ SensorData data; char *token = (char *)malloc(10*sizeof(char)); token = strtok(buffer, ","); for (int i=0; token != NULL; i++) { if (i == 0) { data.accelerometerX = strToDouble(token); } else if (i == 1) { data.accelerometerY = strToDouble(token); } else if (i == 2) { data.accelerometerZ = strToDouble(token); } else if (i == 3) { data.gyroX = strToDouble(token); } else if (i == 4) { data.gyroY = strToDouble(token); } else if (i == 5) { data.gyroZ = strToDouble(token); } else if (i == 6) { data.fix = atoi(token); } else if (i == 7) { data.satellites = atoi(token); } else if (i == 8) { data.hour = (time_t)atoi(token); } else if (i == 9) { data.minute = (time_t)atoi(token); } else if (i == 10) { data.second = (time_t)atoi(token); } else if (i == 11) { data.month = (time_t)atoi(token); } else if (i == 12) { data.day = (time_t)atoi(token); } else if (i == 13) { data.year = (time_t)atoi(token); } else if (i == 14) { data.lattitude = strToDouble(token); } else if (i == 15) { data.longitude = strToDouble(token); } else if (i == 16) { data.speed = atoi(token); } else if (i == 17) { //strcpy(data.command, token); } else if (i == 18) { //data.value = atoi(token); } token = strtok(NULL, ","); } return data; }
// virtual CXMLHandler * RenderCurveHandler::processStart(const XML_Char * pszName, const XML_Char ** papszAttrs) { CXMLHandler * pHandlerToCall = NULL; const char * Transform; const char * Stroke; const char * StrokeWidth; const char * StrokeDashArray; const char * StartHead; const char * EndHead; switch (mCurrentElement.first) { case RenderCurve: mpData->pRenderCurve = new CLRenderCurve(); Transform = mpParser->getAttributeValue("transform", papszAttrs, false); Stroke = mpParser->getAttributeValue("stroke", papszAttrs, false); StrokeWidth = mpParser->getAttributeValue("stroke-width", papszAttrs, false); StrokeDashArray = mpParser->getAttributeValue("stroke-dasharray", papszAttrs, false); StartHead = mpParser->getAttributeValue("startHead", papszAttrs, false); EndHead = mpParser->getAttributeValue("endHead", papszAttrs, false); if (Transform != NULL) { mpData->pRenderCurve->parseTransformation(Transform); } if (Stroke != NULL) { mpData->pRenderCurve->setStroke(Stroke); } if (StrokeWidth != NULL) { double width = strToDouble(StrokeWidth, NULL); mpData->pRenderCurve->setStrokeWidth(width); } if (StrokeDashArray != NULL) { mpData->pRenderCurve->parseDashArray(StrokeDashArray); } if (StartHead != NULL) { mpData->pRenderCurve->setStartHead(StartHead); } if (EndHead != NULL) { mpData->pRenderCurve->setEndHead(EndHead); } break; case ListOfElements: mpData->pListOfCurveElements = mpData->pRenderCurve->getListOfCurveElements(); pHandlerToCall = getHandler(mCurrentElement.second); break; default: CCopasiMessage(CCopasiMessage::EXCEPTION, MCXML + 2, mpParser->getCurrentLineNumber(), mpParser->getCurrentColumnNumber(), pszName); break; } return pHandlerToCall; }
int main(void) { int i = 0; float vx; float vy; DoubleInt dTemp; int count = 0; char temp[100]; char tempStr[24]; ssize_t ret = 0; Coords* c = NULL; ret = allocate(PAGE_SIZE, 0, (void**)(&c)); if (ret != 0) { return (-1); } do { printfstr(STDOUT, "Initial Velocity X: "); ret = readLine(STDIN, temp, 100); if (ret < 0) { return (-1); } dTemp.d = strToDouble(temp); } while (dTemp.u == NAN.u); vx = (float)dTemp.d; do { printfstr(STDOUT, "Initial Velocity Y: "); ret = readLine(STDIN, temp, 100); if (ret < 0) { return (-1); } dTemp.d = strToDouble(temp); } while (dTemp.u == NAN.u); vy = (float)dTemp.d; printfstr(STDOUT, "Initial Count: "); ret = readLine(STDIN, temp, 100); if (ret < 0) { return (-1); } count = strToUint32(temp); do { fillPage(vx, vy, c, &count, 10); ret = readLine(STDIN, temp, 100); if (ret < 0) { return (-1); } if (temp[0] == 'p') { for (i = 0; i < 510; i++) { tempStr[0] = 'x'; tempStr[1] = '='; tempStr[2] = '\0'; snprintfloat(tempStr+2, 24, c[i].x); printfstr(STDOUT, tempStr); printfstr(STDOUT, ", "); tempStr[0] = 'y'; tempStr[1] = '='; tempStr[2] = '\0'; snprintfloat(tempStr+2, 24, c[i].y); printfstr(STDOUT, tempStr); printfstr(STDOUT, "\n"); } } } while ( (temp[0] == 'c') || (temp[0] == 'p') ); }
int main(int argc, char *argv[]) { // Parse the commandline options // first argument is the SBML filename // second argument is the endtime // third argument is the step number // fourth argument is the filename where the results are to be written // fifth argument is the tmp directory (this is not needed) // the rest of the arguments are species names for the result try { // Create the root container. CCopasiRootContainer::init(0, NULL, false); } catch (copasi::autoexcept &e) {} catch (copasi::option_error &e) {} if (argc < 5) { std::cout << "Usage: semantic-test-suite SBMLFILENAME ENDTIME STEPNUMBER OUTFILENAME TMPDIR SPECIESID1 SPECIESID2 ..." << std::endl; exit(1); } char* pSBMLFilename = argv[1]; const char* pEndTime = argv[2]; const char* pStepNumber = argv[3]; char* pOutputFilename = argv[4]; //char* pTmpDirectory=argv[5]; char** pSBMLSpeciesIds = new char * [argc - 6]; unsigned int i, iMax = argc; CTrajectoryTask* pTrajectoryTask = NULL; std::string CWD = COptions::getPWD(); double endTime = strToDouble(pEndTime, &pEndTime); double stepNumber = strToDouble(pStepNumber, &pStepNumber); if (endTime == 0.0) { std::cerr << "Invalid endtime " << pEndTime << std::endl; exit(1); } if (stepNumber == 0.0) { std::cerr << "Invalid step number " << pStepNumber << std::endl; exit(1); } for (i = 6; i < iMax; ++i) { pSBMLSpeciesIds[i - 6] = argv[i]; //std::cout << "Copying pointer to " << argv[i] << "." << std::endl; } try { // Create the global data model. CCopasiDataModel* pDataModel = CCopasiRootContainer::addDatamodel(); // Import the SBML File pDataModel->importSBML(pSBMLFilename); //pDataModel->getModel()->forceCompile(); // create a report with the correct filename and all the species against // time. CReportDefinitionVector* pReports = pDataModel->getReportDefinitionList(); CReportDefinition* pReport = pReports->createReportDefinition("Report", "Output for SBML testsuite run"); pReport->setTaskType(CCopasiTask::timeCourse); pReport->setIsTable(true); std::vector<CRegisteredObjectName>* pTable = pReport->getTableAddr(); pTable->push_back(CCopasiObjectName(pDataModel->getModel()->getCN() + ",Reference=Time")); iMax = iMax - 6; const CCopasiVector<CMetab>& metabolites = pDataModel->getModel()->getMetabolites(); for (i = 0; i < iMax; ++i) { unsigned int j, jMax = metabolites.size(); for (j = 0; j < jMax; ++j) { if (metabolites[j]->getSBMLId() == pSBMLSpeciesIds[i]) { pTable->push_back(metabolites[j]->getObject(CCopasiObjectName("Reference=Concentration"))->getCN()); //std::cout << "adding metabolite " << metabolites[j]->getObjectName() << " to report." << std::endl; break; } } if (j == jMax) { std::cerr << "Could not find a metabolite for the SBML id " << pSBMLSpeciesIds[i] << std::endl; exit(1); } } // create a trajectory task pTrajectoryTask = new CTrajectoryTask(); pTrajectoryTask->getProblem()->setModel(pDataModel->getModel()); pTrajectoryTask->setScheduled(true); pTrajectoryTask->getReport().setReportDefinition(pReport); pTrajectoryTask->getReport().setTarget(CWD + "/" + pOutputFilename); pTrajectoryTask->getReport().setAppend(false); CTrajectoryProblem* pProblem = dynamic_cast<CTrajectoryProblem*>(pTrajectoryTask->getProblem()); pProblem->setStepNumber((const unsigned C_INT32)stepNumber); pProblem->setDuration((const C_FLOAT64)endTime); pProblem->setTimeSeriesRequested(true); //pProblem->setInitialState(pDataModel->getModel()->getInitialState()); CTrajectoryMethod* pMethod = dynamic_cast<CTrajectoryMethod*>(pTrajectoryTask->getMethod()); pMethod->getParameter("Absolute Tolerance")->setValue(1.0e-20); CCopasiVectorN< CCopasiTask > & TaskList = * pDataModel->getTaskList(); TaskList.remove("Time-Course"); TaskList.add(pTrajectoryTask, true); // save the file for control purposes std::string saveFilename = pSBMLFilename; saveFilename = saveFilename.substr(0, saveFilename.length() - 4) + ".cps"; pDataModel->saveModel(saveFilename, NULL, true); // Run the trajectory task pTrajectoryTask->initialize(CCopasiTask::OUTPUT_UI, pDataModel, NULL); pTrajectoryTask->process(true); pTrajectoryTask->restore(); // create another report that will write to the directory where the input file came from // this can be used for debugging // create a trajectory task pTrajectoryTask->getReport().setTarget(pOutputFilename); pTrajectoryTask->initialize(CCopasiTask::OUTPUT_UI, pDataModel, NULL); pTrajectoryTask->process(true); pTrajectoryTask->restore(); } catch (CCopasiException Exception) { std::cerr << Exception.getMessage().getText() << std::endl; } CCopasiRootContainer::destroy(); return 0; }
void test000087::test_simulate_reaction_flux_reference_1() { try { bool result = pCOPASIDATAMODEL->importSBMLFromString(test000087::MODEL_STRING5); CPPUNIT_ASSERT(result = true); } catch (...) { // there should be no exception CPPUNIT_ASSERT(false); } CModel* pModel = pCOPASIDATAMODEL->getModel(); CPPUNIT_ASSERT(pModel != NULL); CPPUNIT_ASSERT(pModel->getCompartments().size() == 1); CPPUNIT_ASSERT(pModel->getMetabolites().size() == 2); CPPUNIT_ASSERT(pModel->getModelValues().size() == 2); CPPUNIT_ASSERT(pModel->getReactions().size() == 1); const CReaction* pReaction = pModel->getReactions()[0]; CPPUNIT_ASSERT(pReaction != NULL); CModelValue* pConstParameter = NULL; CModelValue* pNonConstParameter = NULL; unsigned int i, iMax = pModel->getModelValues().size(); for (i = 0; i < iMax; ++i) { if (pModel->getModelValues()[i]->getStatus() == CModelEntity::FIXED) { pConstParameter = pModel->getModelValues()[i]; } if (pModel->getModelValues()[i]->getStatus() == CModelEntity::ASSIGNMENT) { pNonConstParameter = pModel->getModelValues()[i]; } } CPPUNIT_ASSERT(pConstParameter != NULL); CPPUNIT_ASSERT(pNonConstParameter != NULL); // check if the kinetic law is mass action with const global parameter as the kinetic constant CPPUNIT_ASSERT(pReaction->getChemEq().getSubstrates().size() == 1); CPPUNIT_ASSERT(pReaction->getChemEq().getProducts().size() == 1); CPPUNIT_ASSERT(pReaction->getChemEq().getModifiers().size() == 0); CPPUNIT_ASSERT(pReaction->isReversible() == false); const CFunction* pKineticLaw = pReaction->getFunction(); CPPUNIT_ASSERT(pKineticLaw != NULL); CPPUNIT_ASSERT(pKineticLaw->getType() == CEvaluationTree::MassAction); const std::vector< std::vector<std::string> > & parameterMappings = pReaction->getParameterMappings(); CPPUNIT_ASSERT(parameterMappings.size() == 2); CPPUNIT_ASSERT(parameterMappings[0].size() == 1); CPPUNIT_ASSERT(parameterMappings[0][0] == pConstParameter->getKey()); CPPUNIT_ASSERT(parameterMappings[1].size() == 1); std::string substrateKey = parameterMappings[1][0]; const CCopasiObject* pTempObject = CCopasiRootContainer::getKeyFactory()->get(substrateKey); CPPUNIT_ASSERT(pTempObject != NULL); const CMetab* pSubstrate = dynamic_cast<const CMetab*>(pTempObject); CPPUNIT_ASSERT(pSubstrate != NULL); // check that the assignment consists of only one object node that is a reference to the reaction flux const CExpression* pExpression = pNonConstParameter->getExpressionPtr(); CPPUNIT_ASSERT(pExpression != NULL); const CEvaluationNode* pRoot = pExpression->getRoot(); CPPUNIT_ASSERT(pRoot != NULL); CPPUNIT_ASSERT(CEvaluationNode::type(pRoot->getType()) == CEvaluationNode::OBJECT); const CEvaluationNodeObject* pObjectNode = dynamic_cast<const CEvaluationNodeObject*>(pRoot); CPPUNIT_ASSERT(pObjectNode != NULL); const CRegisteredObjectName cn = pObjectNode->getObjectCN(); std::vector<CCopasiContainer*> listOfContainers; listOfContainers.push_back(pCOPASIDATAMODEL->getModel()); const CCopasiObject* pObject = pCOPASIDATAMODEL->ObjectFromName(listOfContainers, cn); CPPUNIT_ASSERT(pObject != NULL); CPPUNIT_ASSERT(pObject->isReference() == true); CPPUNIT_ASSERT(pObject->getObjectName() == "Flux"); CPPUNIT_ASSERT(pObject->getObjectParent() == pReaction); // Simulate the model (5 steps, stepsize 1 and check that at each step, the value of the variable parameter // is the same as the flux through the reaction. std::ostringstream result; // create a report with the correct filename and all the species against // time. CReportDefinitionVector* pReports = pCOPASIDATAMODEL->getReportDefinitionList(); CReportDefinition* pReport = pReports->createReportDefinition("Report", "Output for simulation"); pReport->setTaskType(CCopasiTask::timeCourse); pReport->setIsTable(false); pReport->setSeparator(CCopasiReportSeparator(", ")); std::vector<CRegisteredObjectName>* pHeader = pReport->getHeaderAddr(); std::vector<CRegisteredObjectName>* pBody = pReport->getBodyAddr(); pHeader->push_back(CCopasiStaticString("time").getCN()); pHeader->push_back(pReport->getSeparator().getCN()); pHeader->push_back(CCopasiStaticString("substrate").getCN()); pHeader->push_back(pReport->getSeparator().getCN()); pHeader->push_back(CCopasiStaticString("reaction flux").getCN()); pHeader->push_back(pReport->getSeparator().getCN()); pHeader->push_back(CCopasiStaticString("variable model value").getCN()); pBody->push_back(CCopasiObjectName(pCOPASIDATAMODEL->getModel()->getCN() + ",Reference=Time")); pBody->push_back(CRegisteredObjectName(pReport->getSeparator().getCN())); pBody->push_back(CCopasiObjectName(pSubstrate->getCN() + ",Reference=Concentration")); pBody->push_back(CRegisteredObjectName(pReport->getSeparator().getCN())); pBody->push_back(CCopasiObjectName(pReaction->getCN() + ",Reference=Flux")); pBody->push_back(CRegisteredObjectName(pReport->getSeparator().getCN())); pBody->push_back(CCopasiObjectName(pNonConstParameter->getCN() + ",Reference=Value")); // // create a trajectory task CTrajectoryTask* pTrajectoryTask = new CTrajectoryTask(); // use LSODAR from now on since we will have events pretty soon pTrajectoryTask->setMethodType(CCopasiMethod::LSODAR); pTrajectoryTask->getProblem()->setModel(pCOPASIDATAMODEL->getModel()); pTrajectoryTask->setScheduled(true); pTrajectoryTask->getReport().setReportDefinition(pReport); // the target needs to be set in order to get output on the stream // object passed to the task in the call to initialize below pTrajectoryTask->getReport().setTarget("test.tmp"); CTrajectoryProblem* pProblem = dynamic_cast<CTrajectoryProblem*>(pTrajectoryTask->getProblem()); pProblem->setStepNumber((const unsigned C_INT32)30); pCOPASIDATAMODEL->getModel()->setInitialTime((const C_FLOAT64)0.0); pProblem->setDuration((const C_FLOAT64)30); pProblem->setTimeSeriesRequested(true); CTrajectoryMethod* pMethod = dynamic_cast<CTrajectoryMethod*>(pTrajectoryTask->getMethod()); pMethod->getParameter("Absolute Tolerance")->setValue(1.0e-12); CCopasiVectorN< CCopasiTask > & TaskList = * pCOPASIDATAMODEL->getTaskList(); TaskList.remove("Time-Course"); TaskList.add(pTrajectoryTask, true); try { pTrajectoryTask->initialize(CCopasiTask::OUTPUT_UI, pCOPASIDATAMODEL, &result); pTrajectoryTask->process(true); pTrajectoryTask->restore(); } catch (...) { // there should be no exception CPPUNIT_ASSERT(false); } // analyse the result CPPUNIT_ASSERT(!result.str().empty()); std::string result_string = result.str(); std::string delimiter = "\n"; std::string delimiter2 = ","; std::size_t lastPos = result_string.find_first_not_of(delimiter); std::size_t pos; std::string line, number_string; unsigned int index = 0; unsigned int index2; std::size_t lastPos2; std::size_t pos2; double last = std::numeric_limits<double>::max(), current = std::numeric_limits<double>::max(); while (lastPos != std::string::npos) { pos = result_string.find_first_of(delimiter, lastPos); line = result_string.substr(lastPos, pos - lastPos); lastPos = result_string.find_first_not_of(delimiter, pos); lastPos2 = line.find_first_not_of(delimiter2); // skip the header line if (index != 0) { index2 = 0; while (lastPos2 != std::string::npos) { pos2 = line.find_first_of(delimiter2, lastPos2); number_string = line.substr(lastPos2, pos2 - lastPos2); lastPos2 = line.find_first_not_of(delimiter2, pos2); // skip the time column if (index2 != 0) { //check that all values in the row (besides the time) // are always the same if (index2 == 1) { last = strToDouble(number_string.c_str(), NULL); if (index == 1) { // just make sure that we don't compare all zeros // The initial value of the substrate hould be higher than 1 CPPUNIT_ASSERT(fabs(pSubstrate->getInitialValue()) > 1); // the first rwo should correspond the the initial value of the substrate // We check this to make sure that the whole timeseries does not consist of zeros CPPUNIT_ASSERT(fabs((last - pSubstrate->getInitialConcentration()) / pSubstrate->getInitialConcentration()) < 1e-20); } } else { current = strToDouble(number_string.c_str(), NULL); CPPUNIT_ASSERT(fabs((current - last) / last) < 1e-20); last = current; } } ++index2; } } ++index; } // make sure there actually were datapoints CPPUNIT_ASSERT(index > 1); // the simulation is set to run until all substrate is depleted, so in the end // last should be below the absolute tolerance for the simulation CPPUNIT_ASSERT(last < *pMethod->getParameter("Absolute Tolerance")->getValue().pDOUBLE); }
/* // Example Primitive { brushDef3 { ( 0 0 1 -604 ) ( ( 0.015625 0 255.9375 ) ( 0 0.015625 0 ) ) "textures/darkmod/stone/brick/blocks_brown" 0 0 0 ( 0 1 0 -1528 ) ( ( 0.015625 0 0 ) ( 0 0.015625 1 ) ) "textures/darkmod/stone/brick/blocks_brown" 0 0 0 ( 1 0 0 -1312 ) ( ( 0.015625 0 255.9375 ) ( 0 0.015625 1 ) ) "textures/darkmod/stone/brick/blocks_brown" 0 0 0 ( 0 0 -1 -0 ) ( ( 0.015625 0 255.9375 ) ( 0 0.015625 0 ) ) "textures/darkmod/stone/brick/blocks_brown" 0 0 0 ( -1 0 0 -1264 ) ( ( 0.015625 0 0.0625 ) ( 0 0.015625 1 ) ) "textures/darkmod/stone/brick/blocks_brown" 0 0 0 ( -0 -1 -0 1524 ) ( ( 0.015625 0 0 ) ( 0 0.015625 1 ) ) "textures/darkmod/stone/brick/blocks_brown" 0 0 0 } } */ scene::INodePtr BrushDef3Parser::parse(parser::DefTokeniser& tok) const { // Create a new brush scene::INodePtr node = GlobalBrushCreator().createBrush(); // Cast the node, this must succeed IBrushNodePtr brushNode = boost::dynamic_pointer_cast<IBrushNode>(node); assert(brushNode != NULL); IBrush& brush = brushNode->getIBrush(); tok.assertNextToken("{"); // Parse face tokens until a closing brace is encountered while (1) { std::string token = tok.nextToken(); // Token should be either a "(" (start of face) or "}" (end of brush) if (token == "}") { break; // end of brush } else if (token == "(") // FACE { // Construct a plane and parse its values Plane3 plane; plane.normal().x() = strToDouble(tok.nextToken()); plane.normal().y() = strToDouble(tok.nextToken()); plane.normal().z() = strToDouble(tok.nextToken()); plane.dist() = -strToDouble(tok.nextToken()); // negate d tok.assertNextToken(")"); // Parse TexDef Matrix4 texdef; tok.assertNextToken("("); tok.assertNextToken("("); texdef.xx() = strToDouble(tok.nextToken()); texdef.yx() = strToDouble(tok.nextToken()); texdef.tx() = strToDouble(tok.nextToken()); tok.assertNextToken(")"); tok.assertNextToken("("); texdef.xy() = strToDouble(tok.nextToken()); texdef.yy() = strToDouble(tok.nextToken()); texdef.ty() = strToDouble(tok.nextToken()); tok.assertNextToken(")"); tok.assertNextToken(")"); // Parse Shader std::string shader = tok.nextToken(); // Parse Contents Flags (and ignore them) tok.skipTokens(3); // Finally, add the new face to the brush IFace& face = brush.addFace(plane, texdef, shader); } else { std::string text = (boost::format(_("BrushDef3Parser: invalid token '%s'")) % token).str(); throw parser::ParseException(text); } } // Final outer "}" tok.assertNextToken("}"); return node; }
void GameScene::update() { ColeScene::update(); p->update(); std::string result = p->clientNetworkUpdate(); while (result != "") { if(result == "ERROR") std::cout << "TODO!!!" << std::endl; if (result != "") { result = result.substr(0, result.length()-1); // Remove the ; std::string command = result.substr(0, result.find("§")); std::vector<std::string> arguments; std::string argumentsString = result.substr(result.find("§")+2); while (argumentsString.length()>0) { arguments.push_back(argumentsString.substr(0, argumentsString.find("§"))); argumentsString = argumentsString.substr(argumentsString.find("§")+2); //it appears that § takes up 2 characters, so +2 } if (command=="join" && arguments[0] != p->name) { std::cout << "New player joining" << std::endl; std::shared_ptr<OtherPlayer> newPlayer = std::make_shared<OtherPlayer>(arguments[0], strToInt(arguments[3])); newPlayer->x = strToInt(arguments[1]); newPlayer->y = strToInt(arguments[2]); otherPlayers.push_back(newPlayer); w->addChild(newPlayer); } if (command == "move" && getOtherPlayerByName(arguments[0]) != NULL) { std::shared_ptr<OtherPlayer> thePlayer = getOtherPlayerByName(arguments[0]); thePlayer->x = strToInt(arguments[1]); thePlayer->y = strToInt(arguments[2]); } if (command == "leave" && getOtherPlayerByName(arguments[0]) != NULL) { std::shared_ptr<OtherPlayer> thePlayer = getOtherPlayerByName(arguments[0]); otherPlayers.remove(thePlayer); w->removeChild(thePlayer); } if (command == "world") { int worldSize = strToInt(arguments[0]); int tilex = 0; int tiley = 0; for (int i=1; i<arguments.size(); i++) { w->setTile(tilex, tiley, strToInt(arguments[i])); tiley++; if (tiley == worldSize) { tiley = 0; tilex++; } } } if (command == "newbullet" && arguments[0] != p->name) { std::shared_ptr<BulletClient> b = std::make_shared<BulletClient>(); //s.broadcast("newbullet§"+p->name+"§"+doubleToStr(b->x)+"§"+doubleToStr(b->y)+"§"+doubleToStr(b->angle)+"§"+doubleToStr(b->speed)+"§"+doubleToStr(b->ttl)+"§"+doubleToStr(b->bulletType)+";"); b->owner = arguments[0]; b->setPos(strToDouble(arguments[1]), strToDouble(arguments[2])); b->angle = strToDouble(arguments[3]); b->speed = strToDouble(arguments[4]); b->ttl = strToDouble(arguments[5]); b->bulletType = strToInt(arguments[6]); b->tag = 1; w->addChild(b); } } result = p->clientNetworkUpdate(); } int futurex = 0, futurey = 0; const Uint8 *state = SDL_GetKeyboardState( NULL ); if (state[SDL_SCANCODE_W]) futurey--; if (state[SDL_SCANCODE_S]) futurey++; if (state[SDL_SCANCODE_A]) futurex--; if (state[SDL_SCANCODE_D]) futurex++; if (futurex != 0 || futurey != 0) p->move(futurex, futurey); int mousex, mousey; Uint32 mouseState = SDL_GetMouseState(&mousex, &mousey); if (mouseState&SDL_BUTTON(1)) { int altMouseX = mousex+p->x-(RenderManager::getInstance()->getScreenX()/2); int altMouseY = mousey+p->y-(RenderManager::getInstance()->getScreenY()/2); if (p->shootTowards(altMouseX, altMouseY)) { std::shared_ptr<BulletClient> b = std::make_shared<BulletClient>(); b->setPos(p->x, p->y); b->speed = 5; b->ttl = 100; b->angle = angleBetween(p->x, p->y, altMouseX, altMouseY); b->owner = p->name; b->tag = 1; w->addChild(b); } } }
int getToken(tToken *Token, FILE* source) { //prvne zkontroluji frontu tokenu if (TQueue != NULL) {//nema cenu si neco na frontu zkouset kdyz je NULL TQDequeue(Token); if (Token != NULL) {//token byl ve fronte return 1; } } //alokace pameti pro cteny token tToken tok = (tToken)malloc(sizeof(struct stToken)); *Token = tok; /* @var c int actual character*/ int c = -1; /* @var prevRest int poslední načtený znak (Zbytek posledního průchodu) */ static int pom = -1; /* @var string s Uklada aktualne cteny string pokud je treba, pri kazdem * konci teto funkce musi byt volano strFree. */ string s; //strInit vraci 1 při chybe if (strInit(&s)) { FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } //string kam se ukladaji sekvence pro escape sekvence string escape; //nastavime vychozi stav int state = START; while (1) { if (pom > 0) {//pozustatek z minuleho cteni c = pom; pom = -1;//-1 je jedina hodnota kterou by nemela pomocna promenna nabyt pokud v ni opravdu je pozustatek //pokud je v ni opravdu EOF tak pomoci getc() ho stejne dostanu znovu } else { c = getc(source); character++; if (c == '\n') {//pokud ctu dalsi radek tak vynuluji citadlo znaku a inkrementuji citadlo radku line++; character = 0; } } switch (state) { case START: //pocatecni bile znaky nic nezmeni if (isspace(c)) { state = START; } //zacatek identifikatoru else if (isalpha(c) || c == '_') { state = IDENTIFICATOR; if (strAddChar(&s, c)) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } //ulozi prvni nulu v cisle else if (c == '0') { state = FLOAT_OR_INT; if (strAddChar(&s, c)) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } //platna cislice na zacatku retezce znamena celou cast cisla else if (c >= '1' && c <= '9') { state = INT_PART; if (strAddChar(&s, c)) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } //strednik ulozi token strednik else if (c == ';') { tok->typ = SEMICOLON; strFree(&s); return 1; } //zacatek escape sekvenci rozsireni BASE else if (c == '\\') { state = ESCAPE; } //string zacina uvozovkami else if (c == '\"') { state = STRING; } //lomeno muze byt operatro nebo zacatek komentare else if (c == '/') { state = DIVISION_COMMENT; } //unarni minus, odcitani nebo dekremenrace else if (c == '-') { //jsem schopny rozlisit jen dekrementaci a minus //unarni minus ani rozdil mezi postfix/prefix neurcim state = DECREMENT_OPERATOR; } //scitani nebo inkrementace else if (c == '+') { state = INCREMENT_OPERATOR; } //nasobeni znamena jedine nasobeni else if (c == '*') { tok->typ = MULTIPLY; strFree(&s); return 1; } //toto mohou byt opertary se dvema znaky i jednim else if (c == '!' || c == '<' || c == '>' || c == '=') { state = TWO_CHAR_OPER; if (strAddChar(&s, c)) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } //zaovrky ihned ulozime jako token else if (c == ')') { tok->typ = PARENTHESIS_CLOSING; strFree(&s); return 1; } else if (c == '(') { tok->typ = PARENTHESIS_OPENING; strFree(&s); return 1; } else if (c == '}') { tok->typ = BRACES_CLOSING; strFree(&s); return 1; } else if (c == '{') { tok->typ = BRACES_OPENING; strFree(&s); return 1; } //logicky or else if (c == '|') { state = LOGICAL_OR; } //logicky and else if (c == '&') { state = LOGICAL_AND; } //carka (comma) operator ulozime do tokenu else if (c == ',') { tok->typ = COMMA; strFree(&s); return 1; } //konec souboru cas vyhlasit chyby pokud nastaly jinak ulozit do tokenu EOF else if (c==EOF) { tok->typ = END_OF_FILE; strFree(&s); if (errorFlag) { freeTokenMem(&tok); return 42; } return 1; } else {//pokud na zacatku tokenu prislo cokoli jineho tak scanner nevi co se deje errorFlag = 1; Warning("%sLine - %d:%d\t- Unknown symbol.\n", ERR_MESSAGES[ERR_LEX], line, character); strFree(&s); freeTokenMem(&tok); return 42; } break; case INT_PART: //cteni cele casti cisla //cislice ukladam if (c >= '0' && c <= '9') { state = INT_PART; if (strAddChar(&s, c)) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } //zacatek exponentu else if (c == 'e' || c == 'E') { state = EXPONENT_CHECK; if (strAddChar(&s, c)) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } //zacatek desetine casti else if (c == '.') { //vlozen testovaci stav pro podminku ze za des. teckou musi byt cislice state = FLOAT_CHECK; if (strAddChar(&s, c)) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } //uloz cele cislo else { int val; if (!strToInt(&s, &val)) { freeTokenMem(&tok); strFree(&s); FatalError(99, "%s-%d: Chyba pri nacteni celeho cisla.", ERR_MESSAGES[ERR_ALLOC], line); return 42; } pom = c; tok->typ = TYPE_INTEGER; tok->value.intVal = val; strFree(&s); return 1; } break; case FLOAT_OR_INT: //prvni nula byla ulozena pocatecnim stavu ted je necham byt if (c == '0') { state = FLOAT_OR_INT; } else if (c >= '1' && c<='9') {//pokud nasleduje cislice ctu cele cislo state = INT_PART; if (strAddChar(&s, c)) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } else if (c == '.') { //zacatek desetine casti state = FLOAT_CHECK; if (strAddChar(&s, c)) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } else if (c == 'e' || c == 'E') { //zacatek exponentu state = EXPONENT_CHECK; if (strAddChar(&s, c)) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } else { //konec celeho cisla int val; if (!strToInt(&s, &val)) { errorFlag = 1; Warning("%sLine - %d:%d\t- Nepodarilo se nacist ciselny literal.\n",ERR_MESSAGES[ERR_LEX], line, character); strFree(&s); freeTokenMem(&tok); return 42; } tok->typ = TYPE_INTEGER; tok->value.intVal = val; strFree(&s); pom = c; return 1; } break; case FLOAT_CHECK: //tento stav slouzi ke kontrole neprazdnosti desetine casti if (c >= '0' && c <= '9') { state = FLOAT_PART; if (strAddChar(&s, c)) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } //pokud za teckou neni cislice je to chyba else { pom = c; errorFlag = 1; Warning("%sLine - %d:%d\t- Nepodarilo se nacist ciselny literal. Desetina cast nesmi byt prazdna.\n", ERR_MESSAGES[ERR_LEX], line, character); strFree(&s); freeTokenMem(&tok); return 42; } break; case FLOAT_PART: if (c >= '0' && c <= '9') { //ulozi cislo a pokracuje ve cteni state = FLOAT_PART; if (strAddChar(&s, c)) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } else if (c == 'e' || c == 'E') { //zacatek exponentu state = EXPONENT_CHECK; if (strAddChar(&s, c)) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } else { //konec desetineho cisla, ulozme jej double val; if (!strToDouble(&s, &val)) { errorFlag = 1; Warning("%sLine - %d:%d\t- Nepodarilo se nacist ciselny literal.\n",ERR_MESSAGES[ERR_LEX], line, character); strFree(&s); freeTokenMem(&tok); return 42; } tok->typ = TYPE_DOUBLE; tok->value.doubleVal = val; strFree(&s); pom = c; return 1; } break; case EXPONENT_CHECK: if (c >= '0' && c <= '9') { //prislo cislo, ulozi jej a pokracuje j*z ve cteni exponentu state = EXPONENT; if (strAddChar(&s, c)) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } else if (c == '+' || c == '-') { //znamenko na zacatku exponentu state = EXPONENT_PLUS_MINUS_CHECK; if (strAddChar(&s, c)) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } //nemuzeme napsat exponent a neudat ho else{ errorFlag = 1; Warning("%sLine - %d:%d\t- Exponent musi obsahovat validni cislici.\n",ERR_MESSAGES[ERR_LEX], line, character); pom = c; strFree(&s); freeTokenMem(&tok); return 42; } break; case EXPONENT_PLUS_MINUS_CHECK: if (c >= '0' && c <= '9') { //spravne bylo za znamenkem exponentu cislo //pokracuji ve cteni expoenntu state = EXPONENT; if (strAddChar(&s, c)) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } else { //nemuzem napsat znamenko exponentu a neudat jeho hodnotu errorFlag = 1; Warning("%sLine - %d:%d\t- Exponent musi obsahovat validni cislici.\n",ERR_MESSAGES[ERR_LEX], line, character); pom = c; strFree(&s); freeTokenMem(&tok); return 42; } break; case EXPONENT: if (c >= '0' && c <= '9') { //cte cisla dokud prichazi state = EXPONENT; if (strAddChar(&s, c)) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } else { //prislo cokoli jineho nez cislo double val = 42; if (!strToDouble(&s, &val)) { errorFlag = 1; Warning("%sLine - %d:%d\t- Nepodarilo se nacist ciselny literal.\n",ERR_MESSAGES[ERR_LEX], line, character); strFree(&s); freeTokenMem(&tok); return 42; } tok->typ = TYPE_DOUBLE; tok->value.doubleVal = val; pom = c;//dalsi znak patri dalsimu tokenu strFree(&s); return 1; } break; case ESCAPE: //escape sekvence celociselne konstanty switch (c) { //binarni escape sekvence case 'b': case 'B': state = BINARY_NUMBER; break; //oktalova escape sekvence case '0': state = OCTAL_NUMBER; break; //hexadecimalni escape sekvence case 'x': case 'X': state = HEX_DEC_NUMBER; break; //cokoli jineho je chybou default: errorFlag = 1; Warning("%sLine - %d:%d\t- Ocekavan symbol pro ciselnou soustavu.\n",ERR_MESSAGES[ERR_LEX], line, character); strFree(&s); freeTokenMem(&tok); return 42; break; } break; case BINARY_NUMBER: //escape sekvence obsahujici binarni cislo if (c == '0' || c == '1') { //zahazuji nevyznamne nuly if (!(c == '0' && strGetLength(&s) == 0)) { if (strAddChar(&s, c)) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } } else { pom = c; int val = 0; if (!strBinToInt(&s, &val)) { strFree(&s); freeTokenMem(&tok); return 42; } tok->typ = TYPE_INTEGER; tok->value.intVal = val; strFree(&s); return 1; } break; case OCTAL_NUMBER: //escape sekvence obsahujici oktalove cislo if (c >= '0' && c <= '7') { //zahazuji nevyznamne nuly if (!(c == '0' && strGetLength(&s) == 0)) { if (strAddChar(&s, c)) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } } else { pom = c; int val = 0; if (!strOctToInt(&s, &val)) { strFree(&s); freeTokenMem(&tok); return 42; } tok->typ = TYPE_INTEGER; tok->value.intVal = val; strFree(&s); return 1; } break; case HEX_DEC_NUMBER: //escape sekvence obsahujici hexadecimalni cislo if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) { //zahazuji nevyznamne nuly if (!(c == '0' && strGetLength(&s)==0)) { if (strAddChar(&s, c)) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } } else { pom = c; int val = 0; if (!strHexToInt(&s, &val)) { strFree(&s); freeTokenMem(&tok); return 42; } tok->typ = TYPE_INTEGER; tok->value.intVal = val; strFree(&s); return 1; } break; case LOGICAL_AND: //logicky and //v IFJ2015 neexistuje binarni and proto jediny prijatelny znak //v tuto chvili je & if (c == '&') { tok->typ = LOG_AND_OPER; strFree(&s); return 1; } else { pom = c; errorFlag = 1; Warning("%sLine - %d:%d\t- Binarni and neni podporovan v IFJ2015.\n",ERR_MESSAGES[ERR_LEX], line, character-1); strFree(&s); freeTokenMem(&tok); return 42; } break; case LOGICAL_OR: //logicky or //v IFJ2015 neexistuje binarni or proto jediny prijatelny znak //v tuto chvili je | if (c == '|') { tok->typ = LOG_OR_OPER; strFree(&s); return 1; } else { /*Abych se zotavil po teto chybe a docetl soubor*/ errorFlag = 1; Warning("%sLine - %d:%d\t- Binarni or neni podporovan v IFJ2015.\n",ERR_MESSAGES[ERR_LEX], line, character - 1); pom = c; strFree(&s); freeTokenMem(&tok); return 42; } break; case STRING: if (c == EOF) { errorFlag = 1; Warning("%sLine - %d:%d\t- Necekany konec souboru.\n",ERR_MESSAGES[ERR_LEX], line, character); strFree(&s); freeTokenMem(&tok); return 42; } else if (c == '\\') { state = STRING_ESCAPE; } else if (c == '"') {//konec retezce uloz ho tok->typ = TYPE_STRING; if (strInit(&tok->value.stringVal)) { //return stringval } if (strCopyString(&tok->value.stringVal, &s)) { //return error; } strFree(&s); return 1; } else if (c < 1 || c>255) {//nejaky znak mimo ASCII chyba } else {//uloz si znak if (strAddChar(&s, c)) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } break; case STRING_ESCAPE: //escape sekvence ve stringu switch (c) { //binarni escape sekvence case 'b': case 'B': if (strInit(&escape)) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } state = STRING_BINARY_NUMBER; break; //oktalova escape sekvence case '0': if (strInit(&escape)) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } state = STRING_OCTAL_NUMBER; break; case 'x': case 'X': //hexadecimalni escape sekvence if (strInit(&escape)) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } state = STRING_HEX_DEC_NUMBER; break; case '\\': //escape sekvence backslash if (strAddChar(&s, '\\')) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } state = STRING; break; case 'n': //escape sekvence noveho radku if (strAddChar(&s, '\n')) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } state = STRING; break; case 't': //escape sekvence tabulatoru if (strAddChar(&s, '\t')) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } state = STRING; break; case '\"': //escape sekvence uvozovek if (strAddChar(&s, '\"')) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } state = STRING; break; default: //cokoliv jineho je chybnym zapsani escape sekvence errorFlag = 1; Warning("%sLine - %d:%d\t- Ocekavana escape sekvence\n", ERR_MESSAGES[ERR_LEX], line, character); strFree(&s); freeTokenMem(&tok); return 42; break; } break; case STRING_BINARY_NUMBER: if ((c == '0' || c == '1')) {//ctu validni vstup if (strGetLength(&escape) < 8) {//jeste nemam 8 cislic tak ctu dal if (strAddChar(&escape, c)) { freeTokenMem(&tok); strFree(&escape); strFree(&s); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } else {//mam 8 cislic pom = c; int val; if (strBinToInt(&escape, &val) && val >= 1 && val <= 255) { if (strAddChar(&s, (char)val)) {//precteny znak pridam do stringu freeTokenMem(&tok); strFree(&escape); strFree(&s); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } else {//nepodarilo se prevest escape na string errorFlag = 1; Warning("%sLine - %d:%d\t- Retezec \"%s\" neni platnou escape sekvenci.\n", ERR_MESSAGES[ERR_LEX], line, character, escape.str); } strFree(&escape); state = STRING; } } else { if (strGetLength(&escape) < 8) { errorFlag = 1; Warning("%sLine - %d:%d\t- Retezec \"%s\" neni platnou escape sekvenci.\n", ERR_MESSAGES[ERR_LEX], line, character, escape.str); } if (strGetLength(&escape) == 8) { int val; if (strBinToInt(&escape, &val) && val >= 1 && val <= 255) { if (strAddChar(&s, (char)val)) { freeTokenMem(&tok); strFree(&escape); strFree(&s); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } else { errorFlag = 1; Warning("%sLine - %d:%d\t- Retezec \"%s\" neni platnou escape sekvenci.\n", ERR_MESSAGES[ERR_LEX], line, character, escape.str); } } pom = c; strFree(&escape); state = STRING; } break; case STRING_OCTAL_NUMBER: if ((c >= '0' && c <= '7')) {//ctu validni vstup if (strGetLength(&escape) < 3) { if (strAddChar(&escape, c)) { freeTokenMem(&tok); strFree(&escape); strFree(&s); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } else { pom = c; int val; if (strOctToInt(&escape, &val) && val >= 1 && val <= 255) { if (strAddChar(&s, (char)val)) { freeTokenMem(&tok); strFree(&escape); strFree(&s); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } else { errorFlag = 1; Warning("%sLine - %d:%d\t- Retezec \"%s\" neni platnou escape sekvenci.\n", ERR_MESSAGES[ERR_LEX], line, character, escape.str); } strFree(&escape); state = STRING; } } else { if (strGetLength(&escape) < 3) { errorFlag = 1; Warning("%sLine - %d:%d\t- Retezec \"%s\" neni platnou escape sekvenci.\n", ERR_MESSAGES[ERR_LEX], line, character, escape.str); } if (strGetLength(&escape) == 3) { int val; if (strOctToInt(&escape, &val) && val >= 1 && val <= 255) { if (strAddChar(&s, (char)val)) { freeTokenMem(&tok); strFree(&escape); strFree(&s); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } else { errorFlag = 1; Warning("%sLine - %d:%d\t- Retezec \"%s\" neni platnou escape sekvenci.\n", ERR_MESSAGES[ERR_LEX], line, character, escape.str); } } pom = c; strFree(&escape); state = STRING; } break; case STRING_HEX_DEC_NUMBER: if ((c >= '0' && c <= '9')||(c >= 'a' && c <= 'f')|| (c >= 'A' && c <= 'F')) {//ctu validni vstup if (strGetLength(&escape) < 2) { if (strAddChar(&escape, c)) { freeTokenMem(&tok); strFree(&escape); strFree(&s); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } else { int val; pom = c; if (strHexToInt(&escape, &val) && val >= 1 && val <= 255) { if (strAddChar(&s, (char)val)) { freeTokenMem(&tok); strFree(&escape); strFree(&s); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } else { errorFlag = 1; Warning("%sLine - %d:%d\t- Retezec \"%s\" neni platnou escape sekvenci.\n", ERR_MESSAGES[ERR_LEX], line, character, escape.str); } strFree(&escape); state = STRING; } } else { if (strGetLength(&escape) < 2) { errorFlag = 1; Warning("%sLine - %d:%d\t- Retezec \"%s\" neni platnou escape sekvenci.\n", ERR_MESSAGES[ERR_LEX], line, character, escape.str); } if (strGetLength(&escape) == 2) { int val; if (strHexToInt(&escape, &val) && val >= 1 && val <= 255) { if (strAddChar(&s, (char)val)) { freeTokenMem(&tok); strFree(&escape); strFree(&s); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } else { errorFlag = 1; Warning("%sLine - %d:%d\t- Retezec \"%s\" neni platnou escape sekvenci.\n", ERR_MESSAGES[ERR_LEX], line, character, escape.str); } } pom = c; strFree(&escape); state = STRING; } break; case IDENTIFICATOR: //ctu cislice, pismena nebo podtrzitka if (isalnum(c) || c == '_') { if (strAddChar(&s, c)) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } //konec identifikatoru else { pom = c; int isIdent = isKeyWord(&s); tok->typ = isIdent; if (isIdent == TYPE_IDENTIFICATOR) { if (strInit(&(tok->value.stringVal))) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } if (strCopyString(&(tok->value.stringVal), &s)) { strFree(&s); freeTokenMem(&tok); FatalError(99, ERR_MESSAGES[ERR_ALLOC]); } } if (isIdent == KEYW_FALSE) { tok->typ = TYPE_BOOL; tok->value.boolVal = false; } if (isIdent == KEYW_TRUE) { tok->typ = TYPE_BOOL; tok->value.boolVal = true; } strFree(&s); return 1; } break; case DIVISION_COMMENT: if (c == '*') { state = BLOCK_COMMENT; } else if (c == '/') { state = LINE_COMMENT; } else {//jednoznakovy operator deleni tok->typ = DIVISION; pom = c; strFree(&s); return 1; } break; case LINE_COMMENT: if (c == '\n') {//konec radkoveho komentare hledame dalsi lexem state = START; } else if (c == EOF) {//nemusi byt lf pred koncem souboru pom = c; state = START; } else {//komentar pokracuje //reflection nepodporujeme takže komentáře zahodíme } break; case BLOCK_COMMENT: if (c == EOF) { Warning("%sLine - %d:%d\t- Necekany konec souboru.\n", ERR_MESSAGES[ERR_LEX], line, character); strFree(&s); freeTokenMem(&tok); return 42; } /*else if (c=='/') { state = NESTED_BLOCK_COMMENT_CHECK; }*/ else if (c=='*') { state = END_BLOCK_COMMENT; } break; case END_BLOCK_COMMENT: if (c == '*') { //zůstaneme tady komentář může končit x hvězdičkama } else if (c == EOF) { Warning("%sLine - %d:%d\t- Necekany konec souboru.\n", ERR_MESSAGES[ERR_LEX], line, character); strFree(&s); freeTokenMem(&tok); return 42; } else if (c == '/') {//konec blokového komentáře jdeme hledat další lexém state = START; } else { state = BLOCK_COMMENT; } break; //dvouznakove operatry case TWO_CHAR_OPER: //jako druhy znak muze jen rovna se //dle prvniho znaku rozhodneme co ulozime if (c == '=') { switch (s.str[0]) { case '!': tok->typ = NOT_EQUAL_OPER; break; case '<': tok->typ = LESS_EQUAL; break; case '>': tok->typ = GREATER_EQUAL; break; case '=': tok->typ = EQUAL; break; default: break; } } //pokud prislo cokoli jineho tak dle prvniho znaku rozhodneme co ulozime else { pom = c; switch (s.str[0]) { case '!': tok->typ = LOG_NOT_OPER; break; case '<': tok->typ = LESS; break; case '>': tok->typ = GREATER; break; case '=': tok->typ = SET_OPER; break; default: break; } } strFree(&s); return 1; break; case DECREMENT_OPERATOR: //druhe minus v rade znamena dekrementaci if (c == '-') { tok->typ = DECREMENTATION; strFree(&s); return 1; } //cokoli jineho znamena pouze minus else { pom = c; tok->typ = MINUS; strFree(&s); return 1; } break; case INCREMENT_OPERATOR: //druhe plus v rade je inkrementace if (c == '+') { tok->typ = INCREMENTATION; strFree(&s); return 1; } //pouze scitani else { pom = c; tok->typ = PLUS; strFree(&s); return 1; } break; default: break; } } }
bool NumberParser::tryParseFloat(const std::string& s, double& value, char decSep, char thSep) { return strToDouble(s.c_str(), value, decSep, thSep); }
int main(int argc, char *argv[]) { // Parse the commandline options // first argument is the SBML filename // second argument is the endtime // third argument is the step number // fourth argument is the filename where the results are to be written // fifth argument is the tmp directory (this is not needed) // the rest of the arguments are species names for the result try { // Create the root container. CCopasiRootContainer::init(0, NULL, false); } catch (copasi::autoexcept &e) {} catch (copasi::option_error &e) {} if (argc < 5) { std::cout << "Usage: stochastic-testsuite METHOD SBMLFILENAME ENDTIME STEPNUMBER REPEATS OUTFILENAME SPECIESID1 SPECIESID2 ..." << std::endl; exit(1); } const char* pMethodType = argv[1]; const char* pSBMLFilename = argv[2]; const char* pEndTime = argv[3]; const char* pStepNumber = argv[4]; const char* pRepeats = argv[5]; const char* pOutputFilename = argv[6]; unsigned int NUMARGS = 7; /* std::cout << "Input : " << pSBMLFilename << std::endl; std::cout << "Endtime : " << pEndTime << std::endl; std::cout << "Stepnumber: " << pStepNumber << std::endl; std::cout << "Repeats : " << pRepeats << std::endl; std::cout << "Output file: " << pOutputFilename << std::endl; */ char** pSBMLSpeciesIds = new char * [argc - NUMARGS]; unsigned int i, iMax = argc; CTrajectoryTask* pTrajectoryTask = NULL; CScanTask* pScanTask = NULL; std::string CWD = COptions::getPWD(); double endTime = strToDouble(pEndTime, &pEndTime); double stepNumber = strToDouble(pStepNumber, &pStepNumber); char** pTmpP = (char**)(&pRepeats); long int repeats = strtol(pRepeats, pTmpP , 10); CCopasiMethod::SubType MethodType; if (!strcmp(pMethodType, "stochastic")) { MethodType = CCopasiMethod::stochastic; } else if (!strcmp(pMethodType, "directMethod")) { MethodType = CCopasiMethod::directMethod; } else if (!strcmp(pMethodType, "tauLeap")) { MethodType = CCopasiMethod::tauLeap; } else if (!strcmp(pMethodType, "adaptiveSA")) { MethodType = CCopasiMethod::adaptiveSA; } else if (!strcmp(pMethodType, "LSODA")) { MethodType = CCopasiMethod::deterministic; } else { std::cerr << "Invalid method type. Valid options are:" << std::endl; std::cerr << " stochastic" << std::endl; std::cerr << " directMethod" << std::endl; std::cerr << " tauLeap" << std::endl; } if (endTime == 0.0) { std::cerr << "Invalid endtime " << pEndTime << std::endl; exit(1); } if (stepNumber == 0.0) { std::cerr << "Invalid step number " << pStepNumber << std::endl; exit(1); } for (i = NUMARGS; i < iMax; ++i) { pSBMLSpeciesIds[i - NUMARGS] = argv[i]; //std::cout << "Copying pointer to " << argv[i] << "." << std::endl; } try { // Create the global data model. CCopasiDataModel* pDataModel = CCopasiRootContainer::addDatamodel(); // Import the SBML File pDataModel->importSBML(pSBMLFilename); //pDataModel->getModel()->forceCompile(); // create a report with the correct filename and all the species against // time. CReportDefinitionVector* pReports = pDataModel->getReportDefinitionList(); CReportDefinition* pReport = pReports->createReportDefinition("Report", "Output for stochastic testsuite run"); pReport->setTaskType(CCopasiTask::timeCourse); pReport->setIsTable(false); CCopasiReportSeparator Separator(std::string(",")); pReport->setSeparator(Separator); std::vector<CRegisteredObjectName> * pHeader = pReport->getHeaderAddr(); std::vector<CRegisteredObjectName> * pBody = pReport->getBodyAddr(); // Add time column pHeader->push_back(CCopasiStaticString("time").getCN()); pBody->push_back(CCopasiObjectName(pDataModel->getModel()->getCN() + ",Reference=Time")); iMax = iMax - NUMARGS; const CCopasiVector<CMetab>& metabolites = pDataModel->getModel()->getMetabolites(); for (i = 0; i < iMax; ++i) { pHeader->push_back(Separator.getCN()); pBody->push_back(Separator.getCN()); unsigned int j, jMax = metabolites.size(); std::string SBMLId = unQuote(pSBMLSpeciesIds[i]); for (j = 0; j < jMax; ++j) { if (metabolites[j]->getSBMLId() == SBMLId) { break; } } if (j == jMax) { std::cerr << "Could not find a metabolite for the SBML id \"" << pSBMLSpeciesIds[i] << "\"" << std::endl; exit(1); } pHeader->push_back(CCopasiStaticString(SBMLId).getCN()); pBody->push_back(metabolites[j]->getObject(CCopasiObjectName("Reference=ParticleNumber"))->getCN()); } // create a trajectory task pTrajectoryTask = new CTrajectoryTask(); pTrajectoryTask->setMethodType(MethodType); pTrajectoryTask->getProblem()->setModel(pDataModel->getModel()); pTrajectoryTask->setScheduled(false); //pTrajectoryTask->getReport().setReportDefinition(pReport); //pTrajectoryTask->getReport().setTarget(CWD + "/" + pOutputFilename); //pTrajectoryTask->getReport().setAppend(false); CTrajectoryProblem* pProblem = dynamic_cast<CTrajectoryProblem*>(pTrajectoryTask->getProblem()); pProblem->setStepNumber((const unsigned C_INT32)stepNumber); pProblem->setDuration((const C_FLOAT64)endTime); pProblem->setTimeSeriesRequested(true); pProblem->setTimeSeriesRequested(false); //pProblem->setInitialState(pDataModel->getModel()->getInitialState()); CCopasiVectorN< CCopasiTask > & TaskList = * pDataModel->getTaskList(); TaskList.remove("Time-Course"); TaskList.add(pTrajectoryTask, true); // create a scan task pScanTask = new CScanTask(pDataModel); CScanProblem* pScanProblem = dynamic_cast<CScanProblem*>(pScanTask->getProblem()); pScanProblem->setModel(pDataModel->getModel()); pScanTask->setScheduled(true); pScanTask->getReport().setReportDefinition(pReport); pScanTask->getReport().setTarget(CWD + "/" + pOutputFilename); pScanTask->getReport().setAppend(false); pScanProblem->setSubtask(CCopasiTask::timeCourse); pScanProblem->createScanItem(CScanProblem::SCAN_REPEAT, repeats); pScanProblem->setOutputInSubtask(true); pScanProblem->setContinueFromCurrentState(false); TaskList.remove("Scan"); TaskList.add(pScanTask, true); // save the file for control purposes std::string saveFilename = pSBMLFilename; saveFilename = saveFilename.substr(0, saveFilename.length() - 4) + ".cps"; pDataModel->saveModel(saveFilename, NULL, true); // Run the trajectory task pScanTask->initialize(CCopasiTask::OUTPUT_SE, pDataModel, NULL); pScanTask->process(true); pScanTask->restore(); // create another report that will write to the directory where the input file came from // this can be used for debugging // create a trajectory task // pScanTask->getReport().setTarget(pOutputFilename); // pScanTask->initialize(CCopasiTask::OUTPUT_SE, pDataModel, NULL); // pScanTask->process(true); // pScanTask->restore(); } catch (CCopasiException Exception) { std::cerr << Exception.getMessage().getText() << std::endl; } CCopasiRootContainer::destroy(); return 0; }