Example #1
0
		virtual void help(const string &command, ParameterList &params) const
		{
			if (command == "-i" || command == "--input" || command == "-o" || command == "--output") {
				cout << "Set current input/output file.\n"
					 << "Usage:\n"
					 << "\tmesher ((--input|-i)|(--output|-o)) (path)\n\n"
					 << "The command is transitory and passive.\n"
					 << "Any further instance of the command will override any previous one.\n"
					 << "Executive commands will use the most recently bound pathname.\n"
					 << endl;
				params.clear();
			} else if (command == "-c" || command == "--convert") {
				string inf,outf,op;
				if (0 < params.size())
					inf = params[0];
				if (1 < params.size())
					outf = params[1];
				if (2 < params.size())
					op = params[2];
				params.clear();

				ConversionImplList& registry = getRegistry();
				for (ConversionImplList::iterator cit=registry.begin(); cit!=registry.end(); ++cit)
					cit->second->conversionHelp(inf, outf, op);
			} else {
				cerr << "Warning: ConvertHandler::help() received an unrecognized command" << endl;
			}
		}
ParameterList lift2PL(const ParameterList& pl1,const ParameterList& pl2,
                      std::function<matrix::Matrix (const matrix::Matrix&, const matrix::Matrix&)> fun){
  ParameterList res;
  assert(pl1.size()==pl2.size());
  FOREACH2(pl1, pl2, p1, p2){
    res.push_back(fun(*p1,*p2));
  }
bool TypeRegistry::same_parameters(const ParameterList &p1, const ParameterList &p2) const
{
    if (p1.size() != p2.size()) return false;
    ParameterList::const_iterator j=p2.begin();
    for (ParameterList::const_iterator i=p1.begin(); i!=p1.end(); ++i, ++j)
    {
        if (TypeNameUtils::trim(i->type_specifier) != TypeNameUtils::trim(j->type_specifier))
            return false;
    }
    return true;
}
QString ExportHelper::generateXML(QString qtext, QString tableElemName, ParameterList &params, QString &errmsg, int xsltmapid)
{
  if (DEBUG)
    qDebug("ExportHelper::generateXML(%s..., %s, %d params, errmsg, %d) entered",
           qPrintable(qtext.left(80)), qPrintable(tableElemName),
           params.size(), xsltmapid);
  if (DEBUG)
  {
    QStringList plist;
    for (int i = 0; i < params.size(); i++)
      plist.append("\t" + params.name(i) + ":\t" + params.value(i).toString());
    qDebug("generateXML parameters:\n%s", qPrintable(plist.join("\n")));
  }

  QDomDocument xmldoc("xtupleimport");
  QDomElement rootelem = xmldoc.createElement("xtupleimport");
  xmldoc.appendChild(rootelem);

  if (! qtext.isEmpty())
  {
    MetaSQLQuery mql(qtext);
    XSqlQuery qry = mql.toQuery(params);
    if (qry.first())
    {
      do {
        QDomElement tableElem = xmldoc.createElement(tableElemName);

        if (DEBUG)
          qDebug("generateXML starting %s", qPrintable(tableElemName));
        for (int i = 0; i < qry.record().count(); i++)
        {
          QDomElement fieldElem = xmldoc.createElement(qry.record().fieldName(i));
          if (qry.record().value(i).isNull())
            fieldElem.appendChild(xmldoc.createTextNode("[NULL]"));
          else
            fieldElem.appendChild(xmldoc.createTextNode(qry.record().value(i).toString()));
          tableElem.appendChild(fieldElem);
        }
        rootelem.appendChild(tableElem);
      } while (qry.next());
    }
    if (qry.lastError().type() != QSqlError::NoError)
      errmsg = qry.lastError().text();
  }

  if (xsltmapid < 0)
    return xmldoc.toString();
  else
    return XSLTConvertString(xmldoc.toString(), xsltmapid, errmsg);
}
Example #5
0
// This method calls an existing function with a parameter list
CFunctionCallAttempt CFunctionWrapper::CallFunction(std::string sFunctionName, ParameterList lParameterList)
{
    // The object we'll return to the script
    CReturnValue oReturnValue;

    // Loop through all the functions
    for(FunctionList::iterator iterator = m_lFunctionList.begin(); iterator != m_lFunctionList.end(); iterator++)
    {
        // Do we have a function name match?
        if((*iterator).m_sName == sFunctionName)
        {
            // Do we have enough parameters? (are the parameter lists equally big?)
            if((*iterator).m_lParameterTypes.size() != lParameterList.size())
            {
                // Setup the error message
                std::stringstream ssErrorMessage;
                ssErrorMessage << sFunctionName << " expects " << (*iterator).m_lParameterTypes.size() << " parameter(s), got " << lParameterList.size() << ".";

                return CFunctionCallAttempt(ssErrorMessage.str());
            }

            // Current parameter number
            int iCurrentParameterNumber = 1;

            // Check if every parameter has the correct type, only if the function is type sensitive
            if((*iterator).m_bTypeSensitive)
            {
                for(unsigned int i = 0; i < lParameterList.size(); i++, iCurrentParameterNumber++)
                {
                    if(lParameterList[i].m_eType != (*iterator).m_lParameterTypes[i])
                    {
                        // The types of this parameter differ
                        std::stringstream ssErrorMessage;
                        ssErrorMessage << "Parameter " << iCurrentParameterNumber << " has a bad type (expected " << GetTypeAsString((*iterator).m_lParameterTypes[i]) << ", got " << GetTypeAsString(lParameterList[i].m_eType) << ", in function call " << sFunctionName << ")";

                        return CFunctionCallAttempt(ssErrorMessage.str());
                    }
                }
            }

            // Call the actual function
            oReturnValue = (*iterator).m_pFunctionToCall(lParameterList);
            break;
        }
    }

    // Return a valid CFunctionCallAttempt object
    return CFunctionCallAttempt(oReturnValue);
}
Example #6
0
void OptimizationTools::ScaleFunction::setParameters(const ParameterList& lambda)
throw (ParameterNotFoundException, ConstraintException)
{
  if (lambda.size() != 1)
    throw Exception("OptimizationTools::ScaleFunction::f(). This is a one parameter function!");
  lambda_.setParametersValues(lambda);
}
void BrentOneDimension::doInit(const ParameterList & params) throw (Exception)
{
  if(params.size() != 1) throw Exception("BrentOneDimension::init(). This optimizer only deals with one parameter.");

  // Bracket the minimum.
  Bracket bracket = OneDimensionOptimizationTools::bracketMinimum(_xinf, _xsup, _function, _parameters);
  if(_verbose > 0)
  {
    printMessage("Initial bracketing:");
    printMessage("A: x = " + TextTools::toString(bracket.a.x) + ", f = " + TextTools::toString(bracket.a.f));
    printMessage("B: x = " + TextTools::toString(bracket.b.x) + ", f = " + TextTools::toString(bracket.b.f));
    printMessage("C: x = " + TextTools::toString(bracket.c.x) + ", f = " + TextTools::toString(bracket.c.f));
  }
  
  // This will be the distance moved on the step before last.
  e = 0.0;

  // a and b must be in ascending order, but input abscissa need not be.
  a = (bracket.a.x < bracket.c.x ? bracket.a.x : bracket.c.x);
  b = (bracket.a.x > bracket.c.x ? bracket.a.x : bracket.c.x);
  // Initializations...
  fw = fv = fx = _function->f(_parameters);
  if(fx < bracket.b.f)
  {
    //We don't want to lose our initial guess!
    x = w = v = bracket.b.x = _parameters[0]->getValue();
  }
  else
  {
    x = w = v = bracket.b.x;
    _parameters[0]->setValue(x);
    fw = fv = fx = _function->f(_parameters);
  }
}
Example #8
0
size_t Alignment::get_number_of_free_parameters() {
    if (!likelihood) throw Exception("Likelihood model not initialised");
    ParameterList pl = likelihood->getBranchLengthsParameters();
    pl.addParameters(model->getIndependentParameters());
    if (rates->getName() == "Gamma") pl.addParameters(rates->getIndependentParameters());
    return pl.size();
}
void GlobalClockTreeLikelihoodFunctionWrapper::initParameters_()
{
  // Check if the tree is rooted:
  TreeTemplate<Node> tree(tl_->getTree());
  if (!tree.isRooted()) throw Exception("GlobalClockTreeLikelihoodFunctionWrapper::initParameters_(). Tree is unrooted!");
  if (TreeTemplateTools::isMultifurcating(*(tree.getRootNode()))) throw Exception("GlobalClockTreeLikelihoodFunctionWrapper::initParameters_(). Tree is multifurcating.");
  std::map<const Node*, double> heights;
  TreeTemplateTools::getHeights(*(tree.getRootNode()), heights);
  double totalHeight = heights[tree.getRootNode()];
  addParameter_(new Parameter("TotalHeight", totalHeight, &Parameter::R_PLUS_STAR));
  for (std::map<const Node*, double>::iterator it = heights.begin(); it != heights.end(); it++)
  {
    if (!it->first->isLeaf() && it->first->hasFather())
    {
      double fatherHeight = heights[it->first->getFather()];
      addParameter_(new Parameter("HeightP" + TextTools::toString(it->first->getId()), it->second / fatherHeight, &Parameter::PROP_CONSTRAINT_IN));
    }
  }
  // We add other parameters:
  ParameterList pl = tl_->getParameters();
  for (unsigned int i = 0; i < pl.size(); ++i)
  {
    if (pl[i].getName().substr(0, 5) != "BrLen")
      addParameter_(pl[i].clone());
  }
  // Compute everything:
  fireParameterChanged(getParameters());
}
unsigned int OneDimensionOptimizationTools::lineMinimization(DirectionFunction & f1dim, ParameterList & parameters, vector<double> & xi, double tolerance, ostream * profiler, ostream * messenger, int verbose)
{
  // Initial guess for brackets:
  double ax = 0.;
  double xx = 0.01;
  
  f1dim.setConstraintPolicy(AutoParameter::CONSTRAINTS_AUTO);
  f1dim.setMessageHandler(messenger);
  f1dim.init(parameters, xi);
  BrentOneDimension bod(&f1dim);
  bod.setMessageHandler(messenger);
  bod.setProfiler(profiler);
  bod.setVerbose(verbose >= 1 ? 1 : 0);
  bod.setOptimizationProgressCharacter(".");
  bod.getStopCondition()->setTolerance(0.01);
  bod.setInitialInterval(ax, xx);
  bod.setConstraintPolicy(AutoParameter::CONSTRAINTS_KEEP);
  ParameterList singleParameter;
  singleParameter.addParameter(Parameter("x", 0.0));
  bod.init(singleParameter);
  bod.optimize();
  //Update parameters:
  //parameters.matchParametersValues(f1dim.getFunction()->getParameters());
  
  double xmin = f1dim.getParameters()[0]->getValue();
  for(unsigned int j = 0; j < parameters.size(); j++)
  {
    xi[j] *= xmin;
    parameters[j]->setValue(parameters[j]->getValue() + xi[j]);
  }
  return bod.getNumberOfEvaluations();
}
void SubstitutionModelSet::addParameters(const ParameterList& parameters, const vector<int>& nodesId) throw (Exception)
{
  for (size_t i = 0; i < parameters.size(); i++)
    {
      modelParameterNames_.push_back(parameters[i].getName());
    }
  ParameterList pl(parameters);
  for (size_t i = 0; i < pl.size(); i++)
    {
      pl[i].setName(pl[i].getName() + "_" + TextTools::toString(++paramNamesCount_[pl[i].getName()]));
    }
  addParameters_(pl);
  // Build model indexes:
  vector<size_t> modelIndexes(nodesId.size());
  map<size_t, size_t> counts; //Check is a model is affected to several nodes.
  for (size_t i = 0; i < nodesId.size(); i++)
    {
      if (nodeToModel_.find(nodesId[i]) == nodeToModel_.end())
        throw Exception("SubstitutionModelSet::addParameters. This node has no associated model: " + TextTools::toString(nodesId[i]));
      size_t pos = nodeToModel_[nodesId[i]];
      size_t count = counts[pos]++;
      if (count == 0)
        modelParameters_[pos].addParameters(parameters);
      modelIndexes[i] = pos;
    }
  for (size_t i = 0; i < pl.size(); i++)
    {
      paramToModels_.push_back(modelIndexes);
    }
  //Update model values:
  fireParameterChanged(pl);
}
Example #12
0
LLG08_UL2::LLG08_UL2(const ProteicAlphabet* alpha) :
  AbstractBiblioMixedSubstitutionModel("LLG08_UL2."),
  pmixmodel_(0)
{
  // build the submodel

  vector<SubstitutionModel*> vpSM;
  vpSM.push_back(new LLG08_UL2::EmbeddedModel(alpha, "M1"));
  vpSM.push_back(new LLG08_UL2::EmbeddedModel(alpha, "M2"));

  Vdouble vrate, vproba;

  for (unsigned int i = 0; i < vpSM.size(); i++)
  {
    vproba.push_back((dynamic_cast<LLG08_UL2::EmbeddedModel*>(vpSM[i]))->getProportion());
    vrate.push_back(vpSM[i]->getRate());
  }

  pmixmodel_.reset(new MixtureOfSubstitutionModels(alpha, vpSM, vproba, vrate));

  string name, st;
  ParameterList pl = pmixmodel_->getParameters();
  for (size_t i = 0; i < pl.size(); i++)
  {
    name = pl[i].getName();
    lParPmodel_.addParameter(Parameter(pl[i]));
    st = pmixmodel_->getParameterNameWithoutNamespace(name);
    mapParNamesFromPmodel_[name] = st;
    addParameter_(new Parameter("LLG08_UL2." + st,
                            pmixmodel_->getParameterValue(st),
                            pmixmodel_->getParameter(st).hasConstraint() ? pmixmodel_->getParameter(st).getConstraint()->clone() : 0, true));
  }

  updateMatrices();
}
Example #13
0
uHTTP::HTTP::StatusCode TestDevice::httpRequestRecieved(HTTPRequest *httpReq)
{
	ParameterList paramList;
	httpReq->getParameterList(paramList);
	for (int n=0; n<paramList.size(); n++) {
		Parameter *param = paramList.getParameter(n);
		cout << "["<< n << "] : "<< param->getName() << "= "<< param->getValue() << endl;
	}

	string uri;
	httpReq->getURI(uri);
	if (uri.find(PRESENTATION_URI) == string::npos)  {
		return Device::httpRequestRecieved(httpReq);
	}
			 
	string contents;
	contents = "<HTML><BODY><H1>";
	contents += "";
	contents += "</H1></BODY></HTML>";
		
	HTTPResponse httpRes;
	httpRes.setStatusCode(HTTP::OK_REQUEST);
	httpRes.setContent(contents);
	return httpReq->post(&httpRes);
}
static QScriptValue exportXML(QScriptContext *context,
                              QScriptEngine  * /*engine*/)
{
  if (context->argumentCount() < 1)
    context->throwError(QScriptContext::UnknownError,
                        "not enough args passed to exportXML");

  int           qryheadid = context->argument(0).toInt32();
  ParameterList params;
  QString       filename;
  QString       errmsg;
  int           xsltmapid = -1;

  if (context->argumentCount() >= 2)
    params = qscriptvalue_cast<ParameterList>(context->argument(1));
  if (context->argumentCount() >= 3)
    filename = context->argument(2).toString();
  if (context->argumentCount() >= 4)
    errmsg = context->argument(3).toString();
  if (context->argumentCount() >= 5)
    xsltmapid = context->argument(4).toInt32();

  if (DEBUG)
    qDebug("exportXML(%d, %d params, %s, %s, %d) called with %d args",
           qryheadid, params.size(), qPrintable(filename),
           qPrintable(errmsg), xsltmapid, context->argumentCount());

  bool result = ExportHelper::exportXML(qryheadid, params, filename,
                                        errmsg, xsltmapid);
  // TODO: how to we pass back filename and errmsg output parameters?

  return QScriptValue(result);
}
void SQLiteApplets::insert ()
{
	v1 [3] = "";
	v1 [4] = "1";
	v1 [5] = "0";
	StringVector fileList;
	fileList.push_back ( "dbstat_hist" );
	fileList.push_back ( "error_hist" );
	fileList.push_back ( "fit_graph" );
	fileList.push_back ( "hist" );
	fileList.push_back ( "mmod_hist" );
	fileList.push_back ( "pr_graph" );
	fileList.push_back ( "sp_graph" );
	for ( StringVectorSizeType i = 0 ; i < fileList.size () ; i++ ) {
		string path = MsparamsDir::instance ().getParamPath ( fileList [i] + ".par.txt" );
		GenNameValueStream nvs ( path );
		if ( genFileExists ( path ) ) {
			v1 [0] = fileList [i];
			GenCommentedIFStream ifs ( path );
			ParameterList p ( ifs );
			StringVector sv = p.getNameList ();
			int numValues = p.size ();
			for ( int j = 0 ; j < numValues ; j++ ) {
				StringVector sv2 = p.getStringVectorValue ( sv [j] );
				for ( int k = 0 ; k < sv2.size () ; k++ ) {
					v1 [1] = sv [j];
					v1 [2] = sv2 [k];
					insertTable ( tableName, n1, v1 );
				}
			}
		}
	}
}
void SQLiteQuanMSMSPurity::insert ()
{
	v1 [5] = "";
	v1 [6] = "1";
	v1 [7] = "0";
	StringVector quanTypes = QuanMSMSXMLData::instance ().getQuanMSMSNames ();

	for ( StringVectorSizeType i = 0 ; i < quanTypes.size () ; i++ ) {
		v1 [0] = quanTypes [i];
		string purityPath = MsparamsDir::instance ().getParamPath (  v1 [0] + ".txt" );
		if ( genFileExists ( purityPath ) ) {
			GenCommentedIFStream ifs ( purityPath );
			while ( ifs.getUncommentedLine ( v1 [1] ) ) {
				ParameterList p ( ifs );
				StringVector sv = p.getNameList ();
				int numQuanPeaks = p.size ();
				for ( int j = 0 ; j < numQuanPeaks ; j++ ) {
					v1 [2] = sv [j];
					istringstream ist ( p.getStringValue ( sv [j] ) );
					for ( int k = 1 ; k <= 4 ; k++ ) {
						v1 [3] = "coefficient" + gen_itoa ( k );
						ist >> v1 [4];
						insertTable ( tableName, n1, v1 );
					}
				}
			}
		}
	}
}
void NewtonOneDimension::doInit(const ParameterList & params) throw (Exception)
{
  // Set the initial value (no use here! Use setInitialValues() instead).
  if(params.size() != 1) throw Exception("NewtonOneDimension::init(). This optimizer only deals with one parameter.");
  _param = params[0]->getName();
  _currentValue = _function->f(_parameters);  
  _stopCondition->init();
}
PurityCorrection::PurityCorrection ( const ParameterList* params )
{
	string quanType = params->getStringValue ( "quan_type", "" );
	if ( isQuanMSMS ( quanType ) ) {	// This is an MSMS quantitation type
		string purityName = params->getStringValue ( "purity_correction", "" );
		string purityFile = quanType + ".txt";
		string purityPath = MsparamsDir::instance ().getParamPath ( purityFile );
		if ( purityName == FROM_FORMULAE ) {
			numQuanPeaks = QuanMSMSXMLData::instance ().getNumQuanPeaks ( quanType );
			matrix = QuanMSMSXMLData::instance ().getFormulaPurityCoefficients ( quanType );
		}
		else if ( purityName == NO_CORRECTION ) {
			numQuanPeaks = QuanMSMSXMLData::instance ().getNumQuanPeaks ( quanType );
			matrix.resize ( numQuanPeaks );
			for ( int i = 0 ; i < numQuanPeaks ; i++ ) {
				for ( int j = 0 ; j < 4 ; j++ ) {
					matrix [i].push_back ( 0.0 );
				}
			}
		}
		else {
			if ( purityName != DEFAULT ) {
				if ( isPrefix ( purityName, quanType ) ) {
					purityName = purityName.substr ( quanType.length () + 1 );
				}
				else {
					ErrorHandler::genError ()->error ( "Invalid purity name.\n" );
				}
			}
			GenIFStream fromFile ( purityPath );
			string line;
			bool flag = false;
			while ( getline ( fromFile, line ) ) {
				if ( line == purityName ) {
					ParameterList p ( fromFile );
					StringVector sv = p.getNameList ();
					numQuanPeaks = p.size ();
					matrix.resize ( numQuanPeaks );
					for ( int i = 0 ; i < numQuanPeaks ; i++ ) {
						istringstream ist ( p.getStringValue ( sv [i] ) );
						double num;
						while ( ist >> num ) {
							matrix [i].push_back ( num / 100.0 );
						}
					}
					flag = true;
					break;
				}
			}
			if ( !flag ) {
				ErrorHandler::genError ()->error ( "Invalid purity name.\n" );
			}
		}
		a = nrmatrix ( 1, numQuanPeaks, 1, numQuanPeaks );
		loadA ();
		b = nrmatrix ( 1, numQuanPeaks, 1, 1 );
	}
Example #19
0
ClsQStateArrayViewHex::ClsQStateArrayViewHex( QWidget *parent, ClsBaseTopology *_clsBaseTopologyGroup,
						const char *_name, unsigned int _iSelectionMode ) :
    ClsBaseQStateArrayView(parent, _clsBaseTopologyGroup, _name, _iSelectionMode) {

    iCellSize = 20;
    iNrCellsX = 10;
    iNrCellsY = 10;

    setBackgroundColor(yellow);


    ParameterList parameterList = _clsBaseTopologyGroup->getListParameters();

    while (parameterList.size()) {
	string strParamName = parameterList.front()->getName();
	string strParamValue = parameterList.front()->getValueAsString();

//	cout << "ParamName: " << strParamName << ": " << strParamValue << endl;

	if(!strParamName.compare(ClsTagLibrary::TopologyWidthTag())) {
	    iNrCellsX = iqrUtils::string2int(strParamValue);

	}
	else if(!strParamName.compare(ClsTagLibrary::TopologyHeightTag())) {
	    iNrCellsY =  iqrUtils::string2int(strParamValue);
	}

	parameterList.pop_front();
    }

    iCellSize = iSizeMax / (iNrCellsX > iNrCellsY ? iNrCellsX : iNrCellsY);

    vCells.resize(iNrCellsX+1);
    for(int ii=0; ii<(iNrCellsX + 1);ii++){
	vCells[ii].resize(iNrCellsY+1);
    }


    iXPosStart = iYPosStart = 0;


    fValMin = 0;
    fValMax = 1.0;
    fScaleFactor = 255.0;
    this->setFrameStyle(  QFrame::WinPanel | QFrame::Raised );

    setMinimumSize( iNrCellsX * iCellSize + 2 * BORDER , iNrCellsY * iCellSize + 2 * BORDER );
    setMaximumSize( iNrCellsX * iCellSize + 2 * BORDER , iNrCellsY * iCellSize + 2 * BORDER );

    clear();
    createNullPixmap();

//    resize( maxi * SCALE + 2 * BORDER , maxj * SCALE + 2 * BORDER );
//    resize( iNrCellsX * iCellSize + 2 * BORDER , iNrCellsY * iCellSize + 2 * BORDER );

}
unsigned int OneDimensionOptimizationTools::lineSearch(DirectionFunction& f1dim,
        ParameterList& parameters,
        std::vector<double>& xi,
        std::vector<double>& gradient,
        OutputStream* profiler,
        OutputStream* messenger,
        int verbose)
{
    size_t size = xi.size();

    f1dim.setConstraintPolicy(AutoParameter::CONSTRAINTS_AUTO);
    f1dim.setMessageHandler(messenger);
    f1dim.init(parameters, xi);

    double slope=0;
    for (unsigned int i=0; i<size; i++)
        slope+=xi[i]*gradient[i];

    //  if (slope>=0)
    //  throw Exception("Slope problem in OneDimensionOptimizationTools::lineSearch. Slope="+TextTools::toString(slope));

    double x, temp, test=0;
    for (unsigned int i=0; i<size; i++) {
        x=abs(parameters[i].getValue());
        temp=abs(xi[i]);
        if (x>1.0)
            temp/=x;
        if (temp>test)
            test=temp;
    }

    NewtonBacktrackOneDimension nbod(&f1dim, slope, test);

    nbod.setMessageHandler(messenger);
    nbod.setProfiler(profiler);
    nbod.setVerbose(verbose >= 1 ? 1 : 0);
    nbod.setOptimizationProgressCharacter(".");
    nbod.getStopCondition()->setTolerance(0.0001);
    //  nbod.setInitialInterval(ax, xx);
    nbod.setConstraintPolicy(AutoParameter::CONSTRAINTS_KEEP);
    ParameterList singleParameter;
    singleParameter.addParameter(Parameter("x", 0.0));
    nbod.init(singleParameter);
    nbod.optimize();
    //Update parameters:
    //parameters.matchParametersValues(f1dim.getFunction()->getParameters());

    double xmin = f1dim.getParameters()[0].getValue();
    for(unsigned int j = 0; j < parameters.size(); j++)
    {
        xi[j] *= xmin;
        parameters[j].setValue(parameters[j].getValue() + xi[j]);
    }

    return nbod.getNumberOfEvaluations();
}
double NumCalcApplicationTools::getDefaultValue(const ParameterList & pl, const string& name, double x)
{
  for(unsigned int i = 0; i < pl.size(); i++)
  {
    Parameter * p = pl[i];
    if(p->getName() == name)
      return p->getValue();
  }
  return x;
}
Example #22
0
bool
MatchesBlueprint::setup(const IIndexEnvironment &,
                        const ParameterList & params)
{
    _field = params[0].asField();
    if (params.size() == 2) {
        _termIdx = params[1].asInteger();
    }
    describeOutput("out", "Returns 1 if the given field is matched by the query, 0 otherwise");
    return true;
}
QString ExportHelper::generateHTML(QString qtext, ParameterList &params, QString &errmsg)
{
  if (DEBUG)
    qDebug("ExportHelper::generateHTML(%s..., %d params, errmsg) entered",
           qPrintable(qtext.left(80)), params.size());
  if (qtext.isEmpty())
    return QString::null;

  QTextDocument    doc(0);
  QTextCursor      cursor(&doc);
  QTextTableFormat tablefmt;

  bool valid;
  QVariant includeheaderVar = params.value("includeHeaderLine", &valid);
  bool includeheader = (valid ? includeheaderVar.toBool() : false);
  if (DEBUG)
    qDebug("generateHTML(qtest, params, errmsg) includeheader = %d, valid = %d",
           includeheader, valid);

  MetaSQLQuery mql(qtext);
  XSqlQuery qry = mql.toQuery(params);
  if (qry.first())
  {
    int cols = qry.record().count();
    int expected = qry.size();
    if (includeheader)
      expected++;

    // presize the table
    cursor.insertTable((expected < 0 ? 1 : expected), cols, tablefmt);
    if (includeheader)
    {
      tablefmt.setHeaderRowCount(1);
      for (int p = 0; p < cols; p++)
      {
        cursor.insertText(qry.record().fieldName(p));
        cursor.movePosition(QTextCursor::NextCell);
      }
    }

    do {
      for (int i = 0; i < cols; i++)
      {
        cursor.insertText(qry.value(i).toString());
        cursor.movePosition(QTextCursor::NextCell);
      }
    } while (qry.next());
  }
  if (qry.lastError().type() != QSqlError::NoError)
    errmsg = qry.lastError().text();

  return doc.toHtml();
}
Example #24
0
void ParametrizableTree::fireParameterChanged(const ParameterList& parameters)
{
  if (liveIndex_) {
    for (size_t i = 0; i < parameters.size(); ++i) {
      const Parameter& param = parameters[i];
      if (reverseIndex_.find(param.getName()) != reverseIndex_.end())
        reverseIndex_[param.getName()]->setDistanceToFather(param.getValue());
    }
    isSynchronized_ = true;
  } else {
    isSynchronized_ = false;
  }
}
QString ExportHelper::generateDelimited(const int qryheadid, ParameterList &params, QString &errmsg)
{
  if (DEBUG)
    qDebug("ExportHelper::exportDelimited(%d, %d params, errmsgd) entered",
           qryheadid, params.size());

  QStringList result;

  XSqlQuery itemq;
  itemq.prepare("SELECT *"
                "  FROM qryitem"
                " WHERE qryitem_qryhead_id=:id"
                " ORDER BY qryitem_order;");
  itemq.bindValue(":id", qryheadid);
  itemq.exec();
  while (itemq.next())
  {
    QString qtext;
    if (itemq.value("qryitem_src").toString() == "REL")
    {
      QString schemaName = itemq.value("qryitem_group").toString();
      qtext = "SELECT * FROM " +
              (schemaName.isEmpty() ? QString("") : schemaName + QString(".")) +
              itemq.value("qryitem_detail").toString();
    }
    else if (itemq.value("qryitem_src").toString() == "MQL")
    {
      QString tmpmsg;
      bool valid;
      qtext = MQLUtil::mqlLoad(itemq.value("qryitem_group").toString(),
                               itemq.value("qryitem_detail").toString(),
                               tmpmsg, &valid);
      if (! valid)
        errmsg = tmpmsg;
    }
    else if (itemq.value("qryitem_src").toString() == "CUSTOM")
      qtext = itemq.value("qryitem_detail").toString();

    if (! qtext.isEmpty())
    {
      QString oneresult = generateDelimited(qtext, params, errmsg);
      if (! oneresult.isEmpty())
        result.append(oneresult);
    }
  }
  if (itemq.lastError().type() != QSqlError::NoError)
    errmsg = itemq.lastError().text();

  return result.join("\n");
}
Example #26
0
void TGen::Engine::CommandSet::executeCommand(const TGen::Engine::Command & command, ParameterList & parameters, TGen::Engine::TextOutputer & output) {
	if (command.getName() == "set") {	
		if (parameters.size() == 1) {
			std::string varName = parameters[0];
			
			try {
				output.outputText(varName + " = " + variables.getVariable(varName).getValue(), 0);
			}
			catch (TGen::RuntimeException & e) {
				output.outputText(varName + ": " + e.getDescription(), 0);
			}
		}
		else if (parameters.size() == 2) {
			std::string varName = parameters[0];
			std::string varValue = parameters[1];
			//output.outputText("changing var " + varName + " to " + varValue, 0);
			
			variables.addVariable(TGen::Engine::Variable(varName, varValue, "null", TGen::Engine::VariableNonInit), TGen::Engine::AddOverrideValue | TGen::Engine::AddNoThrow);
		}
		else {
			throw TGen::Engine::CommandException(command, "parameter count mismatch, expected: 1 or 2");			
		}
	}
}
Example #27
0
/* Action 0: DrawText */
void EventInterpreter::action0(Event *e) {
	ParameterList *params = getParameters(e);

	if(params->at(0)->isString() && !e->isLocked()) {
		gk::ApplicationStateStack::getInstance().push<MessageState>(*(std::string*)(params->at(0)->value()));
		e->lock();
	}
	else {
		if(params->size() == 2 && params->at(1)->isInteger()) {
			e->currentActionID(*(int*)params->at(1)->value());
		}

		e->unlock();
		update(e);
	}
}
void AbstractOptimizer::printPoint(const ParameterList & params, double value)
{
    unsigned int ndim = params.size();
    profile(_nbEval);
    profile("\t");
    for(unsigned int j = 0; j < ndim; j++)
    {
        profile(TextTools::toString(params[j]->getValue()));
        profile("\t");
    }
    profile(value);
    profile("\t");
    time_t seconds;
    time(&seconds);
    profileln(difftime(seconds, _startTime));
}
Example #29
0
vector<string> findParameter(const ParameterList &request, string name) {
    for (unsigned i = 0; i < request.size(); i++)
        if (request.parameterName(i) == name) {
            vector<string> names;
            size_t next = string::npos;

            // split names on every ','
            do {
                size_t last = next;
                next = name.find_first_of(',', next+1);
                names.push_back(name.substr(last+1, next - (last+1)));
            } while (next != string::npos);

            return names;
        }
    return vector<string>();
}
Example #30
0
ClsQStateArrayViewRect::ClsQStateArrayViewRect( QWidget *parent, ClsBaseTopology *_clsBaseTopologyGroup,
						const char *_name, unsigned int _iSelectionMode ) :
    ClsBaseQStateArrayView(parent, _clsBaseTopologyGroup, _name, _iSelectionMode) {
#ifdef DEBUG_CLSQSTATEARRAYVIEWRECT
    cout << "ClsQStateArrayViewRect( QWidget *parent, ClsBaseTopology *_clsBaseTopologyGroup, const char *_name, unsigned int _iSelectionMode ) " << endl;
#endif

    iCellSize = 20;
    iNrCellsX = 10;
    iNrCellsY = 10;

    ParameterList parameterList = _clsBaseTopologyGroup->getListParameters();

    while (parameterList.size()) {
	string strParamName = parameterList.front()->getName();
	string strParamValue = parameterList.front()->getValueAsString();
	if(!strParamName.compare(ClsTagLibrary::TopologyWidthTag())) {
	    iNrCellsX = iqrUtils::string2int(strParamValue);
	}
	else if(!strParamName.compare(ClsTagLibrary::TopologyHeightTag())) {
	    iNrCellsY =  iqrUtils::string2int(strParamValue);
	}
	parameterList.pop_front();
    }

    iCellSize = iSizeMax / (iNrCellsX > iNrCellsY ? iNrCellsX : iNrCellsY);
    if(iCellSize <=1){
	iCellSize = 2;
    }

    vCells.resize(iNrCellsX+1);
    for(int ii=0; ii<(iNrCellsX + 1);ii++){
	vCells[ii].resize(iNrCellsY+1);
    }

    this->setFrameStyle(  QFrame::WinPanel | QFrame::Raised );

    setMinimumSize( iNrCellsX * iCellSize + 2 * BORDER , iNrCellsY * iCellSize + 2 * BORDER );
    setMaximumSize( iNrCellsX * iCellSize + 2 * BORDER , iNrCellsY * iCellSize + 2 * BORDER );

    clear();
    createNullPixmap();


}