void KstBasicPlugin::createFitScalars() {
    // Assumes that this is called with a write lock in place on this object
    Q_ASSERT(myLockStatus() == KstRWLock::WRITELOCKED);

    if (_isFit && _outputVectors.contains("Parameters")) {
        KstVectorPtr vectorParam = _outputVectors["Parameters"];
        if (vectorParam) {
            QString paramName;
            int i = 0;
            int length = vectorParam->length();

            KstWriteLocker blockScalarUpdates(&KST::scalarList.lock());
            KST::scalarList.setUpdateDisplayTags(false);
            for (paramName = parameterName(i);
                    !paramName.isEmpty() && i < length;
                    paramName = parameterName(++i)) {
                double scalarValue = vectorParam->value(i);
                if (!_outputScalars.contains(paramName)) {
                    KstScalarPtr s = new KstScalar(KstObjectTag(paramName, tag()), this, scalarValue);
                    s->KstObject::writeLock();  // must write lock, since fit scalars are created from update()
                    _outputScalars.insert(paramName, s);
                } else {
                    _outputScalars[paramName]->setValue(scalarValue);
                }
            }
            KST::scalarList.setUpdateDisplayTags(true);
        }
    }
}
// If a plugin provides a Parameters Vector, then scalars will be created, as well as a label.
void BasicPlugin::createScalars() {
  // Assumes that this is called with a write lock in place on this object
  Q_ASSERT(myLockStatus() == KstRWLock::WRITELOCKED);

  if (hasParameterVector()) {
    VectorPtr vectorParam = _outputVectors["Parameters Vector"];
    if (vectorParam) {
      QString paramName;
      int i = 0;
      int length = vectorParam->length();

      Q_ASSERT(store());
      for (paramName = parameterName(i);
          !paramName.isEmpty() && i < length;
           paramName = parameterName(++i)) {
        double scalarValue = vectorParam->value(i);
        if (!_outputScalars.contains(paramName)) {
          ScalarPtr s = store()->createObject<Scalar>();
          s->setProvider(this);
          s->setSlaveName(paramName);
          s->setValue(scalarValue);
          s->writeLock();
          _outputScalars.insert(paramName, s);
        } else {
          _outputScalars[paramName]->setValue(scalarValue);
        }
      }
    }
  }
}
Ejemplo n.º 3
0
/**
 * Return a vector with all parameter names.
 */
std::vector<std::string> IFunction::getParameterNames() const {
  std::vector<std::string> out;
  for (size_t i = 0; i < nParams(); ++i) {
    out.push_back(parameterName(i));
  }
  return out;
}
Ejemplo n.º 4
0
void Abragam::setActiveParameter(size_t i,double value)
{
  size_t j = i;

  if (parameterName(j) == "Sigma"  ) 
    setParameter(j,fabs(value),false);  // Make sigma positive
  else if (parameterName(j) == "Phi")
  {
    // Put angle in range of (-180 to 180] degrees
    double a = fmod(value, 2*M_PI); 
    if( a<=-M_PI ) a += 2*M_PI; 
    if( a>M_PI ) a-= 2*M_PI;
    setParameter(j,a,false);
  }
  else
    setParameter(j,value,false);
}
Ejemplo n.º 5
0
/**
 * Writes a string that can be used in Fit.IFunction to create a copy of this
 * IFunction
 * @return string representation of the function
 */
