Mantid
Loading...
Searching...
No Matches
CreateBootstrapWorkspaces.cpp
Go to the documentation of this file.
1// Mantid Repository : https://github.com/mantidproject/mantid
2//
3// Copyright © 2025 ISIS Rutherford Appleton Laboratory UKRI,
4// NScD Oak Ridge National Laboratory, European Spallation Source,
5// Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
6// SPDX - License - Identifier: GPL - 3.0 +
7#include <cmath>
8#include <memory>
9#include <random>
10#include <string>
11
13#include "MantidAPI/Progress.h"
14#include "MantidAPI/Workspace.h"
23
27using namespace Mantid::API;
28
29namespace Mantid::Algorithms {
30
31// Register the algorithm into the AlgorithmFactory
32DECLARE_ALGORITHM(CreateBootstrapWorkspaces)
33
34//----------------------------------------------------------------------------------------------
35
36
37const std::string CreateBootstrapWorkspaces::name() const { return "CreateBootstrapWorkspaces"; }
38
40int CreateBootstrapWorkspaces::version() const { return 1; }
41
43const std::string CreateBootstrapWorkspaces::category() const { return "Simulation"; }
44
46const std::string CreateBootstrapWorkspaces::summary() const {
47 return "Creates a randomly simulated workspace by sampling from the input data.";
48}
49
50//----------------------------------------------------------------------------------------------
54
55 declareProperty(std::make_unique<WorkspaceProperty<MatrixWorkspace>>("InputWorkspace", "", Direction::Input),
56 "Input Workspace containing data to be simulated");
57 declareProperty("Seed", 32, "Integer seed that initialises the random-number generator, for reproducibility");
58
59 auto mustBePositive = std::make_shared<BoundedValidator<int>>();
60 mustBePositive->setLower(1);
61 declareProperty("NumberOfReplicas", 100, mustBePositive, "Number of Bootstrap workspaces to simulate.");
62
63 std::vector<std::string> bootstrapOptions{"ErrorSampling", "SpectraSampling"};
65 "BootstrapType", "ErrorSampling", std::make_shared<StringListValidator>(bootstrapOptions),
66 "Type of bootstrap sampling to use. "
67 "ErrorSampling samples at each data point, while SpectraSampling samples each spectra with repetition.");
68
70 std::make_unique<WorkspaceProperty<WorkspaceGroup>>("OutputWorkspaceGroup", "bootstrap", Direction::Output),
71 "Name of output workspace.");
72}
73
74//----------------------------------------------------------------------------------------------
78
79 auto &ADS = AnalysisDataService::Instance();
80 MatrixWorkspace_sptr inputWs = getProperty("InputWorkspace");
81
82 int inputSeed = getProperty("Seed");
83 std::mt19937 gen(static_cast<unsigned int>(inputSeed));
84
85 int numReplicas = getProperty("NumberOfReplicas");
86 std::string bootType = getProperty("BootstrapType");
87 std::string prefix = getProperty("OutputWorkspaceGroup");
88 Progress progress(this, 0, 1, numReplicas);
89
90 std::vector<std::string> bootNames;
91
92 for (int i = 1; i <= numReplicas; i++) {
93 MatrixWorkspace_sptr bootWs = WorkspaceFactory::Instance().create(inputWs);
94 std::string wsName = prefix + '_' + std::to_string(i);
95 ADS.addOrReplace(wsName, bootWs);
96 bootNames.push_back(std::move(wsName));
97
98 for (size_t index = 0; index < bootWs->getNumberHistograms(); index++) {
99 bootWs->setSharedX(index, inputWs->sharedX(index));
100
101 if (bootType == "ErrorSampling") {
102 bootWs->mutableY(index) = sampleHistogramFromGaussian(inputWs->y(index), inputWs->e(index), gen);
103 bootWs->mutableE(index) = 0;
104
105 } else if (bootType == "SpectraSampling") {
106 // Sample from spectra indices with replacement
107 Kernel::uniform_int_distribution<size_t> dist(0, inputWs->getNumberHistograms() - 1);
108 size_t randomIndex = dist(gen);
109 bootWs->mutableY(index) = inputWs->y(randomIndex);
110 bootWs->mutableE(index) = inputWs->e(randomIndex);
111 }
112 }
113 progress.report("Creating Bootstrap Samples...");
114 }
115 auto alg = createChildAlgorithm("GroupWorkspaces");
116 alg->setProperty("InputWorkspaces", bootNames);
117 alg->executeAsChildAlg();
118 WorkspaceGroup_sptr outputGroup = alg->getProperty("OutputWorkspace");
119 setProperty("OutputWorkspaceGroup", outputGroup);
120}
121
122//----------------------------------------------------------------------------------------------
125HistogramData::HistogramY CreateBootstrapWorkspaces::sampleHistogramFromGaussian(const HistogramData::HistogramY &dataY,
126 const HistogramData::HistogramE &dataE,
127 std::mt19937 &gen) {
128 HistogramData::HistogramY outputY(dataY.size(), 0.0);
129 // For each bin, sample y from Gaussian(y, e)
130 for (size_t index = 0; index < dataY.size(); index++) {
132 outputY[index] = dist(gen);
133 }
134 return outputY;
135}
136} // namespace Mantid::Algorithms
std::string name
Definition Run.cpp:60
#define DECLARE_ALGORITHM(classname)
Definition Algorithm.h:538
std::map< DeltaEMode::Type, std::string > index
void declareProperty(std::unique_ptr< Kernel::Property > p, const std::string &doc="") override
Add a property to the list of managed properties.
TypedValue getProperty(const std::string &name) const override
Get the value of a property.
virtual std::shared_ptr< Algorithm > createChildAlgorithm(const std::string &name, const double startProgress=-1., const double endProgress=-1., const bool enableLogging=true, const int &version=-1)
Create a Child Algorithm.
void progress(double p, const std::string &msg="", double estimatedTime=0.0, int progressPrecision=0)
Sends ProgressNotification.
Helper class for reporting progress from algorithms.
Definition Progress.h:25
A property class for workspaces.
CreateBootstrapWorkspaces: The algorithm generates several simulated workspaces by sampling randomly ...
void init() override
Initialize the algorithm's properties.
static HistogramData::HistogramY sampleHistogramFromGaussian(const HistogramData::HistogramY &dataY, const HistogramData::HistogramE &dataE, std::mt19937 &gen)
Helpers.
const std::string category() const override
Algorithm's category for identification.
int version() const override
Algorithm's version for identification.
const std::string summary() const override
Algorithm's summary for use in the GUI and help.
BoundedValidator is a validator that requires the values to be between upper or lower bounds,...
IPropertyManager * setProperty(const std::string &name, const T &value)
Templated method to set the value of a PropertyWithValue.
ListValidator is a validator that requires the value of a property to be one of a defined list of pos...
static T & Instance()
Return a reference to the Singleton instance, creating it if it does not already exist Creation is do...
std::shared_ptr< WorkspaceGroup > WorkspaceGroup_sptr
shared pointer to Mantid::API::WorkspaceGroup
std::shared_ptr< MatrixWorkspace > MatrixWorkspace_sptr
shared pointer to the matrix workspace base class
STL namespace.
std::string to_string(const wide_integer< Bits, Signed > &n)
Describes the direction (within an algorithm) of a Property.
Definition Property.h:50
@ Input
An input workspace.
Definition Property.h:53
@ Output
An output workspace.
Definition Property.h:54