コード例 #1
0
ファイル: guiPrimitive.cpp プロジェクト: Drahm/virtualflowlab
void Primitive::calculateFunctionDefPointCoor()
{
   float x, y, dx, x1, y1, x2, y2;

   FunctionParser fparser;   // Function parser object
   double funcVals[1];

   // Setup first and last point of the curve
   defPointCoor[0] = enteredPointCoor[0];
   defPointCoor[1] = enteredPointCoor[1];
   defPointCoor[2*(nDefPoints-1)] = enteredPointCoor[2];
   defPointCoor[2*(nDefPoints-1)+1] = enteredPointCoor[3];
   
   // Define some shotcuts
   x1 = enteredPointCoor[0];   // First point of the curve
   y1 = enteredPointCoor[1];
   x2 = enteredPointCoor[2];   // Last point of the curve
   y2 = enteredPointCoor[3];

   dx = (x2-x1)/(FUNCTION_DEF_POINTS-1);

   // Generate the points that will define the curve
   for (int j = 1; j < nDefPoints - 1; j++) {
      x = x1 + j*dx;
      funcVals[0] = x;
      fparser.Parse(function, "x");
      y = fparser.Eval(funcVals);

      defPointCoor[2*j] = x;
      defPointCoor[2*j+1] = y;
   }
}  // End of function calculateFunctionDefPointCoor()
コード例 #2
0
///Parse a line
void ribi::gtst::ParametersGroupAssign::Parse(const std::string& s)
{
  if (s.size() > 19 && s.substr(0,19) == "message_unassigned=")
  {
    const std::string t = s.substr(19,s.size()-19);
    SetMessageUnassigned(t);
    return;
  }
  else if (s.size() > 17 && s.substr(0,17) == "message_assigned=")
  {
    const std::string t = s.substr(17,s.size()-17);
    SetMessageAssigned(t);
    return;
  }
  else if (s.size() > 24 && s.substr(0,24) == "waiting_payoff_function=")
  {
    static_assert(sizeof("waiting_payoff_function=") == 24 + 1,"Assume size 24");
    const std::string t = s.substr(24,s.size()-24);
    FunctionParser f;
    //Parse the formula
    f.Parse(t,"p");
    if (f.GetParseErrorType()!= FunctionParser::FP_NO_ERROR)
    {
      throw std::runtime_error("group_assign_waiting_payoff_function could not be parsed, use for example \'sqrt(p)+10\'");
    }
    SetWaitingPayoffFunction(t);
    return;
  }

  throw std::runtime_error(
    (std::string("Unparsable parameter file line: group_assign_") + s).c_str());

}
コード例 #3
0
double ribi::gtst::ParametersGroupAssign::CalculateWaitingPayoff(const double average_payoff) const
{
  FunctionParser f;
  //Parse the formula
  f.Parse(m_waiting_payoff_function,"p");
  assert(f.GetParseErrorType()== FunctionParser::FP_NO_ERROR);

  //Evaluate the parsed formula
  const double payoffs[1] = { average_payoff };
  const double payoff_waiting = f.Eval(payoffs);

  if (f.EvalError()!=0)
  {
    std::clog
      << "Function \'"
      << m_waiting_payoff_function
      << "\'could not be evaluated"
      << " for an average payoff of "
      << average_payoff
      << '\n';
    return 0.0;
  }

  return payoff_waiting;
}
コード例 #4
0
void ribi::gtst::ParametersGroupReAssign::SetNextPeriodPayoffFunction(const std::string& function)
{
  FunctionParser f;
  //Parse the formula
  f.Parse(function,"p");
  if (f.GetParseErrorType()!= FunctionParser::FP_NO_ERROR)
  {
    throw std::runtime_error("finished_earnings_function could not be parsed, use for example \'sqrt(p)+10\'");
  }
  m_next_period_payoff_function = function;
}
コード例 #5
0
///Parse a line
void ribi::gtst::ParametersGroupReAssign::Parse(const std::string& s)
{
  if (s.size() > 9 && s.substr(0,9) == "duration=")
  {
    const std::string t = s.substr(9,s.size()-9);
    try
    {
      std::stoi(t);
    }
    catch (std::exception&)
    {
      throw std::runtime_error("group_reassign_duration must be an integer");
    }
    const int time = std::stoi(t);
    if (time < 0) throw std::runtime_error("group_reassign_duration must be zero or posive");
    SetDuration(time);
    return;
  }
  else if (s.size() > 18 && s.substr(0,18) == "number_of_periods=")
  {
    const std::string t = s.substr(18,s.size()-18);
    try
    {
      std::stoi(t);
    }
    catch (std::exception&)
    {
      throw std::runtime_error("group_reassign_number_of_periods must be an integer");
    }
    const int n_periods = std::stoi(t);
    if (n_periods < 0) throw std::runtime_error("group_reassign_number_of_periods must be zero or posive");
    SetNumberOfPeriods(n_periods);
    return;
  }
  else if (s.size() > 28 && s.substr(0,28) == "next_period_payoff_function=")
  {
    static_assert(sizeof("next_period_payoff_function=") == 28 + 1,"Assume size 28");
    const std::string t = s.substr(28,s.size()-28);
    FunctionParser f;
    //Parse the formula
    f.Parse(t,"p");
    if (f.GetParseErrorType()!= FunctionParser::FP_NO_ERROR)
    {
      throw std::runtime_error("group_reassign_next_period_payoff_function could not be parsed, use for example \'sqrt(p)+10\'");
    }
    SetNextPeriodPayoffFunction(t);
    return;
  }

  throw std::runtime_error(
    (std::string("Unparsable parameter file line: group_reassign_") + s).c_str());

}
コード例 #6
0
QtDialog::QtDialog(QWidget *parent) :
  QDialog(parent),
  ui(new Ui::QtDialog),
  m_curve(new QwtPlotCurve("Sine")),
  m_plot(new QwtPlot(QwtText("CppQwtExample1")))
{
  ui->setupUi(this);

  assert(!this->layout());
  QLayout * const my_layout = new QVBoxLayout;
  this->setLayout(my_layout);

  #ifndef NDEBUG
  my_layout->addWidget(new QLabel("DEBUG"));
  #else
  my_layout->addWidget(new QLabel("RELEASE"));
  #endif

  my_layout->addWidget(new QLabel( ("GCC version: " + GetGccVersion()).c_str()));
  //my_layout->addWidget(new QLabel( ("Qt Creator version: " + GetQtCreatorVersion()).c_str()));
  my_layout->addWidget(new QLabel( ("STL version: " + GetStlVersion()).c_str()));
  my_layout->addWidget(new QLabel( ("Boost version: " + GetBoostVersion()).c_str()));


  {
    FunctionParser f;
    f.Parse("x * x","x");
    assert(f.GetParseErrorType()== FunctionParser::FP_NO_ERROR);
    const double xs[1] = { M_PI };
    const double y = f.Eval(xs);
    assert(f.EvalError()==0);
    my_layout->addWidget(new QLabel("Warp's function parser version: 4.5.1"));
  }
  {
    m_plot->setGeometry(0,0,640,400);
    m_plot->setAxisScale(QwtPlot::xBottom, 0.0,2.0 * M_PI);
    m_plot->setAxisScale(QwtPlot::yLeft,-1.0,1.0);
    std::vector<double> xs;
    std::vector<double> ys;
    for (double x = 0; x < 2.0 * M_PI; x+=(M_PI / 10.0))
    {
      xs.push_back(x);
      ys.push_back(std::sin(x));
    }
    QwtPointArrayData * const data = new QwtPointArrayData(&xs[0],&ys[0],xs.size());
    m_curve->setData(data);
    m_curve->attach(m_plot);
    m_plot->replot();
    my_layout->addWidget(m_plot);
  }
}
コード例 #7
0
ファイル: excitation.cpp プロジェクト: keirstitt/openEMS
void Excitation::CalcCustomExcitation(double f0, int nTS, string signal)
{
	if (dT==0) return;
	if (nTS<=0) return;

	Length = (unsigned int)(nTS);
//	cerr << "Operator::CalcSinusExcitation: Length of the excite signal: " << ExciteLength << " timesteps" << endl;
	delete[] Signal_volt;
	delete[] Signal_curr;
	Signal_volt = new FDTD_FLOAT[Length+1];
	Signal_curr = new FDTD_FLOAT[Length+1];
	Signal_volt[0]=0.0;
	Signal_curr[0]=0.0;
	FunctionParser fParse;
	fParse.AddConstant("pi", 3.14159265358979323846);
	fParse.AddConstant("e", 2.71828182845904523536);
	fParse.Parse(signal,"t");
	if (fParse.GetParseErrorType()!=FunctionParser::FP_NO_ERROR)
	{
		cerr << "Operator::CalcCustomExcitation: Function Parser error: " << fParse.ErrorMsg() << endl;
		exit(1);
	}
	double vars[1];
	for (unsigned int n=1; n<Length+1; ++n)
	{
		vars[0] = (n-1)*dT;
		Signal_volt[n] = fParse.Eval(vars);
		vars[0] += 0.5*dT;
		Signal_curr[n] = fParse.Eval(vars);
	}

	m_f_max = f0;
	m_foi = f0;
	SetNyquistNum( CalcNyquistNum(f0,dT) );
}
コード例 #8
0
bool FunctionParsersManager::parse(std::vector<foundInfo> & foundInfos, generic_string ext)
{
	if (!_pXmlFuncListDoc)
		return false;

	// Serch the right parser from the given ext in the map
	FunctionParser *fp = getParser(ext);
	if (!fp)
		return false;

	// parse
	int docLen = (*_ppEditView)->getCurrentDocLen();
	fp->parse(foundInfos, 0, docLen, _ppEditView);

	return true;
}
コード例 #9
0
ribi::FunctionPlotterMainDialog::FunctionPlotterMainDialog(
  const std::string& formula,
  const double x_min,
  const double x_max,
  const int n_cols
) : m_x(std::vector<double>(n_cols,0.0)),
    m_y(std::vector<double>(n_cols,0.0))
{
  #ifndef NDEBUG
  assert(Rescale(2.0,1.0,5.0,0.0,100.0) >= 24.9999 && Rescale(2.0,1.0,5.0,0.0,100.0) < 25.0001);
  #endif

  FunctionParser f;

  f.Parse(formula,"x");
  if (f.GetParseErrorType()!= FunctionParser::FP_NO_ERROR)
  {
    throw std::runtime_error("Function cannot not be parsed");
  }

  if (x_min >= x_max)
  {
    throw std::runtime_error("Value of x_min must be smaller than x_max");
  }

  //Evaluate the function in a 2D std::vector
  const double n_cols_d = static_cast<double>(n_cols);

  for (int x = 0; x!=n_cols; ++x)
  {
    const double xD = static_cast<double>(x);
    const double x_scaled = Rescale(xD,0.0,n_cols_d,x_min,x_max);
    const double xs[1] = { x_scaled };
    const double y = f.Eval(xs);
    if (!f.EvalError())
    {
      m_y[x] = y;
    }
    else
    {
      m_y[x] = 0.0;
    }
    m_x[x] = x_scaled;
  }

}
コード例 #10
0
ファイル: glui_tf_gen.cpp プロジェクト: marvis/volume_render
//_____________________________________________________________________________
//
void tf_set_formula()
//-----------------------------------------------------------------------------
{
  // Parse transfer function formula
  if( tf_fun_formula[0] == '\0' ) return ;
  FunctionParser fparser ;
  int res = fparser.Parse( (const char*)tf_fun_formula, "x" ) ;
  if( fparser.GetParseErrorType() != FunctionParser::NO_SYNTAX_ERROR )
  {
    printf( "transfer formula error: %s\n\t%s\n\t% *d\n", fparser.ErrorMsg(), tf_fun_formula, res, 1 ) ;
    return ;
  }


  // Retreives the color map
  if( tf_colmap < 0 || tf_colmap >= CMAP_NB ) return ;
  const float *colmap = cmaps[tf_colmap] ;

  // allocate the transfer function
  int tf_size = tf_sym ? 512 : 256 ;
  vsvr.tf_set_intern() ;
  vsvr.tf_set_size( tf_size ) ;
  vsvr.tf_alloc() ;

  // fills the texture
  float  x = 0.0f ;
  float dx = 1.0f / (tf_size-1) ;
  for( int i = 0 ; i < tf_size ; ++i, x += dx )
  {
    int k = i ;
    // symmetric
    if( i > 255 ) k = 511 - i ;
    // inverse
    if( tf_inv ) k = 255 - k ;
    const float *col = colmap + 3*k ;

    float a = fparser.Eval( &x ) ;
    if( a < 0.0f ) a = 0.0f ;
    if( a > 1.0f ) a = 1.0f ;

    vsvr.tf_set( i, col[0], col[1], col[2], a*opacity ) ;
  }

  force_reload = true ;
}
コード例 #11
0
//-------------------------------------------------------------------------------------------------
double BenchFParser::DoBenchmark(const std::string& sExpr, long iCount)
{
   double fRes (0);
   double fSum (0);

   FunctionParser Parser;
   Parser.AddConstant("pi", (double)M_PI);
   Parser.AddConstant("e", (double)M_E);

   if (Parser.Parse(sExpr.c_str(), "a,b,c,x,y,z,w") >= 0)
   {
      StopTimerAndReport(Parser.ErrorMsg());
      return m_fTime1;
   }
   else
   {
      double vals[] = {
                        1.1,
                        2.2,
                        3.3,
                        2.123456,
                        3.123456,
                        4.123456,
                        5.123456
                      };

      fRes = Parser.Eval(vals);

      StartTimer();

      for (int j = 0; j < iCount; ++j)
      {
         fSum += Parser.Eval(vals);
         std::swap(vals[0], vals[1]);
         std::swap(vals[3], vals[4]);
      }

      StopTimer(fRes, fSum, iCount);
   }

   return m_fTime1;
}
コード例 #12
0
void EigenvalueProblem<dim>::assemble_system()
{
    QGauss<dim> quadrature_formula(2);

    FEValues<dim> fe_values(fe, quadrature_formula,
                            update_values | update_gradients |
                            update_quadrature_points | update_JxW_values);

    const size_t dofs_per_cell = fe.dofs_per_cell;
    const size_t n_q_points = quadrature_formula.size();

    FullMatrix<double> cell_stiffness_matrix (dofs_per_cell, dofs_per_cell);
    FullMatrix<double> cell_mass_matrix (dofs_per_cell, dofs_per_cell);

    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);

    FunctionParser<dim> potential;
    potential.initialize(FunctionParser<dim>::default_variable_names(),
                         parameters.get("Potential"),
                         typename FunctionParser<dim>::ConstMap());

    std::vector<double> potential_values(n_q_points);

    for (auto cell : dof_handler.active_cell_iterators()) {
        fe_values.reinit(cell);

        cell_stiffness_matrix = 0;
        cell_mass_matrix = 0;

        potential.value_list(fe_values.get_quadrature_points(),
                             potential_values);
        for (size_t q_point = 0; q_point < n_q_points; ++q_point) {
            for (size_t i = 0; i < dofs_per_cell; ++i) {
                for (size_t j = 0; j < dofs_per_cell; ++j) {
                    cell_stiffness_matrix(i, j) += (fe_values.shape_grad(i, q_point) *
                                                    fe_values.shape_grad(j, q_point)
                                                    +
                                                    potential_values[q_point] *
                                                    fe_values.shape_value(i, q_point) *
                                                    fe_values.shape_value(j, q_point)
                                                   ) * fe_values.JxW(q_point);
                    cell_mass_matrix(i, j) += (fe_values.shape_value(i, q_point) *
                                               fe_values.shape_value(j, q_point)
                                              ) * fe_values.JxW(q_point);
                }
            }
        }

        cell->get_dof_indices(local_dof_indices);

        constraints.distribute_local_to_global(cell_stiffness_matrix,
                                               local_dof_indices,
                                               stiffness_matrix);
        constraints.distribute_local_to_global(cell_mass_matrix,
                                               local_dof_indices,
                                               mass_matrix);
    }

    stiffness_matrix.compress(VectorOperation::add);
    mass_matrix.compress(VectorOperation::add);


    double min_spurious_eigenvalue = std::numeric_limits<double>::max(),
           max_spurious_eigenvalue = -std::numeric_limits<double>::max();
    for (size_t i = 0; i < dof_handler.n_dofs(); ++i) {
        if (constraints.is_constrained(i)) {
            const double ev = stiffness_matrix(i, i) / mass_matrix(i, i);
            min_spurious_eigenvalue = std::min (min_spurious_eigenvalue, ev);
            max_spurious_eigenvalue = std::max (max_spurious_eigenvalue, ev);
        }
    }
    std::cout << "   Spurious eigenvalues are all in the interval "
              << "[" << min_spurious_eigenvalue << "," << max_spurious_eigenvalue << "]"
              << std::endl;
}
コード例 #13
0
ファイル: GraphOption.cpp プロジェクト: BijanZarif/coolfluid3
void  GraphOption::generate_function(QString name,QString formula){

  m_button_generate_function->setEnabled(false);


  //ferification of name and formula input
  if(name.isEmpty() || formula.isEmpty()){
    core::NLog::global()->add_error("Please give function's name and formula.");
    m_button_generate_function->setEnabled(true);
    return;
  }

  //check if the function name already exist
  for(int i=0; i < m_data_table->rowCount(); ++i){
    if((((QLabel *)m_data_table->cellWidget(i,0))->text()) == name){
      core::NLog::global()->add_error("The function name already exist.");
      m_button_generate_function->setEnabled(true);
      return;
    }
  }

  FunctionParser fparser;

  //get all fct name separated by ','
  QString variable = "";
  for(int i=1; i < m_data_table->rowCount(); ++i){
    if(!(((QLabel *)m_data_table->cellWidget(i,0))->text()).isEmpty()){
      if(!variable.isEmpty()){
        variable += ",";
      }
      variable.append(((QLabel *)m_data_table->cellWidget(i,0))->text());
    }
  }

  //parsing function
  int res = fparser.Parse(formula.toStdString().c_str(),
                          variable.toStdString().c_str());

  if(res > 0){
    core::NLog::global()->add_error("The function is not recognized.");
    m_button_generate_function->setEnabled(true);
    return;
  }

  //<to remove>
  int max_it = 0;
  if(m_data_table->rowCount()>0)
  {
    max_it = m_fcts->size();
  }else{
    core::NLog::global()->add_error("The function is not recognized.");
    m_button_generate_function->setEnabled(true);
    return;
  }
  //</to remove>

  //generate the new function's data
  std::vector<double> vector_temp(max_it);

  double vals[m_data_table->rowCount()-1];
  for(int i=0;i<max_it;++i)
  {
    for(int j=0;j<m_data_table->rowCount()-1;++j)
    {
      vals[j] = (*m_fcts)[i][j+1];
    }
    vector_temp[i] = fparser.Eval(vals);
  }

  //add the new function
  this->add_data(vector_temp,name,formula);

  //get back the button and clear the name and function line
  m_button_generate_function->setEnabled(true);
  m_line_function->clear();
  m_line_function_name->clear();

}
コード例 #14
0
//-------------------------------------------------------------------------------------------------
double BenchFParser::DoBenchmark(const std::string& sExpr, long iCount)
{
   double fRes = 0.0;
   double fSum = 0.0;

   FunctionParser Parser;
   Parser.AddConstant("pi", (double)M_PI);
   Parser.AddConstant("e", (double)M_E);

   if (Parser.Parse(sExpr.c_str(), "a,b,c,x,y,z,w") >= 0)
   {
      StopTimerAndReport(Parser.ErrorMsg());
      return m_fTime1;
   }
   else
   {
      double vals[] = {
                        1.1,
                        2.2,
                        3.3,
                        2.123456,
                        3.123456,
                        4.123456,
                        5.123456
                      };

      //Prime the I and D caches for the expression
      {
         double d0 = 0.0;
         double d1 = 0.0;

         for (std::size_t i = 0; i < priming_rounds; ++i)
         {
            if (i & 1)
               d0 += Parser.Eval(vals);
            else
               d1 += Parser.Eval(vals);
         }

         if (
               (d0 == std::numeric_limits<double>::infinity()) &&
               (d1 == std::numeric_limits<double>::infinity())
            )
         {
            printf("\n");
         }
      }

      fRes = Parser.Eval(vals);

      StartTimer();

      for (int j = 0; j < iCount; ++j)
      {
         fSum += Parser.Eval(vals);
         std::swap(vals[0], vals[1]);
         std::swap(vals[3], vals[4]);
      }

      StopTimer(fRes, fSum, iCount);
   }

   return m_fTime1;
}
コード例 #15
0
double ScrSpinBox::valueFromText ( const QString & text ) const
{
	//Get all our units strings
//CB: Replaced by new CommonStrings versions
// 	QString trStrPT=unitGetStrFromIndex(SC_PT);
// 	QString trStrMM=unitGetStrFromIndex(SC_MM);
// 	QString trStrIN=unitGetStrFromIndex(SC_IN);
// 	QString trStrP =unitGetStrFromIndex(SC_P);
// 	QString trStrCM=unitGetStrFromIndex(SC_CM);
// 	QString trStrC =unitGetStrFromIndex(SC_C);
// 	QString strPT=unitGetUntranslatedStrFromIndex(SC_PT);
// 	QString strMM=unitGetUntranslatedStrFromIndex(SC_MM);
// 	QString strIN=unitGetUntranslatedStrFromIndex(SC_IN);
// 	QString strP =unitGetUntranslatedStrFromIndex(SC_P);
// 	QString strCM=unitGetUntranslatedStrFromIndex(SC_CM);
// 	QString strC =unitGetUntranslatedStrFromIndex(SC_C);
	//Get a copy for use
	QString ts = text.trimmed();
	//Find our suffix
	QString su(unitGetStrFromIndex(m_unitIndex));
	//Replace our pica XpY.Z format with (X*12+Y.Z)pt
	if (CommonStrings::trStrP.localeAwareCompare(CommonStrings::strP)!=0)
		ts.replace(CommonStrings::trStrP, CommonStrings::strP);
	QRegExp rxP;
	if (m_unitIndex==SC_PICAS)
		rxP.setPattern("\\b(\\d+)"+CommonStrings::strP+"?(\\d+\\.?\\d*)?\\b");
	else
		rxP.setPattern("\\b(\\d+)"+CommonStrings::strP+"(\\d+\\.?\\d*)?\\b");
	int posP = 0;
	while (posP >= 0)
	{
// 		qDebug() << "#";
		posP = rxP.indexIn(ts, posP);
		if (posP >= 0)
		{
// 			qDebug() << rxP.cap(1);
// 			qDebug() << rxP.cap(2);
			QString replacement = QString("%1%2").arg(rxP.cap(1).toDouble()*(static_cast<double>(unitGetBaseFromIndex(SC_PICAS))) + rxP.cap(2).toDouble()).arg(CommonStrings::strPT);
			ts.replace(posP, rxP.cap(0).length(), replacement);
// 			qDebug() << ts;
		}
	}
// 	qDebug() << "##" << ts;
	
	ts.replace(",", ".");
	ts.replace("%", "");
	ts.replace("°", "");
	ts.replace(FinishTag, "");
	ts = ts.trimmed();

	if (ts.endsWith(su))
		ts = ts.left(ts.length()-su.length());
	int pos = ts.length();
	while (pos > 0)
	{
		pos = ts.lastIndexOf(".", pos);
		if (pos >= 0) 
		{
			if (pos < static_cast<int>(ts.length()))
			{
				if (!ts[pos+1].isDigit())
					ts.insert(pos+1, "0 ");
			}
			pos--;
		}
	}
	if (ts.endsWith("."))
		ts.append("0");
	//CB FParser doesn't handle unicode well/at all.
	//So, instead of just getting the translated strings and
	//sticking them in as variables in the parser, if they are
	//not the same as the untranslated version, then we replace them.
	//We lose the ability for now to have some strings in languages 
	//that might use them in variables.
	//To return to previous functionality, remove the follow replacement ifs,
	//S&R in the trStr* assignments trStrPT->strPT and remove the current str* ones. 
	//IE, send the translated strings through to the regexp.
	if (CommonStrings::trStrPT.localeAwareCompare(CommonStrings::strPT)!=0)
		ts.replace(CommonStrings::trStrPT, CommonStrings::strPT);
	if (CommonStrings::trStrMM.localeAwareCompare(CommonStrings::strMM)!=0)
		ts.replace(CommonStrings::trStrMM, CommonStrings::strMM);
	if (CommonStrings::trStrIN.localeAwareCompare(CommonStrings::strIN)!=0)
		ts.replace(CommonStrings::trStrIN, CommonStrings::strIN);
	if (CommonStrings::trStrCM.localeAwareCompare(CommonStrings::strCM)!=0)
		ts.replace(CommonStrings::trStrCM, CommonStrings::strCM);
	if (CommonStrings::trStrC.localeAwareCompare(CommonStrings::trStrC)!=0)
		ts.replace(CommonStrings::trStrC, CommonStrings::strC);
	//Replace in our typed text all of the units strings with *unitstring
	QRegExp rx("\\b(\\d+)\\s*("+CommonStrings::strPT+"|"+CommonStrings::strMM+"|"+CommonStrings::strC+"|"+CommonStrings::strCM+"|"+CommonStrings::strIN+")\\b");
	pos = 0;
	while (pos >= 0) {
		pos = rx.indexIn(ts, pos);
		if (pos >= 0) {
			QString replacement = rx.cap(1) + "*" + rx.cap(2);
			ts.replace(pos, rx.cap(0).length(), replacement);
		}
	}

	//Add in the fparser constants using our unit strings, and the conversion factors.
	FunctionParser fp;
// 	setFPConstants(fp);
	fp.AddConstant(CommonStrings::strPT.toStdString(), value2value(1.0, SC_PT, m_unitIndex));
	fp.AddConstant(CommonStrings::strMM.toStdString(), value2value(1.0, SC_MM, m_unitIndex));
	fp.AddConstant(CommonStrings::strIN.toStdString(), value2value(1.0, SC_IN, m_unitIndex));
	fp.AddConstant(CommonStrings::strP.toStdString(), value2value(1.0, SC_P, m_unitIndex));
	fp.AddConstant(CommonStrings::strCM.toStdString(), value2value(1.0, SC_CM, m_unitIndex));
	fp.AddConstant(CommonStrings::strC.toStdString(), value2value(1.0, SC_C, m_unitIndex));

	fp.AddConstant("old", value());
	if (m_constants)
	{
		QMap<QString, double>::ConstIterator itend = m_constants->constEnd();
		QMap<QString, double>::ConstIterator it = m_constants->constBegin();
		while(it != itend)
		{
			fp.AddConstant(it.key().toStdString(), it.value() * unitGetRatioFromIndex(m_unitIndex));
			++it;
		}
	}
	
	int ret = fp.Parse(ts.toStdString(), "", true);
//	qDebug() << "fp return =" << ret;
	if (ret >= 0)
		return 0;
	double erg = fp.Eval(NULL);
//	qDebug() << "fp value =" << erg;
	return erg;
}
コード例 #16
0
void ribi::QtToolSurfacePlotterMainDialog::OnAnyChange()
{
  try { boost::lexical_cast<double>(ui->edit_minx->text().toStdString()); }
  catch (boost::bad_lexical_cast&)
  {
    this->setWindowTitle("Value of x_min is not a valid double"); return;
  }
  try { boost::lexical_cast<double>(ui->edit_miny->text().toStdString()); }
  catch (boost::bad_lexical_cast&)
  {
    this->setWindowTitle("Value of y_min is not a valid double"); return;
  }
  try { boost::lexical_cast<double>(ui->edit_maxx->text().toStdString()); }
  catch (boost::bad_lexical_cast&)
  {
    this->setWindowTitle("Value of x_max is not a valid double"); return;
  }
  try { boost::lexical_cast<double>(ui->edit_maxy->text().toStdString()); }
  catch (boost::bad_lexical_cast&)
  {
    this->setWindowTitle("Value of y_max is not a valid double"); return;
  }

  FunctionParser f;

  //Parse the formula
  f.Parse(ui->edit_equation->text().toStdString().c_str(),"x,y");
  if (f.GetParseErrorType()!= FunctionParser::FP_NO_ERROR)
  {
    this->setWindowTitle("Function cannot not be parsed"); return;
  }


  const double x_min = boost::lexical_cast<double>(ui->edit_minx->text().toStdString());
  const double y_min = boost::lexical_cast<double>(ui->edit_miny->text().toStdString());
  const double x_max = boost::lexical_cast<double>(ui->edit_maxx->text().toStdString());
  const double y_max = boost::lexical_cast<double>(ui->edit_maxy->text().toStdString());

  if (x_min >= x_max)
  {
    this->setWindowTitle("Value of x_min must be smaller than x_max"); return;
  }

  if (y_min >= y_max)
  {
    this->setWindowTitle("Value of y_min must be smaller than y_max"); return;
  }

  //Evaluate the function in a 2D std::vector
  const int n_rows = ui->surfaceplotwidget->height();
  const int n_cols = ui->surfaceplotwidget->width();
  std::vector<std::vector<double> > v(n_rows,std::vector<double>(n_cols,0.0));
  const double n_rows_d = static_cast<double>(n_rows);
  const double n_cols_d = static_cast<double>(n_cols);

  for (int y = 0; y!=n_rows; ++y)
  {
    const double yD = static_cast<double>(y);
    const double y_scaled = Rescale(yD,0.0,n_rows_d,y_min,y_max);
    for (int x = 0; x!=n_cols; ++x)
    {
      const double xD = static_cast<double>(x);
      const double x_scaled = Rescale(xD,0.0,n_cols_d,x_min,x_max);
      const double xs[2] = { x_scaled,y_scaled };
      const double z = f.Eval(xs);
      if (!f.EvalError())
      {
        v[y][x] = z;
      }
      else
      {
        v[y][x] = 0.0;
      }
    }
  }

  this->setWindowTitle("Function plotted successfully");

  //Plot the 2D std::vector
  ui->surfaceplotwidget->SetSurfaceGrey(v);
}
コード例 #17
0
ファイル: GLDriver.cpp プロジェクト: jrco/nau
bool GLDriver::Init()
{

  //Read in the configuration data
  defaultConfigData.ReadConfigData(); //Read basic config
  configData = defaultConfigData;
  setConfigDataExport(&configData, this);

  //Set if the logger mirrors to the debugger
  //if(gliLog)
  //{
  //  gliLog->SetDebuggerLogEnabled(configData.errorDebuggerErrorLog);
  //}

  //Attempt to open the driver
  if(!openGLLib.Init(configData.openGLFileName.c_str()))
  {
    LOGERR(("GLDriver::Init - Unable to open OpenGL lib file %s",configData.openGLFileName.c_str())); 
    return false;
  }

#ifdef GLI_BUILD_WINDOWS

  //Check that we have not loaded our own DLL (Windows can sometimes force this)
  if(openGLLib.IsDLLHandleMatch(dllHandle))
  {
    LOGERR(("GLDriver::Init - OpenGL lib file points to GLIntercept lib - using <appname>.exe.local file?")); 
    return false;
  }

#endif //GLI_BUILD_WINDOWS

  //Do the core OpenGL function mapping
  if(!MapCoreOpenGLFunctions(openGLLib) || !MapWGLFunctions(openGLLib))
  {
    LOGERR(("GLDriver::Init - Unable to map core/windows OpenGL functions")); 
    return false;
  }

  //Create the function table if necessary
  if(!functionTable)
  { 
    InitFunctionTable();
  }


  //Create the extension function handler
  extensionFunction = new ExtensionFunction(functionTable);

  //Parse the include files
  FunctionParser    parser;
  FunctionDataArray tmpFuncArray;
  EnumDataArray     tmpEnumArray;

  //If parsing was successful, get the known function table data
  if(parser.Parse(configData.functionDataFileName.c_str()))
  {
    //Get the data from the parser (A double copy, slow -may need to speed up)
    parser.GetFunctionData(tmpFuncArray,tmpEnumArray);
  }

  //Init the function table with known data (even if there is no known data or parsing faild)
  functionTable->InitKnownFunctionTable(tmpFuncArray,tmpEnumArray);
  
  //Assign thread checking flag
  threadCheckingEnabled = configData.errorThreadChecking;

  //Assign the current logging directory
  //currLogDir = configData.logPath;

  //Set if the any logging is enabled
  loggingEnabled = !configData.logPerFrame;

  //If we are not-perframe logging, create the initial logger here
  if(loggingEnabled && configData.logEnabled)
  {
    //Init the initial function log
    if(!InitFunctionLog())
    {
      return false;
    }
  }

  //Create the error data log
  errorDataLog =  new InterceptLog(functionTable);

  //Register the rendering functions.
  functionTable->SetFunctionFlag("glEvalMesh1",FDF_RENDER_FUNC);
  functionTable->SetFunctionFlag("glEvalMesh2",FDF_RENDER_FUNC);
  functionTable->SetFunctionFlag("glRectd",FDF_RENDER_FUNC);
  functionTable->SetFunctionFlag("glRectf",FDF_RENDER_FUNC);
  functionTable->SetFunctionFlag("glRecti",FDF_RENDER_FUNC);
  functionTable->SetFunctionFlag("glRects",FDF_RENDER_FUNC);
  functionTable->SetFunctionFlag("glRectdv",FDF_RENDER_FUNC);
  functionTable->SetFunctionFlag("glRectfv",FDF_RENDER_FUNC);
  functionTable->SetFunctionFlag("glRectiv",FDF_RENDER_FUNC);
  functionTable->SetFunctionFlag("glRectsv",FDF_RENDER_FUNC);

  functionTable->SetFunctionFlag("glBegin",FDF_RENDER_FUNC);
  functionTable->SetFunctionFlag("glDrawPixels",FDF_RENDER_FUNC);
  functionTable->SetFunctionFlag("glDrawArrays",FDF_RENDER_FUNC);
  functionTable->SetFunctionFlag("glDrawArraysEXT",FDF_RENDER_FUNC);
  functionTable->SetFunctionFlag("glDrawElements",FDF_RENDER_FUNC);
  functionTable->SetFunctionFlag("glDrawRangeElements",FDF_RENDER_FUNC);
  functionTable->SetFunctionFlag("glDrawRangeElementsEXT",FDF_RENDER_FUNC);
  functionTable->SetFunctionFlag("glMultiDrawArrays",FDF_RENDER_FUNC);  
  functionTable->SetFunctionFlag("glMultiDrawArraysEXT",FDF_RENDER_FUNC);
  functionTable->SetFunctionFlag("glMultiDrawElements",FDF_RENDER_FUNC);
  functionTable->SetFunctionFlag("glMultiDrawElementsEXT",FDF_RENDER_FUNC);

  functionTable->SetFunctionFlag("glDrawArraysInstancedARB",FDF_RENDER_FUNC); 
  functionTable->SetFunctionFlag("glDrawElementsInstancedARB",FDF_RENDER_FUNC); 
  functionTable->SetFunctionFlag("glDrawArraysInstancedEXT",FDF_RENDER_FUNC); 
  functionTable->SetFunctionFlag("glDrawElementsInstancedEXT",FDF_RENDER_FUNC); 
  functionTable->SetFunctionFlag("glDrawArraysInstanced",FDF_RENDER_FUNC);
  functionTable->SetFunctionFlag("glDrawElementsInstanced",FDF_RENDER_FUNC); 

  functionTable->SetFunctionFlag("glDrawElementsBaseVertex",FDF_RENDER_FUNC); 
  functionTable->SetFunctionFlag("glDrawRangeElementsBaseVertex",FDF_RENDER_FUNC); 
  functionTable->SetFunctionFlag("glDrawElementsInstancedBaseVertex",FDF_RENDER_FUNC); 
  functionTable->SetFunctionFlag("glMultiDrawElementsBaseVertex",FDF_RENDER_FUNC); 

  functionTable->SetFunctionFlag("glDrawArraysIndirect",FDF_RENDER_FUNC); 
  functionTable->SetFunctionFlag("glDrawElementsIndirect",FDF_RENDER_FUNC); 
  functionTable->SetFunctionFlag("glDrawTransformFeedback",FDF_RENDER_FUNC); 
  functionTable->SetFunctionFlag("glDrawTransformFeedbackStream",FDF_RENDER_FUNC); 

  functionTable->SetFunctionFlag("glDrawArraysInstancedBaseInstance",FDF_RENDER_FUNC); 
  functionTable->SetFunctionFlag("glDrawElementsInstancedBaseInstance",FDF_RENDER_FUNC); 
  functionTable->SetFunctionFlag("glDrawElementsInstancedBaseVertexBaseInstance",FDF_RENDER_FUNC); 
  functionTable->SetFunctionFlag("glDrawTransformFeedbackInstanced",FDF_RENDER_FUNC); 
  functionTable->SetFunctionFlag("glDrawTransformFeedbackStreamInstanced",FDF_RENDER_FUNC); 

  functionTable->SetFunctionFlag("glMultiDrawArraysIndirect",FDF_RENDER_FUNC); 
  functionTable->SetFunctionFlag("glMultiDrawElementsIndirect",FDF_RENDER_FUNC);

  functionTable->SetFunctionFlag("glMultiDrawArraysIndirectCountARB",FDF_RENDER_FUNC);
  functionTable->SetFunctionFlag("glMultiDrawElementsIndirectCountARB",FDF_RENDER_FUNC);

  functionTable->SetFunctionFlag("glDrawArraysInstancedNV",FDF_RENDER_FUNC);
  functionTable->SetFunctionFlag("glDrawElementsInstancedNV",FDF_RENDER_FUNC);
  functionTable->SetFunctionFlag("glDrawTransformFeedbackNV",FDF_RENDER_FUNC);
  functionTable->SetFunctionFlag("glMultiDrawArraysIndirectBindlessNV",FDF_RENDER_FUNC);
  functionTable->SetFunctionFlag("glMultiDrawElementsIndirectBindlessNV",FDF_RENDER_FUNC);

  functionTable->SetFunctionFlag("glMultiDrawArraysIndirectAMD",FDF_RENDER_FUNC); 
  functionTable->SetFunctionFlag("glMultiDrawElementsIndirectAMD",FDF_RENDER_FUNC); 

  functionTable->SetFunctionFlag("glDrawElementArrayAPPLE",FDF_RENDER_FUNC); 
  functionTable->SetFunctionFlag("glDrawRangeElementArrayAPPLE",FDF_RENDER_FUNC); 
  functionTable->SetFunctionFlag("glMultiDrawElementArrayAPPLE",FDF_RENDER_FUNC); 
  functionTable->SetFunctionFlag("glMultiDrawRangeElementArrayAPPLE",FDF_RENDER_FUNC); 

  //Set any other additionally configured render calls
  const vector<string>& renderCalls = configData.frameAdditionalRenderCalls;
  for(vector<string>::size_type i = 0; i < renderCalls.size(); i++)
  {
    functionTable->SetFunctionFlag(renderCalls[i], FDF_RENDER_FUNC);
  }

#ifdef GLI_BUILD_WINDOWS

  //Set the buffer swap call
  functionTable->SetFunctionFlag("wglSwapBuffers",FDF_FRAME_FUNC);
  functionTable->SetFunctionFlag("wglSwapLayerBuffers",FDF_FRAME_FUNC);
  functionTable->SetFunctionFlag("wglSwapMultipleBuffers",FDF_FRAME_FUNC);
  
#endif// GLI_BUILD_WINDOWS

  setFunctionTableExport(functionTable);

#ifdef GLI_BUILD_LINUX

  //Set the buffer swap call. Only one for GLX?
  functionTable->SetFunctionFlag("glXSwapBuffers",FDF_FRAME_FUNC);
  
#endif// GLI_BUILD_LINUX


  //Flag that we are now init
  isInit = true;

  //Create the plugin manager
  pluginManager = new InterceptPluginManager(this,functionTable);
  
  //Attempt to load the plugins
  if(!pluginManager->LoadPlugins(configData))
  {
    delete pluginManager;
    pluginManager = NULL;
  }
  
  return true;
}