Example #1
0
void ParserMgr::AssociateVars(mu::Parser& parser)
{
#ifdef DEBUG_PM_FUNC
    ScopeTracker st("ParserMgr::AssociateVars", std::this_thread::get_id());
#endif
    try
    {
        for (size_t i=0; i<ds::NUM_MODELS; ++i)
        {
            const ParamModelBase* model = _modelMgr->Model((ds::PMODEL)i);
            if (model->Id()==ds::INIT || model->Id()==ds::COND) continue;
            double* data = _modelData[i].first,
                    * temp_data = _modelData[i].second;
            const size_t num_pars = model->NumPars();
            for (size_t j=0; j<num_pars; ++j)
            {
                const std::string& key = model->ShortKey(j);
                parser.DefineVar(key, &data[j]);
                if (model->DoEvaluate())
                    parser.DefineVar(model->TempKey(j), &temp_data[j]);
            }
        }
    }
    catch (mu::ParserError& e)
    {
        _log->AddExcept("ParserMgr::AssociateVars: " + AnnotateErrMsg(e.GetMsg(), parser));
    }
}
Example #2
0
static void addSBMLFunctions(mu::Parser & p)
{
	p.DefineFun("pow", &power , false);
	p.DefineFun("ge", &ge , false);
	p.DefineFun("gt", &gt , false);
	p.DefineFun("le", &le , false);
	p.DefineFun("lt", &lt , false);
}
Example #3
0
	//initialize muparser and graphics 
	void init() {
		p.DefineVar("theta", &t);
		p.DefineConst("pi", pi);
		graph.create(size,size,sf::Color::Transparent);
		graphTx.loadFromImage(graph);
		graphSpr.setTexture(graphTx);

		//center on screen
		graphSpr.setOrigin(size/2,size/2);
		graphSpr.setPosition(windowsize.x/2, windowsize.y/2);
	}
Example #4
0
	//plots draw_speed points per frame
	void animation() {
		// p.DefineVar("theta", &t);
		for(int i = 0; (i < speed || speed == 0) && t <= tmax ; i++) {
			t += tinc;
			r = p.Eval();
			plot();
		}
	}
/**
 * Calculate the value of a formula parsed by muParser
 * @param parser :: muParser object
 * @return calculated value
 * @throw InstrumentDefinitionError if parser throws during evaluation
 */
double DetectorEfficiencyCorUser::evaluate(const mu::Parser &parser) const {
  try {
    return parser.Eval();
  } catch (mu::Parser::exception_type &e) {
    throw Kernel::Exception::InstrumentDefinitionError(
        "Error calculating formula from string. Muparser error message is: " +
        e.GetMsg());
  }
}
Example #6
0
	//constructor
	Func(std::string tag,
	     int speed_in,
	     int line_width_in,
	     double tmax_in,
	     double tinc_in,
	     double rotation_in,
	     sf::Color color_in )

		: speed( speed_in ),
		  line_width(line_width_in),
		  t (0),
		  tmax ( tmax_in ),
		  tinc ( tinc_in ),
		  rotation( rotation_in ),
		  color ( color_in )
	{
		p.DefineVar("theta", &t);
		p.SetExpr(tag);
	}
Example #7
0
	VoxelOp( std::string expr ) {
		parser.SetExpr( expr );
		parser.DefineVar( std::string( "vox" ), &voxBuff );
		parser.DefineVar( std::string( "pos_x" ), &posBuff[data::rowDim] );
		parser.DefineVar( std::string( "pos_y" ), &posBuff[data::columnDim] );
		parser.DefineVar( std::string( "pos_z" ), &posBuff[data::sliceDim] );
		parser.DefineVar( std::string( "pos_t" ), &posBuff[data::timeDim] );
	}
