39void Fit::initConcrete() {
43 "the fitting function.");
46 auto mustBePositive = std::make_shared<Kernel::BoundedValidator<int>>();
47 mustBePositive->setLower(0);
49 "Stop after this number of iterations if a good fit is not found");
54 std::vector<std::string> minimizerOptions = API::FuncMinimizerFactory::Instance().getKeys();
57 declareProperty(
"Minimizer",
"Levenberg-Marquardt", minimizerValidator,
"Minimizer to use for fitting.");
59 std::vector<std::string> costFuncOptions = API::CostFunctionFactory::Instance().getKeys();
61 for (
auto &costFuncOption : costFuncOptions) {
62 auto costFunc = std::dynamic_pointer_cast<CostFunctions::CostFuncFitting>(
63 API::CostFunctionFactory::Instance().
create(costFuncOption));
68 Kernel::IValidator_sptr costFuncValidator = std::make_shared<Kernel::ListValidator<std::string>>(costFuncOptions);
72 "Set to true to create output workspaces with the results of the fit"
73 "(default is false).");
75 "A base name for the output workspaces (if not "
76 "given default names will be created). The "
77 "default is to use the name of the original data workspace as prefix "
78 "followed by suffixes _Workspace, _Parameters, etc.");
80 "Set to true to calcuate errors when output isn't created "
81 "(default is false).");
83 "If true and CreateOutput is true then the value of each "
84 "member of a Composite Function is also output.");
86 "If true and OutputCompositeMembers is true members of any "
87 "Convolution are output convolved\n"
88 "with corresponding resolution");
90 "Set to true to output only the parameters and not "
91 "workspace(s) with the calculated values\n"
92 "(default is false, ignored if CreateOutput is false and "
93 "Output is an empty string).");
96std::map<std::string, std::string> Fit::validateInputs() {
97 std::map<std::string, std::string> issues;
101 if (constraints.size() > 0) {
102 auto operatorPresent =
false;
103 for (
const auto &op : possibleOperators) {
104 const auto it = constraints.find_first_of(op);
105 if (it <= constraints.size()) {
106 operatorPresent =
true;
110 if (!operatorPresent) {
111 issues[
"Constraints"] =
"No operator is present in the constraint.";
119void Fit::readProperties() {
125 if (!constraints.empty()) {
131 int intMaxIterations =
getProperty(
"MaxIterations");
137void Fit::initializeMinimizer(
size_t maxIterations) {
138 const bool unrollComposites =
getProperty(
"OutputCompositeMembers");
140 if (convolveMembers) {
143 m_domainCreator->separateCompositeMembersInOutput(unrollComposites, convolveMembers);
146 m_minimizer = API::FuncMinimizerFactory::Instance().createMinimizer(minimizerName);
157 for (
auto property : properties) {
159 auto clonedProperty = std::unique_ptr<Kernel::Property>((*property).clone());
167size_t Fit::runMinimizer() {
169 auto prog = std::make_shared<API::Progress>(
this, 0.0, 1.0, nsteps);
174 bool isFinished =
false;
175 g_log.
debug(
"Starting minimizer iteration\n");
177 g_log.
debug() <<
"Starting iteration " << iter <<
"\n";
203 g_log.
debug() <<
"Number of minimizer iterations=" << iter <<
"\n";
209void Fit::finalizeMinimizer(
size_t nIterations) {
213 g_log.
debug() <<
"Iteration stopped. Minimizer status string=" << errorString <<
"\n";
216 if (!errorString.empty()) {
222 if (errorString.empty()) {
223 errorString =
"success";
230 logStream <<
"Fit status: " << errorString <<
'\n';
231 logStream <<
"Stopped after " << nIterations <<
" iterations" <<
'\n';
236void Fit::createOutput() {
242 double rawcostfuncval =
m_minimizer->costFunctionVal();
243 double finalCostFuncVal = rawcostfuncval / double(dof);
245 setProperty(
"OutputChi2overDoF", finalCostFuncVal);
249 if (!baseName.empty()) {
250 doCreateOutput =
true;
253 if (doCreateOutput) {
257 doCalcErrors =
false;
267 if (doCreateOutput) {
273 if (baseName.empty()) {
274 baseName = ws->getName();
275 if (baseName.empty()) {
283 "The name of the TableWorkspace in which to store the final covariance "
285 setPropertyValue(
"OutputNormalisedCovarianceMatrix", baseName +
"NormalisedCovarianceMatrix");
289 covariance->addColumn(
"str",
"Name");
291 covariance->getColumn(covariance->columnCount() - 1)->setPlotType(6);
292 for (
size_t i = 0; i <
m_function->nParams(); i++) {
294 covariance->addColumn(
"double",
m_function->parameterName(i));
300 for (
size_t i = 0; i < np; i++) {
306 for (
size_t j = 0; j < np; j++) {
313 throw std::runtime_error(
"There was an error while allocating the covariance "
315 "which is needed to produce fitting error results.");
317 row << 100.0 * covar.
get(ia, ja) / sqrt(covar.
get(ia, ia) * covar.
get(ja, ja));
321 if (ja >= covar.
size2())
326 if (ia >= covar.
size1())
330 setProperty(
"OutputNormalisedCovarianceMatrix", covariance);
337 "The name of the TableWorkspace in which to store the "
338 "final fit parameters");
343 result->addColumn(
"str",
"Name");
345 result->getColumn(result->columnCount() - 1)->setPlotType(6);
346 result->addColumn(
"double",
"Value");
347 result->addColumn(
"double",
"Error");
349 result->getColumn(result->columnCount() - 1)->setPlotType(5);
351 for (
size_t i = 0; i <
m_function->nParams(); i++) {
359 if (costfuncname ==
"Rwp")
360 row <<
"Cost function value" << rawcostfuncval;
362 row <<
"Cost function value" << finalCostFuncVal;
365 bool outputParametersOnly =
getProperty(
"OutputParametersOnly");
367 if (!outputParametersOnly) {
377void Fit::registerMinimizerAndCostFuncUsage() {
378 std::stringstream ss;
390void 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 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...
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)
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.