41void Fit::initConcrete() {
45 "the fitting function.");
48 auto mustBePositive = std::make_shared<Kernel::BoundedValidator<int>>();
49 mustBePositive->setLower(0);
51 "Stop after this number of iterations if a good fit is not found");
56 std::vector<std::string> minimizerOptions = API::FuncMinimizerFactory::Instance().getKeys();
59 declareProperty(
"Minimizer",
"Levenberg-Marquardt", minimizerValidator,
"Minimizer to use for fitting.");
61 std::vector<std::string> costFuncOptions = API::CostFunctionFactory::Instance().getKeys();
63 for (
auto &costFuncOption : costFuncOptions) {
64 auto costFunc = std::dynamic_pointer_cast<CostFunctions::CostFuncFitting>(
65 API::CostFunctionFactory::Instance().
create(costFuncOption));
70 Kernel::IValidator_sptr costFuncValidator = std::make_shared<Kernel::ListValidator<std::string>>(costFuncOptions);
74 "Set to true to create output workspaces with the results of the fit"
75 "(default is false).");
77 "A base name for the output workspaces (if not "
78 "given default names will be created). The "
79 "default is to use the name of the original data workspace as prefix "
80 "followed by suffixes _Workspace, _Parameters, etc.");
82 "Set to true to calcuate errors when output isn't created "
83 "(default is false).");
85 "If true and CreateOutput is true then the value of each "
86 "member of a Composite Function is also output.");
88 "If true and OutputCompositeMembers is true members of any "
89 "Convolution are output convolved\n"
90 "with corresponding resolution");
92 "Set to true to output only the parameters and not "
93 "workspace(s) with the calculated values\n"
94 "(default is false, ignored if CreateOutput is false and "
95 "Output is an empty string).");
96 declareProperty(
"CustomStepSizes", std::vector<double>{},
"Custom step sizes for numerical derivatives.");
98 std::make_unique<Kernel::EnabledWhenProperty>(
102std::map<std::string, std::string> Fit::validateInputs() {
103 std::map<std::string, std::string> issues;
107 if (constraints.size() > 0) {
108 auto operatorPresent =
false;
109 for (
const auto &op : possibleOperators) {
110 const auto it = constraints.find_first_of(op);
111 if (it <= constraints.size()) {
112 operatorPresent =
true;
116 if (!operatorPresent) {
117 issues[
"Constraints"] =
"No operator is present in the constraint.";
122 const std::vector<double> customStepSizes =
getProperty(
"CustomStepSizes");
124 issues[
"CustomStepSizes"] =
"CustomStepSizes must be provided when StepSizeMethod is set to Custom.";
127 issues[
"CustomStepSizes"] =
"CustomStepSizes can only be provided when StepSizeMethod is set to Custom.";
134void Fit::readProperties() {
140 if (!constraints.empty()) {
146 int intMaxIterations =
getProperty(
"MaxIterations");
151 const std::vector<double> customStepSizes =
getProperty(
"CustomStepSizes");
153 if (customStepSizes.size() != nParams) {
154 throw std::invalid_argument(
155 "The 'CustomStepSizes' list must be the same length as the number of parameters. The list should contain " +
158 m_function->setCustomStepSizes(customStepSizes);
159 for (
size_t i = 0; i < nParams; i++) {
160 g_log.
debug() <<
"The step size of " <<
m_function->parameterName(i) <<
" has been set to " << customStepSizes[i]
168void Fit::initializeMinimizer(
size_t maxIterations) {
169 const bool unrollComposites =
getProperty(
"OutputCompositeMembers");
171 if (convolveMembers) {
174 m_domainCreator->separateCompositeMembersInOutput(unrollComposites, convolveMembers);
177 m_minimizer = API::FuncMinimizerFactory::Instance().createMinimizer(minimizerName);
188 for (
auto property : properties) {
190 auto clonedProperty = std::unique_ptr<Kernel::Property>((*property).clone());
198size_t Fit::runMinimizer() {
200 auto prog = std::make_shared<API::Progress>(
this, 0.0, 1.0, nsteps);
205 bool isFinished =
false;
206 g_log.
debug(
"Starting minimizer iteration\n");
208 g_log.
debug() <<
"Starting iteration " << iter <<
"\n";
234 g_log.
debug() <<
"Number of minimizer iterations=" << iter <<
"\n";
240void Fit::finalizeMinimizer(
size_t nIterations) {
244 g_log.
debug() <<
"Iteration stopped. Minimizer status string=" << errorString <<
"\n";
247 if (!errorString.empty()) {
253 if (errorString.empty()) {
261 logStream <<
"Fit status: " << errorString <<
'\n';
262 logStream <<
"Stopped after " << nIterations <<
" iterations" <<
'\n';
267void Fit::createOutput() {
273 double rawcostfuncval =
m_minimizer->costFunctionVal();
274 double finalCostFuncVal = rawcostfuncval / double(dof);
276 setProperty(
"OutputChi2overDoF", finalCostFuncVal);
280 if (!baseName.empty()) {
281 doCreateOutput =
true;
284 if (doCreateOutput) {
288 doCalcErrors =
false;
298 if (doCreateOutput) {
304 if (baseName.empty()) {
305 baseName = ws->getName();
306 if (baseName.empty()) {
314 "The name of the TableWorkspace in which to store the final covariance "
316 setPropertyValue(
"OutputNormalisedCovarianceMatrix", baseName +
"NormalisedCovarianceMatrix");
320 covariance->addColumn(
"str",
"Name");
322 covariance->getColumn(covariance->columnCount() - 1)->setPlotType(6);
323 for (
size_t i = 0; i <
m_function->nParams(); i++) {
325 covariance->addColumn(
"double",
m_function->parameterName(i));
331 for (
size_t i = 0; i < nParams; i++) {
337 for (
size_t j = 0; j < nParams; j++) {
344 throw std::runtime_error(
"There was an error while allocating the covariance "
346 "which is needed to produce fitting error results.");
348 row << 100.0 * covar.
get(ia, ja) / sqrt(covar.
get(ia, ia) * covar.
get(ja, ja));
352 if (ja >= covar.
size2())
357 if (ia >= covar.
size1())
361 setProperty(
"OutputNormalisedCovarianceMatrix", covariance);
368 "The name of the TableWorkspace in which to store the "
369 "final fit parameters");
374 result->addColumn(
"str",
"Name");
376 result->getColumn(result->columnCount() - 1)->setPlotType(6);
377 result->addColumn(
"double",
"Value");
378 result->addColumn(
"double",
"Error");
380 result->getColumn(result->columnCount() - 1)->setPlotType(5);
382 for (
size_t i = 0; i <
m_function->nParams(); i++) {
390 if (costfuncname ==
"Rwp")
391 row <<
"Cost function value" << rawcostfuncval;
393 row <<
"Cost function value" << finalCostFuncVal;
396 bool outputParametersOnly =
getProperty(
"OutputParametersOnly");
398 if (!outputParametersOnly) {
408void Fit::registerMinimizerAndCostFuncUsage() {
409 std::stringstream ss;
421void Fit::execConcrete() {
#define DECLARE_ALGORITHM(classname)
void declareProperty(std::unique_ptr< Kernel::Property > p, const std::string &doc="") override
Add a property to the list of managed properties.
Kernel::Property * getPointerToProperty(const std::string &name) const override
Get a property by name.
bool existsProperty(const std::string &name) const override
Checks whether the named property is already in the list of managed property.
std::string getPropertyValue(const std::string &name) const override
Get the value of a property as a string.
TypedValue getProperty(const std::string &name) const override
Get the value of a property.
bool isChild() const override
To query whether algorithm is a child.
void progress(double p, const std::string &msg="", double estimatedTime=0.0, int progressPrecision=0)
Sends ProgressNotification.
void setPropertyValue(const std::string &name, const std::string &value) override
Set the value of a property by string N.B.
A composite function is a function containing other functions.
static const std::vector< std::string > DEFAULT_OPS_STR
An interface for function minimizers.
TableRow represents a row in a TableWorkspace.
A property class for workspaces.
A generic fitting algorithm.
void finalizeMinimizer(size_t nIterations)
Finalize the minimizer.
std::shared_ptr< CostFunctions::CostFuncFitting > m_costFunction
The cost function.
void copyMinimizerOutput(const API::IFuncMinimizer &minimizer)
Copy all output workspace properties from the minimizer to Fit algorithm.
size_t m_maxIterations
Max number of iterations.
size_t runMinimizer()
Run the minimizer's iteration loop.
void createOutput()
Create algorithm output workspaces.
void registerMinimizerAndCostFuncUsage()
std::shared_ptr< API::IFuncMinimizer > m_minimizer
The minimizer.
void readProperties()
Read in the properties specific to Fit.
void initializeMinimizer(size_t maxIterations)
Initialize the minimizer for this fit.
A wrapper around Eigen::Matrix.
double get(size_t i, size_t j) const
Get an element.
size_t size1() const
First size of the matrix.
size_t size2() const
Second size of the matrix.
const map_type inspector() const
Get a const copy of the Eigen matrix.
A base class for fitting algorithms.
std::shared_ptr< API::IDomainCreator > m_domainCreator
Pointer to a domain creator.
std::shared_ptr< CostFunctions::CostFuncFitting > getCostFunctionInitialized() const
Create a cost function from the "CostFunction" property and make it ready for evaluation.
std::shared_ptr< API::IFunction > m_function
Pointer to the fitting function.
Exception thrown when a fitting function changes number of parameters during fit.
IPropertyManager * setProperty(const std::string &name, const T &value)
Templated method to set the value of a PropertyWithValue.
void setPropertySettings(const std::string &name, std::unique_ptr< IPropertySettings const > settings)
Add a PropertySettings instance to the chain of settings for a given property.
void debug(const std::string &msg)
Logs at debug level.
void notice(const std::string &msg)
Logs at notice level.
void warning(const std::string &msg)
Logs at warning level.
const std::vector< Property * > & getProperties() const override
Get the list of managed properties.
The concrete, templated class for properties.
void setDocumentation(const std::string &documentation)
Sets the user level description of the property.
static T & Instance()
Return a reference to the Singleton instance, creating it if it does not already exist Creation is do...
const std::string SUCCESS
Reported when a minimizer has fully converged.
std::shared_ptr< ITableWorkspace > ITableWorkspace_sptr
shared pointer to Mantid::API::ITableWorkspace
std::shared_ptr< const Workspace > Workspace_const_sptr
shared pointer to Mantid::API::Workspace (const version)
const std::string CUSTOM_STEP_SIZE
std::unique_ptr< T > create(const P &parent, const IndexArg &indexArg, const HistArg &histArg)
This is the create() method that all the other create() methods call.
std::shared_ptr< IValidator > IValidator_sptr
A shared_ptr to an IValidator.
std::string to_string(const wide_integer< Bits, Signed > &n)
@ InOut
Both an input & output workspace.
@ Input
An input workspace.
@ Output
An output workspace.