Example #8
0
/** \brief Check for external keywords.
*/
int CheckKeywords(const mu::char_type *a_szLine, mu::Parser &a_Parser)
{
  string_type sLine(a_szLine);

  if ( sLine == _T("quit") )
  {
    return -1;
  }
  else if ( sLine == _T("list var") )
  {
    ListVar(a_Parser);
    return 1;
  }
  else if ( sLine == _T("list const") )
  {
    ListConst(a_Parser);
    return 1;
  }
  else if ( sLine == _T("list exprvar") )
  {
    ListExprVar(a_Parser);
    return 1;
  }
  else if ( sLine == _T("list const") )
  {
    ListConst(a_Parser);
    return 1;
  }
  else if ( sLine == _T("locale de") )
  {
    mu::console() << _T("Setting german locale: ArgSep=';' DecSep=',' ThousandsSep='.'\n");
    a_Parser.SetArgSep(';');
    a_Parser.SetDecSep(',');
    a_Parser.SetThousandsSep('.');
    return 1;
  }
  else if ( sLine == _T("locale en") )
  {
    mu::console() << _T("Setting english locale: ArgSep=',' DecSep='.' ThousandsSep=''\n");
    a_Parser.SetArgSep(',');
    a_Parser.SetDecSep('.');
    a_Parser.SetThousandsSep();
    return 1;
  }
  else if ( sLine == _T("locale reset") )
  {
    mu::console() << _T("Resetting locale\n");
    a_Parser.ResetLocale();
    return 1;
  }

  return 0;
}
/// Calculate emission time for a given detector (L1, t2)
/// and TOF when Emode==Elastic
double ModeratorTzero::CalculateT0elastic(const double &tof, const double &L12,
                                          double &E1, mu::Parser &parser) {
  double t0_curr, t0_next;
  t0_curr = m_tolTOF; // current iteration emission time
  t0_next = 0.0;      // next iteration emission time, initialized to zero
  size_t iiter(0);    // current iteration number
  // iterate until convergence in t0 reached
  while (std::fabs(t0_curr - t0_next) >= m_tolTOF && iiter < m_niter) {
    t0_curr = t0_next;
    double v1 = L12 / (tof - t0_curr); // v1 = v2 = v since emode is elastic
    E1 = m_convfactor * v1 * v1; // Energy in meV if v1 in meter/microsecond
    t0_next = parser.Eval();
    iiter++;
  }
  return t0_next;
}
Example #10
0
std::string ParserMgr::AnnotateErrMsg(const std::string& err_mesg, const mu::Parser& parser) const
{
#ifdef DEBUG_PM_FUNC
    ScopeTracker st("ParserMgr::AnnotateErrMsg", std::this_thread::get_id());
#endif
    const char* pos_str = "position ";
    size_t pos = err_mesg.find(pos_str);
    if (pos!=std::string::npos)
    {
        size_t spc = err_mesg.find_first_of(' ', pos);
        std::string s = err_mesg.substr(spc);
        int errpos = std::stoi(s);
        std::string pstr = parser.GetExpr();
        std::string small = "..." + pstr.substr(errpos, 20) + "...";
        return err_mesg + "  " + small;
    }
    return err_mesg;
}
Example #11
0
int Network3::run_PLA(double& time, double maxTime, double sampleTime,
					  double& step, double maxStep, double stepInterval,
					  mu::Parser& stop_condition, bool print_on_stop,
					  char* prefix,
					  bool print_cdat, bool print_func, bool print_save_net, bool print_end_net,
					  bool additional_pla_output,
					  bool verbose){

	// Output files
	string outpre(prefix);
	bool print_classif = additional_pla_output;
	// ...

	// Species file (must exist)
	FILE* cdat = NULL;
	string cFile = outpre + ".cdat";
	if ((cdat = fopen(cFile.c_str(),"r"))){
		fclose(cdat);
		cdat = fopen(cFile.c_str(),"a");
	}
	else {
		cout << "Error in Network3::run_PLA(): Concentrations file \"" << cFile << "\" doesn't exist. Exiting." << endl;
		exit(1);
	}

	// Observables file (optional)
	FILE* gdat = NULL;
	string gFile = outpre + ".gdat";
	if ((gdat = fopen(gFile.c_str(),"r"))){
		fclose(gdat);
		gdat = fopen(gFile.c_str(),"a");
	}
	else{
//		cout << "Warning: Groups file \"" << gFile << "\" doesn't exist." << endl;
	}

	// Functions file (optional)
/*	FILE* fdat = NULL;
	string fFile = outpre + ".fdat";
	if ((fdat = fopen(fFile.c_str(),"r"))){
		fclose(fdat);
		fdat = fopen(fFile.c_str(),"a");
	}
	else{
//		cout << "Warning: Functions file \"" << fFile << "\" doesn't exist." << endl;
	}*/

	// PLA-specific output files
	FILE* classif = NULL;
	if (print_classif){
		if ((classif = fopen((outpre+"_classif.pla").c_str(),"r"))){
			fclose(classif);
			classif = fopen((outpre+"_classif.pla").c_str(),"a");
		}
		else{
			cout << "Error in Network3::run_PLA(): 'print_classif' flag set but classifications file \""
				 << (outpre+"_classif.pla") << "\" doesn't exist. Exiting." << endl;
			exit(1);
		}
	}
	// ...

	// Identify observables involved in functions
	vector<unsigned int> funcObs;
	for (unsigned int i=0;i < FUNCTION.size();i++){
		map<string,double*> var = FUNCTION[i]->first->p->GetUsedVar();
		for (unsigned int j=0;j < OBSERVABLE.size();j++){
			if (var.find(OBSERVABLE[j]->first->name) != var.end()){
				bool already = false;
				for (unsigned int k=0;k < funcObs.size() && !already;k++){
					if (funcObs[k] == j){
						already = true;
					}
				}
				if (!already){ // add to the list
					funcObs.push_back(j);
				}
			}
		}
	}

	// Prepare for simulation
	double nextOutputTime = time + sampleTime;
	double nextOutputStep = stepInterval;
	while (nextOutputStep <= step) nextOutputStep += stepInterval;
	bool lastOut = true;

	// Simulation loop
//	PLA_SIM->rc.forceClassifications(RxnClassifier::EXACT_STOCHASTIC);
	string print_net_message;
	while (time < maxTime && step < maxStep && !stop_condition.Eval())
	{
		// Next step
		step++;
		PLA_SIM->nextStep();

		if (PLA_SIM->tau < INFINITY && PLA_SIM->tau > -INFINITY){
			time += PLA_SIM->tau;
		}
		else break;

		// Error check
		if (PLA_SIM->tau <= 0.0){
			cout << "Error in Network3::run_PLA(): tau = " << PLA_SIM->tau << ". Shouldn't happen. Exiting." << endl;
			exit(1);
		}

		// Is it time to output?
		lastOut = false;
		if (time >= nextOutputTime || step >= nextOutputStep) // YES
		{
			// Update all observables
			for (unsigned int i=0;i < OBSERVABLE.size();i++){
				OBSERVABLE[i]->second = OBSERVABLE[i]->first->getValue();
			}
			// Update all functions
			for (unsigned int i=0;i < FUNCTION.size();i++){
				FUNCTION[i]->second = FUNCTION[i]->first->Eval();
			}
			// Output to file
			if (print_cdat) Network3::print_species_concentrations(cdat,time);
			if (gdat) Network3::print_observable_concentrations(gdat,time,print_func);
			if (print_func) Network3::print_function_values(gdat,time);
			if (print_save_net){ // Write current system state to .net file
				// Collect species populations and update network concentrations vector
				double* pops = new double[SPECIES.size()];
				for (unsigned int j=0;j < SPECIES.size();j++){
					pops[j] = SPECIES[j]->population;
				}
				set_conc_network(pops);
				delete pops;
				// Print network w/ current species populations using network::print_network()
				char buf[1000];
				sprintf(buf, "%s_save.net", prefix);
				FILE* out = fopen(buf, "w");
				print_network(out);
				fclose(out);
				print_net_message = " Wrote NET file to " + (string)buf;
//				fprintf(stdout, " Wrote NET file to %s", buf);
			}
			if (print_classif){
				fprintf(classif,"%19.12e",time);
				fprintf(classif," %19.19g",step);
				for (unsigned int v=0;v < PLA_SIM->classif.size();v++){
					fprintf(classif, " %10d", PLA_SIM->classif[v]);
				}
				fprintf(classif,"\n");
				fflush(classif);
			}
			// Output to stdout
			if (verbose){
				cout << "\t" << fixed << setprecision(6) << time << "\t" << setprecision(0) << step;
//				for (unsigned int i=0;i < OBSERVABLE.size();i++){
//					cout << "\t" << OBSERVABLE[i]->second;
//				}
				if (print_save_net){
					fprintf(stdout, "%s", print_net_message.c_str());
				}
				cout << endl;
			}
			// Get next output time and step
			if (time >= nextOutputTime) nextOutputTime += sampleTime;
			if (step >= nextOutputStep) nextOutputStep += stepInterval;
			lastOut = true;
		}
		else{ // NO
			// Only update observables that are involved in functions
			for (unsigned int i=0;i < funcObs.size();i++){
				OBSERVABLE[funcObs[i]]->second = OBSERVABLE[funcObs[i]]->first->getValue();
			}
			// Update all functions
			for (unsigned int i=0;i < FUNCTION.size();i++){
				FUNCTION[i]->second = FUNCTION[i]->first->Eval();
			}
		}
	}

	// Final output
	if (!lastOut)
	{
		// Update all observables
		for (unsigned int i=0;i < OBSERVABLE.size();i++){
			OBSERVABLE[i]->second = OBSERVABLE[i]->first->getValue();
		}
		// Update all functions
		for (unsigned int i=0;i < FUNCTION.size();i++){
			FUNCTION[i]->second = FUNCTION[i]->first->Eval();
		}
		// Output to file
		if (print_cdat) Network3::print_species_concentrations(cdat,time);
		// Don't print if stopping condition met and !print_on_stop (must print to CDAT)
		if (!(stop_condition.Eval() && !print_on_stop)){
			if (gdat) Network3::print_observable_concentrations(gdat,time,print_func);
			if (print_func) Network3::print_function_values(gdat,time);
			string print_net_message;
			if (print_save_net){ // Write current system state to .net file
				// Collect species populations and update network concentrations vector
				double pops[SPECIES.size()];
				for (unsigned int j=0;j < SPECIES.size();j++){
					pops[j] = SPECIES[j]->population;
				}
				set_conc_network(pops);
				// Print network w/ current species populations using network::print_network()
				char buf[1000];
				sprintf(buf, "%s_save.net", prefix);
				FILE* out = fopen(buf, "w");
				print_network(out);
				fclose(out);
				print_net_message = " Wrote NET file to " + (string)buf;
			}
			if (print_classif){
				fprintf(classif,"%19.12e",time);
				for (unsigned int v=0;v < PLA_SIM->classif.size();v++){
					fprintf(classif, " %10d", PLA_SIM->classif[v]);
				}
				fprintf(classif,"\n");
				fflush(classif);
			}
		}
		// Output to stdout
		if (verbose){
			cout << "\t" << fixed << setprecision(6) << time << "\t" << setprecision(0) << step;
//			for (unsigned int i=0;i < OBSERVABLE.size();i++) cout << "\t" << OBSERVABLE[i]->second;
			if (print_save_net) fprintf(stdout, "%s", print_net_message.c_str());
			cout << endl;
		}
	}

	// Messages if stopping conditions met
	if (stop_condition.Eval()){ // Stop condition satisfied
		cout << "Stopping condition " << stop_condition.GetExpr() << "met in PLA simulation." << endl;
	}
//	else if (step >= startStep + maxSteps){ // maxSteps limit reached
//		cout << "Maximum step limit (" << maxSteps << ") reached in PLA simulation." << endl;
//	}

	// If print_end_net = true, collect species populations and update network concentrations vector
	if (print_end_net){
		double pops[SPECIES.size()];
		for (unsigned int j=0;j < SPECIES.size();j++){
			pops[j] = SPECIES[j]->population;
		}
		set_conc_network(pops);
	}

	// Close files
	fclose(cdat);
	if (gdat) fclose(gdat);
//	if (fdat) fclose(fdat);
	if (classif) fclose(classif);

	// Return value
	if (time >= maxTime) return 0;
	else if (step >= maxStep) return -1;
	else return -2; // stop condition met
}
Example #12
0
	bool operator()( double &vox, const isis::util::vector4<size_t>& pos ) {
		voxBuff = vox; //using parser.DefineVar every time would slow down the evaluation
		posBuff = pos;
		vox = parser.Eval();
		return true;
	}