std::string IFunction::asString() const {
  std::ostringstream ostr;
  ostr << "name=" << this->name();
  // print the attributes
  std::vector<std::string> attr = this->getAttributeNames();
  for (const auto &attName : attr) {
    std::string attValue = this->getAttribute(attName).value();
    if (!attValue.empty() && attValue != "\"\"") {
      ostr << ',' << attName << '=' << attValue;
    }
  }
  // print the parameters
  for (size_t i = 0; i < nParams(); i++) {
    const ParameterTie *tie = getTie(i);
    if (!tie || !tie->isDefault()) {
      ostr << ',' << parameterName(i) << '=' << getParameter(i);
    }
  }
  // collect non-default constraints
  std::string constraints;
  for (size_t i = 0; i < nParams(); i++) {
    const IConstraint *c = getConstraint(i);
    if (c && !c->isDefault()) {
      std::string tmp = c->asString();
      if (!tmp.empty()) {
        if (!constraints.empty()) {
          constraints += ",";
        }
        constraints += tmp;
      }
    }
  }
  // print constraints
  if (!constraints.empty()) {
    ostr << ",constraints=(" << constraints << ")";
  }
  // collect the non-default ties
  std::string ties;
  for (size_t i = 0; i < nParams(); i++) {
    const ParameterTie *tie = getTie(i);
    if (tie && !tie->isDefault()) {
      std::string tmp = tie->asString(this);
      if (!tmp.empty()) {
        if (!ties.empty()) {
          ties += ",";
        }
        ties += tmp;
      }
    }
  }
  // print the ties
  if (!ties.empty()) {
    ostr << ",ties=(" << ties << ")";
  }
  return ostr.str();
}
QString BasicPlugin::label(int precision) const {
  Q_UNUSED(precision)
  QString label;
  QString paramName;

  label = Name();

  if (hasParameterVector()) {
    VectorPtr vectorParam = _outputVectors["Parameters Vector"];
    int length = vectorParam->length();
    int i=0;
    for (paramName = parameterName(i);
         !paramName.isEmpty() && i < length;
         paramName = parameterName(++i)) {
        if (_outputScalars.contains(paramName)) {
          label += QString("\n%1: [%2]").arg(paramName).arg(_outputScalars[paramName]->Name());
        }
    }
  }

  return label;
}
Ejemplo n.º 7
0
/** Returns the name of parameter i as it declared in its function
 * @param i :: The parameter index
 * @param recursive :: If true call parameterLocalName recusively until
 *    a non-composite function is reached.
 * @return The pure parameter name (without the function identifier f#.)
 */
std::string CompositeFunction::parameterLocalName(size_t i,
                                                  bool recursive) const {
  size_t iFun = functionIndex(i);
  auto localIndex = i - m_paramOffsets[iFun];
  auto localFunction = m_functions[iFun].get();
  if (recursive) {
    auto cf = dynamic_cast<const CompositeFunction *>(localFunction);
    if (cf) {
      return cf->parameterLocalName(localIndex, recursive);
    }
  }
  return localFunction->parameterName(localIndex);
}
QStringList specSpectrumCalculatorAction::descriptorNames(QString& teststring)
{
	QRegExp re("\"([^\"]|\\\\\")*\"") ;
	QStringList descriptorNames ;
	int i = 0 ;
	int index = 0 ;
	while((index = re.indexIn(teststring)) != -1)
	{
		descriptorNames << re.cap().mid(1, re.cap().length() - 2) ;
		teststring.remove(index, re.matchedLength()) ;
		teststring.insert(index, parameterName(i++)) ;
	}
	return descriptorNames ;
}
Ejemplo n.º 9
0
  void ALCPeakFittingPresenter::onPeakPickerChanged()
  {
    auto index = m_view->currentFunctionIndex();

    // If PeakPicker is changed, it should be enabled, which means a peak function should be selected
    // (See onCurrentFunctionChanged)
    assert(index);

    auto peakFunc = m_view->peakPicker();

    // Update all the defined parameters of the peak function
    for (size_t i = 0; i < peakFunc->nParams(); ++i)
    {
      QString paramName = QString::fromStdString(peakFunc->parameterName(i));
      m_view->setParameter(*index, paramName, peakFunc->getParameter(paramName.toStdString()));
    }
  }
