24 #include <gsl/gsl_errno.h>
34 for (
size_t i = 0; i < detector.
dimension(); ++i)
41 size_t getIndexStep(
size_t total_size,
size_t n_handlers)
45 size_t result = total_size / n_handlers;
46 return total_size % n_handlers ? ++result : result;
49 size_t getStartIndex(
size_t n_handlers,
size_t current_handler,
size_t n_elements)
51 const size_t handler_size = getIndexStep(n_elements,
static_cast<size_t>(n_handlers));
52 const size_t start_index = current_handler * handler_size;
53 if (start_index >= n_elements)
58 size_t getNumberOfElements(
size_t n_handlers,
size_t current_handler,
size_t n_elements)
60 const size_t handler_size = getIndexStep(n_elements,
static_cast<size_t>(n_handlers));
61 const size_t start_index = current_handler * handler_size;
62 if (start_index >= n_elements)
64 return std::min(handler_size, n_elements - start_index);
67 void runComputations(std::vector<std::unique_ptr<IComputation>>& computations)
69 ASSERT(!computations.empty());
71 if (computations.size() == 1) {
72 auto& computation = computations.front();
74 if (computation->isCompleted())
76 std::string message = computation->errorMessage();
77 throw std::runtime_error(
"Error in runComputations: ISimulation has "
78 "terminated unexpectedly with following error: "
86 std::vector<std::unique_ptr<std::thread>> threads;
89 for (
auto& comp : computations)
90 threads.emplace_back(
new std::thread([&comp]() { comp->run(); }));
93 for (
auto& thread : threads)
97 std::vector<std::string> failure_messages;
98 for (
auto& comp : computations)
99 if (!comp->isCompleted())
100 failure_messages.push_back(comp->errorMessage());
102 if (failure_messages.empty())
104 throw std::runtime_error(
"Error in runComputations: "
105 "At least one simulation thread has terminated unexpectedly.\n"
117 : m_instrument(beam, detector)
138 , m_options(other.m_options)
139 , m_progress(other.m_progress)
140 , m_sample_provider(other.m_sample_provider)
141 , m_distribution_handler(other.m_distribution_handler)
142 , m_instrument(other.instrument())
169 if (percentage_done < 100)
170 std::cout << std::setprecision(2) <<
"\r... " << percentage_done <<
"%" << std::flush;
172 std::cout <<
"\r... 100%\n";
186 throw std::runtime_error(
187 "Error in ISimulation::prepareSimulation(): non-default materials of"
188 " several different types are used in the sample provided");
189 gsl_set_error_handler_off();
207 const size_t batch_start = getStartIndex(n_batches, current_batch, total_size);
208 const size_t batch_size = getNumberOfElements(n_batches, current_batch, total_size);
212 if(param_combinations == 1)
216 for (
size_t index = 0; index < param_combinations; ++index) {
256 std::vector<const INode*>
result;
266 double sigma_factor,
const RealLimits& limits)
287 std::vector<std::unique_ptr<IComputation>> computations;
289 for (
size_t i_thread = 0; i_thread < n_threads;
291 const size_t thread_start = batch_start + getStartIndex(n_threads, i_thread, batch_size);
292 const size_t thread_size = getNumberOfElements(n_threads, i_thread, batch_size);
293 if (thread_size == 0)
297 runComputations(computations);
309 bool put_masked_areas_to_zero)
314 if (roi_data->hasSameDimensions(data)) {
316 if (put_masked_areas_to_zero) {
326 }
else if (detHasSameDimensions(
detector(), data)) {
332 !put_masked_areas_to_zero);
335 throw std::runtime_error(
"FitObject::init_dataset() -> Error. Detector and exp data have "
#define ASSERT(condition)
Defines a few helper functions.
Defines interface IBackground.
Defines interface IComputation.
Defines interface ISampleBuilder.
Defines interface ISimulation.
Defines class MPISimulation.
Defines helper functions for MultiLayer objects.
Defines class ParameterPool.
Declares utilities for unit converters.
An incident neutron or x-ray beam.
void addParameterDistribution(const std::string ¶m_name, const IDistribution1D &distribution, size_t nbr_samples, double sigma_factor=0.0, const RealLimits &limits=RealLimits())
add a sampled parameter distribution
double setParameterValues(ParameterPool *p_parameter_pool, size_t index)
set the parameter values of the simulation object to a specific combination of values,...
void setParameterToMeans(ParameterPool *p_parameter_pool) const
Sets mean distribution values to the parameter pool.
size_t getTotalNumberOfSamples() const
get the total number of parameter value combinations (product of the individual sizes of each paramet...
virtual size_t size() const =0
retrieve the number of bins
Interface for a simulating the background signal.
virtual IBackground * clone() const =0
Interface for polymorphic classes that should not be copied, except by explicit cloning.
Abstract detector interface.
size_t dimension() const
Returns actual dimensionality of the detector (number of defined axes)
const IAxis & axis(size_t index) const
void setResolutionFunction(const IResolutionFunction2D &resFunc)
void iterate(std::function< void(const_iterator)> func, bool visit_masks=false) const
Interface for one-dimensional distributions.
Base class for tree-like structures containing parameterized objects.
ParameterPool * createParameterTree() const
Creates new parameter pool, with all local parameters and those of its children.
void registerChild(INode *node)
Interface providing two-dimensional resolution function.
Abstract base class of OffSpecularSimulation, GISASSimulation and SpecularSimulation.
void setSample(const MultiLayer &sample)
The MultiLayer object will not be owned by the ISimulation object.
std::vector< const INode * > getChildren() const
Returns a vector of children.
virtual void updateIntensityMap()
virtual void validateParametrization(const ParameterDistribution &) const
Checks the distribution validity for simulation.
void runSingleSimulation(size_t batch_start, size_t batch_size, double weight=1.0)
Runs a single simulation with fixed parameter values.
virtual size_t numberOfSimulationElements() const =0
Gets the number of elements this simulation needs to calculate.
virtual void addDataToCache(double weight)=0
void setDetectorResolutionFunction(const IResolutionFunction2D &resolution_function)
const MultiLayer * sample() const
void addParameterDistribution(const std::string ¶m_name, const IDistribution1D &distribution, size_t nbr_samples, double sigma_factor=0.0, const RealLimits &limits=RealLimits())
virtual std::unique_ptr< IComputation > generateSingleThreadedComputation(size_t start, size_t n_elements)=0
Generate a single threaded computation for a given range of simulation elements.
SampleProvider m_sample_provider
SimulationResult convertData(const OutputData< double > &data, bool put_masked_areas_to_zero=true)
Convert user data to SimulationResult object for later drawing in various axes units.
void runMPISimulation()
Run a simulation in a MPI environment.
const Instrument & instrument() const
void runSimulation()
Run a simulation, possibly averaged over parameter distributions.
SimulationOptions m_options
void setSampleBuilder(const std::shared_ptr< ISampleBuilder > &sample_builder)
void setInstrument(const Instrument &instrument_)
virtual void moveDataFromCache()=0
virtual void addBackgroundIntensity(size_t start_ind, size_t n_elements)=0
virtual void initSimulationElementVector()=0
Initializes the vector of ISimulation elements.
virtual void prepareSimulation()
Put into a clean state for running a simulation.
virtual SimulationResult result() const =0
Returns the results of the simulation in a format that supports unit conversion and export to numpy a...
std::unique_ptr< IBackground > m_background
void setBackground(const IBackground &bg)
DistributionHandler m_distribution_handler
virtual void normalize(size_t start_ind, size_t n_elements)=0
Normalize the detector counts to beam intensity, to solid angle, and to exposure angle.
ProgressHandler m_progress
void setTerminalProgressMonitor()
Initializes a progress monitor that prints to stdout.
virtual void transferResultsToIntensityMap()
Creates the appropriate data structure (e.g.
Assembles beam, detector and their relative positions with respect to the sample.
void runSimulation(ISimulation *simulation)
Our sample model: a stack of layers one below the other.
size_t rank() const
Returns number of dimensions.
std::vector< T > getRawDataVector() const
Returns copy of raw data vector.
const IAxis & axis(size_t serial_number) const
returns axis with given serial number
A parametric distribution function, for use with any model parameter.
void subscribe(ProgressHandler::Callback_t callback)
void setExpectedNTicks(size_t n)
Limits for a real fit parameter.
void setSample(const MultiLayer &multilayer)
void updateSample()
Generates new sample if sample builder defined.
const MultiLayer * sample() const
Returns current sample.
std::vector< const INode * > getChildren() const override
Returns a vector of children.
void setBuilder(const std::shared_ptr< ISampleBuilder > &sample_builder)
An iterator for SimulationArea.
size_t detectorIndex() const
unsigned getNumberOfBatches() const
unsigned getCurrentBatch() const
unsigned getNumberOfThreads() const
Wrapper around OutputData<double> that also provides unit conversions.
bool ContainsCompatibleMaterials(const MultiLayer &multilayer)
Returns true if the multilayer contains non-default materials of one type only.
std::string join(const std::vector< std::string > &joinable, const std::string &joint)
Returns string obtain by joining vector elements.
std::unique_ptr< IUnitConverter > createConverter(const ISimulation &simulation)
std::unique_ptr< OutputData< double > > createOutputData(const IUnitConverter &converter, Axes::Units units)
Returns zero-valued output data array in specified units.