Mantid
Loading...
Searching...
No Matches
Algorithm.h
Go to the documentation of this file.
1// Mantid Repository : https://github.com/mantidproject/mantid
2//
3// Copyright © 2007 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#pragma once
8
9#include <atomic>
10#include <memory>
11
12#include "MantidAPI/DllConfig.h"
16#include "MantidTypes/Core/DateAndTime.h"
17
18// -- These headers will (most-likely) be used by every inheriting algorithm
19#include "MantidAPI/AlgorithmFactory.h" //for the factory macro
20#include "MantidAPI/Progress.h"
23
24namespace Poco {
25template <class R, class A, class O, class S> class ActiveMethod;
26template <class O> class ActiveStarter;
27class NotificationCenter;
28template <class C, class N> class NObserver;
29class Void;
30} // namespace Poco
31
32namespace Json {
33class Value;
34}
35
36namespace Mantid {
37namespace Kernel {
38// this is declared in MantidKernel/Timer.h
39using time_point_ns = std::chrono::time_point<std::chrono::high_resolution_clock>;
40} // namespace Kernel
41namespace Indexing {
42class SpectrumIndexSet;
43}
44namespace API {
45//----------------------------------------------------------------------
46// Forward Declaration
47//----------------------------------------------------------------------
48class AlgorithmHistory;
49class WorkspaceHistory;
50
52using Algorithm_sptr = std::shared_ptr<Algorithm>;
53
76class MANTID_API_DLL Algorithm : public IAlgorithm {
77public:
79 class MANTID_API_DLL AlgorithmNotification : public Poco::Notification {
80 public:
81 AlgorithmNotification(const Algorithm *const alg);
82 const IAlgorithm *algorithm() const;
83
84 private:
85 const IAlgorithm *const m_algorithm;
86 };
87
89 class MANTID_API_DLL StartedNotification : public AlgorithmNotification {
90 public:
91 StartedNotification(const Algorithm *const alg);
92 std::string name() const override;
93 };
94
96 class MANTID_API_DLL FinishedNotification : public AlgorithmNotification {
97 public:
98 FinishedNotification(const Algorithm *const alg, bool res);
99 std::string name() const override;
100 bool success;
102 };
103
106 class MANTID_API_DLL ProgressNotification : public AlgorithmNotification {
107 public:
109 ProgressNotification(const Algorithm *const alg, double p, std::string msg, double estimatedTime,
110 int progressPrecision);
111 std::string name() const override;
112 double progress;
113 std::string message;
117 };
118
121 class MANTID_API_DLL ErrorNotification : public AlgorithmNotification {
122 public:
124 ErrorNotification(const Algorithm *const alg, std::string str);
125 std::string name() const override;
126 std::string what;
127 };
128
136 class MANTID_API_DLL CancelException : public std::exception {
137 public:
139 const char *what() const noexcept override;
140 };
141
142 //============================================================================
143 Algorithm();
144 Algorithm(const Algorithm &) = delete;
145 Algorithm &operator=(const Algorithm &) = delete;
146 ~Algorithm() override;
147
151 const std::string name() const override = 0;
154 int version() const override = 0;
157 const std::string summary() const override = 0;
160 const std::string category() const override { return "Misc"; }
162 const std::vector<std::string> categories() const override;
165 const std::string categorySeparator() const override { return ";"; }
168 const std::vector<std::string> seeAlso() const override { return {}; };
170 const std::string alias() const override { return ""; }
172 bool calledByAlias = false;
173
175 const std::string aliasDeprecated() const override { return ""; }
176
180 const std::string helpURL() const override { return ""; }
181
182 template <typename T, typename = typename std::enable_if<std::is_convertible<T *, MatrixWorkspace *>::value>::type>
183 std::tuple<std::shared_ptr<T>, Indexing::SpectrumIndexSet> getWorkspaceAndIndices(const std::string &name) const;
184
185 template <typename T1, typename T2,
186 typename = typename std::enable_if<std::is_convertible<T1 *, MatrixWorkspace *>::value>::type,
187 typename = typename std::enable_if<std::is_convertible<T2 *, std::string *>::value ||
188 std::is_convertible<T2 *, std::vector<int64_t> *>::value>::type>
189 void setWorkspaceInputProperties(const std::string &name, const std::shared_ptr<T1> &wksp, IndexType type,
190 const T2 &list);
191
192 template <typename T1, typename T2,
193 typename = typename std::enable_if<std::is_convertible<T1 *, MatrixWorkspace *>::value>::type,
194 typename = typename std::enable_if<std::is_convertible<T2 *, std::string *>::value ||
195 std::is_convertible<T2 *, std::vector<int64_t> *>::value>::type>
196 void setWorkspaceInputProperties(const std::string &name, const std::string &wsName, IndexType type, const T2 &list);
197
198 const std::string workspaceMethodName() const override;
199 const std::vector<std::string> workspaceMethodOn() const override;
200 const std::string workspaceMethodInputProperty() const override;
201
204 AlgorithmID getAlgorithmID() const override { return m_algorithmID; }
205
207 void initialize() override;
208 bool execute() override final;
209 void addTimer(const std::string &name, const Kernel::time_point_ns &begin, const Kernel::time_point_ns &end);
210 void executeAsChildAlg() override;
211 std::map<std::string, std::string> validateInputs() override;
212
214 ExecutionState executionState() const override;
216 ResultState resultState() const override;
217 bool isInitialized() const override;
218 bool isExecuted() const override;
219 bool isRunning() const override;
220 bool isReadyForGarbageCollection() const override;
221
222 bool isChild() const override;
223 void setChild(const bool isChild) override;
224 void enableHistoryRecordingForChild(const bool on) override;
225 bool isRecordingHistoryForChild() { return m_recordHistoryForChild; }
226 void setAlwaysStoreInADS(const bool doStore) override;
227 bool getAlwaysStoreInADS() const override;
228 void setRethrows(const bool rethrow) override;
229
231 Poco::ActiveResult<bool> executeAsync() override;
232
234 void addObserver(const Poco::AbstractObserver &observer) const override;
235
237 void removeObserver(const Poco::AbstractObserver &observer) const override;
238
240 void cancel() override;
241 bool getCancel() const;
242
243 Kernel::Logger &getLogger() const;
244 void setLogging(const bool value) override;
245 bool isLogging() const override;
246 void setLoggingOffset(const int value) override;
247 int getLoggingOffset() const override;
249 void setAlgStartupLogging(const bool enabled) override;
251 bool getAlgStartupLogging() const override;
252
254 void setChildStartProgress(const double startProgress) const override { m_startChildProgress = startProgress; }
256 void setChildEndProgress(const double endProgress) const override { m_endChildProgress = endProgress; }
257
261 std::string toString() const override;
263 ::Json::Value toJson() const override;
265 static IAlgorithm_sptr fromString(const std::string &input);
267 static IAlgorithm_sptr fromJson(const Json::Value &input);
269 static IAlgorithm_sptr fromHistory(const AlgorithmHistory &history);
271
272 virtual std::shared_ptr<Algorithm> createChildAlgorithm(const std::string &name, const double startProgress = -1.,
273 const double endProgress = -1.,
274 const bool enableLogging = true, const int &version = -1);
275 void setupAsChildAlgorithm(const Algorithm_sptr &algorithm, const double startProgress = -1.,
276 const double endProgress = -1., const bool enableLogging = true);
277
280 void trackAlgorithmHistory(std::shared_ptr<AlgorithmHistory> parentHist);
281
282 using WorkspaceVector = std::vector<std::shared_ptr<Workspace>>;
283
284 void findWorkspaces(WorkspaceVector &workspaces, unsigned int direction, bool checkADS = false) const;
285
286 // ------------------ For WorkspaceGroups ------------------------------------
287 virtual bool checkGroups();
288
289 virtual bool processGroups();
290
291 void copyNonWorkspaceProperties(IAlgorithm *alg, int periodNum);
292
293 // Function to declare properties (i.e. store them)
294 void declareProperty(std::unique_ptr<Kernel::Property> p, const std::string &doc = "") override;
295
296 // Function to declare properties (i.e. store them)
297 void declareOrReplaceProperty(std::unique_ptr<Kernel::Property> p, const std::string &doc = "") override;
298 void resetProperties() override;
299 using IPropertyManager::declareProperty;
300 // Sets all the declared properties from
301 void setProperties(const std::string &propertiesJson,
302 const std::unordered_set<std::string> &ignoreProperties = std::unordered_set<std::string>(),
303 bool createMissing = false) override;
304
305 // Sets all the declared properties from a json object
306 void setProperties(const ::Json::Value &jsonValue,
307 const std::unordered_set<std::string> &ignoreProperties = std::unordered_set<std::string>(),
308 bool createMissing = false) override;
309
310 // sets all the declared properties using a simple string format
311 void setPropertiesWithString(
312 const std::string &propertiesString,
313 const std::unordered_set<std::string> &ignoreProperties = std::unordered_set<std::string>()) override;
314
315 void setPropertyValue(const std::string &name, const std::string &value) override;
316 void setPropertyValueFromJson(const std::string &name, const Json::Value &value) override;
317 void setPropertyOrdinal(const int &index, const std::string &value) override;
318
320 virtual void copyPropertiesFrom(const Algorithm &alg) { m_properties.copyPropertiesFrom(alg.m_properties); }
321
322 bool existsProperty(const std::string &name) const override;
323 bool validateProperties() const override;
324 size_t propertyCount() const override;
325
326 std::string getPropertyValue(const std::string &name) const override;
327 const std::vector<Kernel::Property *> &getProperties() const override;
328 std::vector<std::string> getDeclaredPropertyNames() const noexcept override;
329
331 TypedValue getProperty(const std::string &name) const override;
332
334 std::string asString(bool withDefaultValues = false) const override;
335
337 ::Json::Value asJson(bool withDefaultValues = false) const override;
338
339 bool isDefault(const std::string &name) const;
340
342 void removeProperty(const std::string &name, const bool delproperty = true) override;
344 std::unique_ptr<Kernel::Property> takeProperty(const size_t index) override;
345
347 void clear() override;
351 void afterPropertySet(const std::string &) override;
352
353 Kernel::Property *getPointerToProperty(const std::string &name) const override;
354 Kernel::Property *getPointerToPropertyOrdinal(const int &index) const override;
355
356protected:
358 virtual void init() = 0;
360 virtual void exec() = 0;
361
364 virtual const std::string workspaceMethodOnTypes() const { return ""; }
365
366 void cacheWorkspaceProperties();
367 void cacheInputWorkspaceHistories();
368
369 void setExecutionState(const ExecutionState state);
370 void setResultState(const ResultState state);
371
372 void store();
373
375 friend class Progress;
376 void progress(double p, const std::string &msg = "", double estimatedTime = 0.0, int progressPrecision = 0);
377 void interruption_point();
378
380 Poco::NotificationCenter &notificationCenter() const;
381
384 void handleChildProgressNotification(const Poco::AutoPtr<ProgressNotification> &pNf);
386 const Poco::AbstractObserver &progressObserver() const;
387
390 template <typename NumT> static bool isEmpty(const NumT toCheck);
391
393 bool isWorkspaceProperty(const Kernel::Property *const prop) const;
394
396 bool trackingHistory();
399 virtual void fillHistory();
401 void fillHistory(const std::vector<Workspace_sptr> &outputWorkspaces);
402
404 std::atomic<bool> m_cancel;
406 std::atomic<bool> m_parallelException;
407
408 friend class WorkspaceHistory; // Allow workspace history loading to adjust
409 // g_execCount
410 static size_t g_execCount;
411
412 virtual void setOtherProperties(IAlgorithm *alg, const std::string &propertyName, const std::string &propertyValue,
413 int periodNum);
414
416 std::vector<IWorkspaceProperty *> m_inputWorkspaceProps;
418 std::shared_ptr<AlgorithmHistory> m_history;
419
423
425 std::shared_ptr<AlgorithmHistory> m_parentHistory;
426
429 std::vector<WorkspaceVector> m_unrolledInputWorkspaces;
434 bool m_usingBaseProcessGroups = false;
435
436 template <typename T, const int AllowedIndexTypes = static_cast<int>(IndexType::WorkspaceIndex),
437 typename... WSPropArgs,
438 typename = typename std::enable_if<std::is_convertible<T *, MatrixWorkspace *>::value>::type>
439 void declareWorkspaceInputProperties(const std::string &propertyName, const std::string &doc,
440 WSPropArgs &&...wsPropArgs);
441
442private:
443 template <typename T1, typename T2, typename WsType>
444 void doSetInputProperties(const std::string &name, const T1 &wksp, IndexType type, const T2 &list);
445 void lockWorkspaces();
446
447 void unlockWorkspaces();
448
449 void clearWorkspaceCaches();
450
451 void linkHistoryWithLastChild();
452
453 void logAlgorithmInfo() const;
454
455 bool executeInternal();
456
457 bool executeAsyncImpl(const Poco::Void &i);
458
459 bool doCallProcessGroups(Mantid::Types::Core::DateAndTime &start_time);
460
461 // Report that the algorithm has completed.
462 void reportCompleted(const double &duration, const bool groupProcessing = false);
463
464 void registerFeatureUsage() const;
465
466 bool isCompoundProperty(const std::string &name) const;
467
468 // --------------------- Private Members -----------------------------------
470 std::unique_ptr<Poco::ActiveMethod<bool, Poco::Void, Algorithm, Poco::ActiveStarter<Algorithm>>> m_executeAsync;
471
475 mutable std::unique_ptr<Poco::NotificationCenter> m_notificationCenter;
477 mutable std::unique_ptr<Poco::NObserver<Algorithm, ProgressNotification>> m_progressObserver;
478
479 std::atomic<ExecutionState> m_executionState;
480 std::atomic<ResultState> m_resultState;
490 mutable double m_startChildProgress;
492 mutable double m_endChildProgress;
495 std::vector<std::weak_ptr<IAlgorithm>> m_ChildAlgorithms;
500
505
507 std::vector<IWorkspaceProperty *> m_outputWorkspaceProps;
509 std::vector<IWorkspaceProperty *> m_pureOutputWorkspaceProps;
510
512 std::vector<std::shared_ptr<WorkspaceGroup>> m_groupWorkspaces;
519 std::vector<Workspace_sptr> m_inputWorkspaceHistories;
520
522 std::vector<std::string> m_reservedList;
523
525 Mantid::Types::Core::DateAndTime m_gcTime;
526
528};
529
530} // namespace API
531} // namespace Mantid
532
533/* Used to register classes into the factory. creates a global object in an
534 * anonymous namespace. The object itself does nothing, but the comma operator
535 * is used in the call to its constructor to effect a call to the factory's
536 * subscribe method.
537 */
538#define DECLARE_ALGORITHM(classname) \
539 namespace { \
540 Mantid::Kernel::RegistrationHelper \
541 register_alg_##classname(((Mantid::API::AlgorithmFactory::Instance().subscribe<classname>()), 0)); \
542 }
std::string name
Definition Run.cpp:60
double value
The value of the point.
Definition FitMW.cpp:51
std::map< DeltaEMode::Type, std::string > index
std::vector< history_type > history
history information
This class stores information about the Command History used by algorithms on a workspace.
Base class for algorithm notifications.
Definition Algorithm.h:79
const IAlgorithm *const m_algorithm
The algorithm.
Definition Algorithm.h:85
CancelException is thrown to cancel execution of the algorithm.
Definition Algorithm.h:136
ErrorNotification is sent when an exception is caught during execution of the algorithm.
Definition Algorithm.h:121
FinishedNotification is sent after the algorithm finishes its execution.
Definition Algorithm.h:96
bool success
true if the finished algorithm was successful or false if it failed.
Definition Algorithm.h:100
An algorithm can report its progress by sending ProgressNotification.
Definition Algorithm.h:106
double estimatedTime
Estimated time to completion.
Definition Algorithm.h:114
double progress
Current progress. Value must be between 0 and 1.
Definition Algorithm.h:112
int progressPrecision
Digits of precision to the progress (after the decimal).
Definition Algorithm.h:115
std::string message
Message sent with notification.
Definition Algorithm.h:113
StartedNotification is sent when the algorithm begins execution.
Definition Algorithm.h:89
Base class from which all concrete algorithm classes should be derived.
Definition Algorithm.h:76
const std::string categorySeparator() const override
Function to return the separator token for the category string.
Definition Algorithm.h:165
std::vector< std::shared_ptr< WorkspaceGroup > > m_groupWorkspaces
Pointer to the WorkspaceGroup (if any) for each input workspace property.
Definition Algorithm.h:512
std::vector< Workspace_sptr > m_inputWorkspaceHistories
Store a pointer to the input workspace histories so they can be copied to the outputs to avoid anythi...
Definition Algorithm.h:519
AlgorithmID m_algorithmID
Algorithm ID for managed algorithms.
Definition Algorithm.h:494
std::unique_ptr< Poco::NObserver< Algorithm, ProgressNotification > > m_progressObserver
Child algorithm progress observer.
Definition Algorithm.h:477
std::vector< std::string > m_reservedList
Reserved property names.
Definition Algorithm.h:522
AlgorithmID getAlgorithmID() const override
Algorithm ID.
Definition Algorithm.h:204
int m_singleGroup
If only one input is a group, this is its index. -1 if they are all groups.
Definition Algorithm.h:514
std::vector< IWorkspaceProperty * > m_inputWorkspaceProps
All the WorkspaceProperties that are Input or InOut. Set in execute()
Definition Algorithm.h:416
void setChildEndProgress(const double endProgress) const override
setting the child end progress
Definition Algorithm.h:256
WorkspaceVector m_writeLockedWorkspaces
Vector of all the workspaces that have been write-locked.
Definition Algorithm.h:504
bool m_rethrow
Algorithm should rethrow exceptions while executing.
Definition Algorithm.h:486
double m_startChildProgress
Whether to log alg startup and closedown messages from the base class (default = true)
Definition Algorithm.h:490
const std::string aliasDeprecated() const override
Expiration date (in ISO8601 format) for the algorithm aliases; default implementation for no expirati...
Definition Algorithm.h:175
std::vector< std::weak_ptr< IAlgorithm > > m_ChildAlgorithms
A list of weak pointers to any child algorithms created.
Definition Algorithm.h:495
std::atomic< bool > m_cancel
Set to true to stop execution.
Definition Algorithm.h:404
std::shared_ptr< AlgorithmHistory > m_parentHistory
Pointer to the parent history object (if set)
Definition Algorithm.h:425
Algorithm(const Algorithm &)=delete
std::shared_ptr< AlgorithmHistory > m_history
Pointer to the history for the algorithm being executed.
Definition Algorithm.h:418
std::vector< IWorkspaceProperty * > m_outputWorkspaceProps
All the WorkspaceProperties that are Output or InOut. Set in execute()
Definition Algorithm.h:507
std::vector< IWorkspaceProperty * > m_pureOutputWorkspaceProps
All the WorkspaceProperties that are Output (not inOut). Set in execute()
Definition Algorithm.h:509
virtual void copyPropertiesFrom(const Algorithm &alg)
Make m_properties point to the same PropertyManager as alg.m_properties.
Definition Algorithm.h:320
size_t m_groupSize
Size of the group(s) being processed.
Definition Algorithm.h:431
std::atomic< bool > m_parallelException
Set if an exception is thrown, and not caught, within a parallel region.
Definition Algorithm.h:406
WorkspaceVector m_readLockedWorkspaces
Vector of all the workspaces that have been read-locked.
Definition Algorithm.h:502
Kernel::Logger & g_log
Definition Algorithm.h:422
std::vector< std::shared_ptr< Workspace > > WorkspaceVector
Definition Algorithm.h:282
void setChildStartProgress(const double startProgress) const override
setting the child start progress
Definition Algorithm.h:254
bool m_alwaysStoreInADS
Always store in the ADS, even for child algos.
Definition Algorithm.h:484
std::atomic< ResultState > m_resultState
the current result State
Definition Algorithm.h:480
const std::string alias() const override
function to return any aliases to the algorithm; A default implementation is provided
Definition Algorithm.h:170
std::unique_ptr< Poco::ActiveMethod< bool, Poco::Void, Algorithm, Poco::ActiveStarter< Algorithm > > > m_executeAsync
Poco::ActiveMethod used to implement asynchronous execution.
Definition Algorithm.h:470
Algorithm & operator=(const Algorithm &)=delete
std::vector< WorkspaceVector > m_unrolledInputWorkspaces
One vector of workspaces for each input workspace property.
Definition Algorithm.h:429
bool m_isChildAlgorithm
Algorithm is a child algorithm.
Definition Algorithm.h:481
Mantid::Kernel::PropertyManagerOwner m_properties
Definition Algorithm.h:527
const std::string category() const override
function to return a category of the algorithm.
Definition Algorithm.h:160
~Algorithm() override
Virtual destructor.
bool m_runningAsync
Algorithm is running asynchronously.
Definition Algorithm.h:485
const std::string helpURL() const override
function to return URL for algorithm documentation; A default implementation is provided.
Definition Algorithm.h:180
int version() const override=0
function to return a version of the algorithm, must be overridden in all algorithms
std::atomic< ExecutionState > m_executionState
the current execution state
Definition Algorithm.h:479
static bool isEmpty(const NumT toCheck)
checks that the value was not set by users, uses the value in empty double/int.
const std::vector< std::string > seeAlso() const override
Function to return all of the seeAlso (these are not validated) algorithms related to this algorithm....
Definition Algorithm.h:168
bool m_groupsHaveSimilarNames
All the groups have similar names (group_1, group_2 etc.)
Definition Algorithm.h:516
const std::string summary() const override=0
function returns a summary message that will be displayed in the default GUI, and in the help.
double m_endChildProgress
Keeps value for algorithm's progress at Child Algorithm's finish.
Definition Algorithm.h:492
Mantid::Types::Core::DateAndTime m_gcTime
The earliest this class should be considered for garbage collection.
Definition Algorithm.h:525
std::unique_ptr< Poco::NotificationCenter > m_notificationCenter
Sends notifications to observers.
Definition Algorithm.h:475
Kernel::Logger m_log
Logger for this algorithm.
Definition Algorithm.h:421
static size_t g_execCount
Counter to keep track of algorithm execution order.
Definition Algorithm.h:410
bool m_recordHistoryForChild
Flag to indicate whether history should be recorded.
Definition Algorithm.h:482
const std::string name() const override=0
function to return a name of the algorithm, must be overridden in all algorithms
IAlgorithm is the interface implemented by the Algorithm base class.
Definition IAlgorithm.h:45
Helper class for reporting progress from algorithms.
Definition Progress.h:25
This class stores information about the Workspace History used by algorithms on a workspace and the e...
The Logger class is in charge of the publishing messages from the framework through various channels.
Definition Logger.h:51
Kernel/PropertyManagerOwner.h.
Base class for properties.
Definition Property.h:94
std::shared_ptr< IAlgorithm > IAlgorithm_sptr
shared pointer to Mantid::API::IAlgorithm
ResultState
The validity of the results of the algorithm object.
Definition IAlgorithm.h:33
ExecutionState
The current state of the algorithm object.
Definition IAlgorithm.h:31
void * AlgorithmID
As we have multiple interfaces to the same logical algorithm we need a way of uniquely identifying ma...
Definition IAlgorithm.h:28
std::shared_ptr< Algorithm > Algorithm_sptr
Typedef for a shared pointer to an Algorithm.
Definition Algorithm.h:52
std::chrono::time_point< std::chrono::high_resolution_clock > time_point_ns
Definition Algorithm.h:39
std::string toString(const T &value)
Convert values to strings.
Helper class which provides the Collimation Length for SANS instruments.
STL namespace.