Ejemplo n.º 10
0
std::string IPeakFunction::getCentreParameterName() const {
  FunctionParameterDecorator_sptr fn =
      boost::dynamic_pointer_cast<FunctionParameterDecorator>(
          FunctionFactory::Instance().createFunction("PeakParameterFunction"));

  if (!fn) {
    throw std::runtime_error(
        "PeakParameterFunction could not be created successfully.");
  }

  fn->setDecoratedFunction(this->name());

  FunctionDomain1DVector domain(std::vector<double>(4, 0.0));
  TempJacobian jacobian(4, fn->nParams());

  fn->functionDeriv(domain, jacobian);

  return parameterName(jacobian.maxParam(0));
}
Ejemplo n.º 11
0
/**
* Initializes the mu::Parser.
*/
void UserFunctionMD::setFormula() {
  // variables must be already defined
  if (m_vars.empty())
    return;
  if (m_formula.empty()) {
    m_formula = "0";
  }
  m_parser.SetVarFactory(AddVariable, this);
  m_parser.SetExpr(m_formula);
  // declare function parameters using mu::Parser's implicit variable setting
  m_parser.Eval();
  m_parser.ClearVar();
  // set muParser variables
  for (size_t i = 0; i < m_vars.size(); ++i) {
    m_parser.DefineVar(m_varNames[i], &m_vars[i]);
  }
  for (size_t i = 0; i < nParams(); i++) {
    m_parser.DefineVar(parameterName(i), getParameterAddress(i));
  }

  m_parser.SetExpr(m_formula);
}
Ejemplo n.º 12
0
/**
 * Writes a string that can be used in Fit.IFunction to create a copy of this IFunction
 * @param fmt :: Formatting flag. Set to true to ctreated formatted output.
 * @return string representation of the function
 */
std::string IFunction::asString(bool fmt, size_t level)const
{
  std::string nl = fmt? "\n" : "";
  std::string padding = fmt && level ? std::string(level*2,' ') : "";
  std::string padding2 = padding + "  ";

  std::ostringstream ostr;
  
  // write function name
  ostr << padding << this->name() << "(" << nl;
  bool needComma = false;

  // write function attributes
  std::vector<std::string> attr = this->getAttributeNames();
  for(size_t i=0;i<attr.size();i++)
  {
    std::string attName = attr[i];
    std::string attValue = this->getAttribute(attr[i]).value();
    if (!attValue.empty())
    {
      if (needComma)
      {
        ostr << ',' << nl;
      }
      needComma = true;
      ostr << padding2 << attName << '=' << attValue;
    }
  }

  // write function parameters
  for(size_t i=0;i<nParams();i++)
  {
    if (needComma)
    {
      ostr << ',' << nl;
    }
    needComma = true;
    ostr << padding2 << parameterName(i) << '=' << getParameter(i);
  }

  // write constraints
  std::string constraints;
  for(size_t i=0;i<nParams();i++)
  {
    const IConstraint* c = getConstraint(i);
    if (c)
    {
      std::string tmp = c->asString();
      if (!tmp.empty())
      {
        if (!constraints.empty())
        {
          constraints += ",";
        }
        constraints += tmp;
      }
    }
  }
  if (!constraints.empty())
  {
    ostr << ",constraints=(" << constraints << ")";
  }

  // write ties
  std::string ties;
  for(size_t i=0;i<nParams();i++)
  {
    const ParameterTie* tie = getTie(i);
    if (tie)
    {
      std::string tmp = tie->asString(this);
      if (!tmp.empty())
      {
        if (!ties.empty())
        {
          ties += ",";
        }
        ties += tmp;
      }
    }
  }
  if (!ties.empty())
  {
    ostr << ",ties=(" << ties << ")";
  }
  ostr << nl << padding << ")";
  return ostr.str();
}
Ejemplo n.º 13
0
////////////////////////////////////////////////////////////////
//
// addWMIParametersToCIMMethod
//
// Add parameters from a WMI class to a CIMMethod.
//
///////////////////////////////////////////////////////////////
void addWMIParametersToCIMMethod(
        const CComPtr<IWbemClassObject>& wmiParameters, 
        CIMMethod& method,
        Boolean includeQualifiers)
{
    // Check if wmiParameters is NULL (this will ocurr when there are none)
    HRESULT hr;
    if (wmiParameters)
    {
        // Enumerate all output parameters
        hr = wmiParameters->BeginEnumeration(WBEM_FLAG_LOCAL_ONLY);
        while(true)
        {
            // Get current parameter name and value
            CComBSTR bstrParamName;
            CComVariant vParamValue;
            CIMTYPE wmiType;
            hr = wmiParameters->Next(0, &bstrParamName, 
                &vParamValue, &wmiType, NULL);

            // Check errors
            if (WBEM_S_NO_MORE_DATA == hr) 
            {
                break;
            }
            if (FAILED(hr)) 
            {
                bstrParamName.Empty();
                vParamValue.Clear();
                throw CIMException(CIM_ERR_FAILED);
            }
            
            // Convert to CIMParameter
            BSTR tmpBstr = (BSTR)bstrParamName.Copy();
            String parameterName(_bstr_t(tmpBstr, FALSE));
            SysFreeString(tmpBstr);

            // Add the parameter to this method if it is not the return value
            // and it does not already exist in the method.
            // If the parameter already exists (i.e., an in & out parameter), 
            // then there is no need to re-add or modify it here
            // (the in version is an exact copy of the out version):
            String strRetVal("ReturnValue");
            if (!(String::equalNoCase(parameterName, strRetVal)) &&
                method.findParameter(parameterName) == PEG_NOT_FOUND)
            {
                // Get the qualifier list for this param from WMI:
                CComPtr<IWbemQualifierSet> pParamQualifiers;
                HRESULT hr = 
                    wmiParameters->GetPropertyQualifierSet(bstrParamName, 
                                                           &pParamQualifiers);
                
                // create the CIMParameter
                CIMParameter cimParam = 
                    cimParamFromWMIParam(parameterName,
                                         wmiType,
                                         pParamQualifiers,
                                         includeQualifiers);

                // Now, add the new parameter to the CIMMethod:
                method.addParameter(cimParam);

                if (pParamQualifiers)
                    pParamQualifiers.Release();
            }

            bstrParamName.Empty();
            vParamValue.Clear();
        }
        hr = wmiParameters->EndEnumeration();    
    }
}
Ejemplo n.º 14
0
int DOUserValueModified(const CKBehaviorContext& behcontext)
{
	CKBehavior* beh = behcontext.Behavior;
	CKMessageManager* mm = behcontext.MessageManager;
	CKContext* ctx = behcontext.Context;

	//////////////////////////////////////////////////////////////////////////
	//connection id : 
	int connectionID = vtTools::BehaviorTools::GetInputParameterValue<int>(beh,0);





	if (beh->IsInputActive(1))
	{
		beh->ActivateInput(1,FALSE);
		beh->ActivateOutput(1);
		return 0;
	}



	//////////////////////////////////////////////////////////////////////////
	//the object :
	CK3dEntity *obj= (CK3dEntity*)beh->GetInputParameterObject(1);
	if (!obj)
	{
		beh->ActivateOutput(3);
		return CKBR_ACTIVATENEXTFRAME;
	}

	//////////////////////////////////////////////////////////////////////////
	//network ok  ? 
	xNetInterface *cin  = GetNM()->GetClientNetInterface();
	if (!cin)
	{
		CKParameterOut *pout = beh->GetOutputParameter(2);
		XString errorMesg("distributed object creation failed,no network connection !");
		pout->SetStringValue(errorMesg.Str());
		beh->ActivateOutput(3);
		return CKBR_ACTIVATENEXTFRAME;
	}

	//use objects name, if not specified : 
	CKSTRING name= obj->GetName();
	
	IDistributedObjects*doInterface  = cin->getDistObjectInterface();
	IDistributedClasses*cInterface = cin->getDistributedClassInterface();
    
	XString className((CKSTRING) beh->GetLocalParameterReadDataPtr(0));
	XString parameterName((CKSTRING) beh->GetLocalParameterReadDataPtr(1));

	xDistributedClass *_class = cInterface->get(className.CStr());
	
	
	//////////////////////////////////////////////////////////////////////////
	//dist class ok  ? 
	if (_class==NULL)
	{
		beh->ActivateOutput(3);
		ctx->OutputToConsoleEx("Distributed Class doesn't exists : %s",className.CStr());
		return CKBR_ACTIVATENEXTFRAME;
	}
	const char * cNAme  = _class->getClassName().getString();

	int classType  = _class->getEnitityType();
	int bcount = beh->GetInputParameterCount();

	//////////////////////////////////////////////////////////////////////////
	//we come in by input 0 : 

	

	xDistributedObject *dobjDummy = NULL;
	xDistributedObject *dobj = doInterface->getByEntityID(obj->GetID());
	if (!dobj)
	{
		beh->ActivateOutput(3);
		return CKBR_ACTIVATENEXTFRAME;
	}

	if (dobj)
	{
		xDistributedProperty * prop  = dobj->getUserProperty(parameterName.CStr());
		if (prop)
		{
			if ( dobj->getGhostUpdateBits().testStrict(1 << prop->getBlockIndex()))
			{
				CKParameterManager *pam = static_cast<CKParameterManager *>(ctx->GetParameterManager());
				CKParameterOut *ciIn = beh->GetOutputParameter(1);
				CKParameterType pType  = ciIn->GetType();

				int sType = vtTools::ParameterTools::GetVirtoolsSuperType(ctx,pam->ParameterTypeToGuid(pType));	
				int userType = xDistTools::ValueTypeToSuperType(prop->getPropertyInfo()->mValueType);
				if ( userType ==sType )
				{
					beh->ActivateOutput(2);
					dobj->getGhostUpdateBits().set(1 << prop->getBlockIndex(),false);
					switch(xDistTools::ValueTypeToSuperType(prop->getPropertyInfo()->mValueType))
					{
						case vtFLOAT:
						{
							xDistributedPoint1F *propValue  = static_cast<xDistributedPoint1F*>(prop);
							if (propValue)
							{
								float ovalue = propValue->mLastServerValue;
								beh->SetOutputParameterValue(1,&ovalue);
								break;
							}
						}

						case vtVECTOR2D:
						{
							xDistributedPoint2F *propValue  = static_cast<xDistributedPoint2F*>(prop);
							if (propValue)
							{
								Point2F ovalue = propValue->mLastServerValue;
								Vx2DVector ovaluex(ovalue.x,ovalue.y);
								beh->SetOutputParameterValue(1,&ovaluex);
								break;
							}
						}
						case vtVECTOR:
						{
							xDistributedPoint3F *propValue  = static_cast<xDistributedPoint3F*>(prop);
							if (propValue)
							{
								Point3F ovalue = propValue->mLastServerValue;
								VxVector ovaluex(ovalue.x,ovalue.y,ovalue.z);
								beh->SetOutputParameterValue(1,&ovaluex);
								break;
							}
						}
						case vtQUATERNION:
						{
							xDistributedQuatF*propValue  = static_cast<xDistributedQuatF*>(prop);
							if (propValue)
							{
								QuatF ovalue = propValue->mLastServerValue;
								VxQuaternion ovaluex(ovalue.x,ovalue.y,ovalue.z,ovalue.w);
								beh->SetOutputParameterValue(1,&ovaluex);
								break;
							}
						}
						case vtSTRING:
						{
							xDistributedString*propValue  = static_cast<xDistributedString*>(prop);
							if (propValue)
							{
								TNL::StringPtr ovalue = propValue->mCurrentValue;
								CKParameterOut *pout = beh->GetOutputParameter(1);
								XString errorMesg(ovalue.getString());
								pout->SetStringValue(errorMesg.Str());
								break;
							}
						}
						case vtINTEGER:
						{
							xDistributedInteger*propValue  = static_cast<xDistributedInteger*>(prop);
							if (propValue)
							{
								int ovalue = propValue->mLastServerValue;
								beh->SetOutputParameterValue(1,&ovalue);
								break;
							}
						}
					}
				}
			}
		}
	}

	return CKBR_ACTIVATENEXTFRAME;
	if (beh->IsInputActive(0))
	{
		beh->ActivateOutput(0);
	}



	/*
	//////////////////////////////////////////////////////////////////////////
	//we come in by input 0 : 
	if (beh->IsInputActive(0))
	{
		beh->ActivateOutput(0);

	
		for (int i = BEH_IN_INDEX_MIN_COUNT  ; i < beh->GetInputParameterCount() ; i++ )
		{
			beh->ActivateInput(0,FALSE);

			xDistributedObject *dobj = doInterface->get(name);
			if (!dobj)
			{
				beh->ActivateOutput(0);
				return 0;
			}

			CKParameterIn *ciIn = beh->GetInputParameter(i);
			CKParameterType pType  = ciIn->GetType();
			int sType = vtTools::ParameterTools::GetVirtoolsSuperType(ctx,pam->ParameterTypeToGuid(pType));	
			xDistributedPropertyArrayType &props = *dobj->getDistributedPorperties();
			
			int propID = _class->getInternalUserFieldIndex(i - BEH_IN_INDEX_MIN_COUNT);
			if (propID==-1 ||  propID > props.size() )
			{
				beh->ActivateOutput(1);
				return 0;
			}
			
			xDistributedProperty *prop  = props[propID];
			if (prop)
			{
				xDistributedPropertyInfo*propInfo  = prop->getPropertyInfo();
				if (propInfo)
				{
					
					if (xDistTools::ValueTypeToSuperType(propInfo->mValueType) ==sType )
					{
						TNL::U32 currentTime = TNL::Platform::getRealMilliseconds();

						switch(propInfo->mValueType)
						{
							case E_DC_PTYPE_3DVECTOR:
							{

								xDistributedPoint3F * dpoint3F  = (xDistributedPoint3F*)prop;
								if (dpoint3F)
								{
									VxVector vvalue;
									beh->GetInputParameterValue(i,&vvalue);
									bool update = dpoint3F->updateValue(xMath::getFrom(vvalue),currentTime);
								}
                                break;
							}

							case E_DC_PTYPE_FLOAT:
								{

									xDistributedPoint1F * dpoint3F  = (xDistributedPoint1F*)prop;
									if (dpoint3F)
									{
										float vvalue;
										beh->GetInputParameterValue(i,&vvalue);
										bool update = dpoint3F->updateValue(vvalue,currentTime);
									}
									break;
								}
						}
					}
				}
			}
		}
			
		beh->ActivateOutput(0);
	}

	
	*/
	//////////////////////////////////////////////////////////////////////////
	//we come in by loop : 
	return 0;
}
Ejemplo n.º 15
0
//----------------------------------------------------------------------------------------------
/// Execute the algorithm.
void EstimateFitParameters::execConcrete() {
  auto costFunction = getCostFunctionProperty();
  auto func = costFunction->getFittingFunction();

  // Use additional constraints on parameters tied in some way
  // to the varied parameters to exculde unwanted results.
  std::vector<std::unique_ptr<IConstraint>> constraints;
  std::string constraintStr = getProperty("Constraints");
  if (!constraintStr.empty()) {
    Expression expr;
    expr.parse(constraintStr);
    expr.toList();
    for (auto &term : expr.terms()) {
      IConstraint *c =
          ConstraintFactory::Instance().createInitialized(func.get(), term);
      constraints.push_back(std::unique_ptr<IConstraint>(c));
    }
  }

  // Ranges to use with random number generators: one for each free parameter.
  std::vector<std::pair<double, double>> ranges;
  ranges.reserve(costFunction->nParams());
  for (size_t i = 0; i < func->nParams(); ++i) {
    if (func->isFixed(i)) {
      continue;
    }
    auto constraint = func->getConstraint(i);
    if (constraint == nullptr) {
      func->fix(i);
      continue;
    }
    auto boundary = dynamic_cast<Constraints::BoundaryConstraint *>(constraint);
    if (boundary == nullptr) {
      throw std::runtime_error("Parameter " + func->parameterName(i) +
                               " must have a boundary constraint. ");
    }
    if (!boundary->hasLower()) {
      throw std::runtime_error("Constraint of " + func->parameterName(i) +
                               " must have a lower bound.");
    }
    if (!boundary->hasUpper()) {
      throw std::runtime_error("Constraint of " + func->parameterName(i) +
                               " must have an upper bound.");
    }
    // Use the lower and upper bounds of the constraint to set the range
    // of a generator with uniform distribution.
    ranges.push_back(std::make_pair(boundary->lower(), boundary->upper()));
  }
  // Number of parameters could have changed
  costFunction->reset();
  if (costFunction->nParams() == 0) {
    throw std::runtime_error("No parameters are given for which to estimate "
                             "initial values. Set boundary constraints to "
                             "parameters that need to be estimated.");
  }

  size_t nSamples = static_cast<int>(getProperty("NSamples"));
  size_t seed = static_cast<int>(getProperty("Seed"));

  if (getPropertyValue("Type") == "Monte Carlo") {
    runMonteCarlo(*costFunction, ranges, constraints, nSamples, seed);
  } else {
    size_t nSelection = static_cast<int>(getProperty("Selection"));
    size_t nIterations = static_cast<int>(getProperty("NIterations"));
    runCrossEntropy(*costFunction, ranges, constraints, nSamples, nSelection,
                    nIterations, seed);
  }
  bool fixBad = getProperty("FixBadParameters");
  if (fixBad) {
    fixBadParameters(*costFunction, ranges);
  }
}
Ejemplo n.º 16
0
//----------------------------------------------------------------------------------------------
/// Execute the algorithm.
void EstimateFitParameters::execConcrete() {
  auto costFunction = getCostFunctionInitialized();
  auto func = costFunction->getFittingFunction();

  // Use additional constraints on parameters tied in some way
  // to the varied parameters to exculde unwanted results.
  std::vector<std::unique_ptr<IConstraint>> constraints;
  std::string constraintStr = getProperty("Constraints");
  if (!constraintStr.empty()) {
    Expression expr;
    expr.parse(constraintStr);
    expr.toList();
    for (auto &term : expr.terms()) {
      IConstraint *c =
          ConstraintFactory::Instance().createInitialized(func.get(), term);
      constraints.push_back(std::unique_ptr<IConstraint>(c));
    }
  }

  // Ranges to use with random number generators: one for each free parameter.
  std::vector<std::pair<double, double>> ranges;
  ranges.reserve(costFunction->nParams());
  for (size_t i = 0; i < func->nParams(); ++i) {
    if (!func->isActive(i)) {
      continue;
    }
    auto constraint = func->getConstraint(i);
    if (constraint == nullptr) {
      func->fix(i);
      continue;
    }
    auto boundary = dynamic_cast<Constraints::BoundaryConstraint *>(constraint);
    if (boundary == nullptr) {
      throw std::runtime_error("Parameter " + func->parameterName(i) +
                               " must have a boundary constraint. ");
    }
    if (!boundary->hasLower()) {
      throw std::runtime_error("Constraint of " + func->parameterName(i) +
                               " must have a lower bound.");
    }
    if (!boundary->hasUpper()) {
      throw std::runtime_error("Constraint of " + func->parameterName(i) +
                               " must have an upper bound.");
    }
    // Use the lower and upper bounds of the constraint to set the range
    // of a generator with uniform distribution.
    ranges.push_back(std::make_pair(boundary->lower(), boundary->upper()));
  }
  // Number of parameters could have changed
  costFunction->reset();
  if (costFunction->nParams() == 0) {
    throw std::runtime_error("No parameters are given for which to estimate "
                             "initial values. Set boundary constraints to "
                             "parameters that need to be estimated.");
  }

  size_t nSamples = static_cast<int>(getProperty("NSamples"));
  unsigned int seed = static_cast<int>(getProperty("Seed"));

  if (getPropertyValue("Type") == "Monte Carlo") {
    int nOutput = getProperty("NOutputs");
    auto outputWorkspaceProp = getPointerToProperty("OutputWorkspace");
    if (outputWorkspaceProp->isDefault() || nOutput <= 0) {
      nOutput = 1;
    }
    auto output = runMonteCarlo(*costFunction, ranges, constraints, nSamples,
                                static_cast<size_t>(nOutput), seed);

    if (!outputWorkspaceProp->isDefault()) {
      auto table = API::WorkspaceFactory::Instance().createTable();
      auto column = table->addColumn("str", "Name");
      column->setPlotType(6);
      for (size_t i = 0; i < output.size(); ++i) {
        column = table->addColumn("double", std::to_string(i + 1));
        column->setPlotType(2);
      }

      for (size_t i = 0, ia = 0; i < m_function->nParams(); ++i) {
        if (m_function->isActive(i)) {
          TableRow row = table->appendRow();
          row << m_function->parameterName(i);
          for (auto &j : output) {
            row << j[ia];
          }
          ++ia;
        }
      }
      setProperty("OutputWorkspace", table);
    }
  } else {
    size_t nSelection = static_cast<int>(getProperty("Selection"));
    size_t nIterations = static_cast<int>(getProperty("NIterations"));
    runCrossEntropy(*costFunction, ranges, constraints, nSamples, nSelection,
                    nIterations, seed);
  }
  bool fixBad = getProperty("FixBadParameters");
  if (fixBad) {
    fixBadParameters(*costFunction, ranges);
  }
}
specUndoCommand* specSpectrumCalculatorAction::generateUndoCommand()
{
	// prepare items
	QList<specModelItem*> items, folders ;
	expandSelectedFolders(items, folders);
	if(items.isEmpty()) return 0 ;  // TODO include this in requirements

	// get formulae
	if(!dialog->exec()) return 0 ;

	// prepare multi command
	specMultiCommand* parentCommand = new specMultiCommand ;
	parentCommand->setParentObject(model) ;
	parentCommand->setMergeable(false) ;

	// prepare the parsers
	mu::Parser xParser, yParser ;
	QString xFormula(dialog->xFormula()), yFormula(dialog->yFormula()) ;
	QStringList xDescriptors(descriptorNames(xFormula)), yDescriptors(descriptorNames(yFormula)) ;
	try
	{
		xParser.DefineOprt("%", modulo, 6);
		yParser.DefineOprt("%", modulo, 6);
		xParser.SetExpr(xFormula.toStdString()) ;
		yParser.SetExpr(yFormula.toStdString()) ;
	}
	catch(...)
	{
		QMessageBox::critical(0, tr("Failed evaluation"), tr("Failed parsing the given formulae.")) ;
		return 0;
	}

	// generate new data
	int failCount = 0 ;
	foreach(specModelItem * item, items)
	{
		size_t count = item->dataSize() ;
		double* oldX = new double[count],
		*oldY = new double[count],
		*newX = new double[count],
		*newY = new double[count];

		for(size_t i = 0 ; i < count ; ++i)
		{
			QPointF point = item->sample(i) ;
			oldX[i] = point.x() ;
			oldY[i] = point.y() ;
		}

		bool evaluationOk = false ;
		QVector<specDataPoint> newData ;
		try
		{
			xParser.ClearVar();
			yParser.ClearVar();
			xParser.ClearConst();
			yParser.ClearConst();

			xParser.DefineVar("x", oldX) ;
			yParser.DefineVar("x", oldX) ;
			xParser.DefineVar("y", oldY) ;
			yParser.DefineVar("y", oldY) ;
			for(int i = 0 ; i < xDescriptors.size() ; ++i)
				xParser.DefineConst(parameterName(i).toStdString(), item->descriptorValue(xDescriptors[i])) ;
			for(int i = 0 ; i < yDescriptors.size() ; ++i)
				yParser.DefineConst(parameterName(i).toStdString(), item->descriptorValue(yDescriptors[i])) ;

			xParser.Eval(newX, count) ;
			yParser.Eval(newY, count) ;

			for(size_t i = 0 ; i < count ; ++i)
				newData << specDataPoint(newX[i], newY[i], 0.) ;
			evaluationOk = true ;
		}
		catch(...) {}

		delete[] oldX ;
		delete[] oldY ;
		delete[] newX ;
		delete[] newY ;

		failCount += !evaluationOk ;

		// prepare the command
		if(evaluationOk)
		{
			if(specDataItem* dataItem = dynamic_cast<specDataItem*>(item))
				dataItem->reverseCorrection(newData) ;
			specExchangeDataCommand* command = new specExchangeDataCommand(parentCommand) ;
			command->setParentObject(model) ;
			command->setItem(item, newData);
		}
	}
Ejemplo n.º 18
0
bool ObjectTypeTemplate::isParameterPrivate(int index) const
{
    const std::string& name = parameterName(index);
    return !name.empty() && name[0] == '_';
}