18#include "MantidJson/Json.h"
28#include "MantidParallel/Communicator.h"
31#include <Poco/ActiveMethod.h>
32#include <Poco/ActiveResult.h>
33#include <Poco/NotificationCenter.h>
34#include <Poco/RWLock.h>
46#include "MantidAPI/Algorithm.tcc"
54const std::string WORKSPACE_TYPES_SEPARATOR =
";";
58const size_t DELAY_BEFORE_GC = 5;
60class WorkspacePropertyValueIs {
64 auto *prop =
dynamic_cast<Property *
>(property);
74template <
typename T>
struct RunOnFinish {
75 RunOnFinish(T &&task) :
m_onfinsh(std::move(task)) {}
89 return static_cast<int>(toCheck) ==
EMPTY_INT();
97template MANTID_API_DLL
bool Algorithm::isEmpty<int>(
const int);
98template MANTID_API_DLL
bool Algorithm::isEmpty<int64_t>(
const int64_t);
99template MANTID_API_DLL
bool Algorithm::isEmpty<std::size_t>(
const std::size_t);
112 : m_cancel(false), m_parallelException(false), m_log(
"Algorithm"),
g_log(m_log), m_groupSize(0),
113 m_executeAsync(nullptr), m_notificationCenter(nullptr), m_progressObserver(nullptr),
115 m_isChildAlgorithm(false), m_recordHistoryForChild(false), m_alwaysStoreInADS(true), m_runningAsync(false),
116 m_rethrow(false), m_isAlgStartupLoggingEnabled(true), m_startChildProgress(0.), m_endChildProgress(0.),
117 m_algorithmID(this), m_singleGroup(-1), m_groupsHaveSimilarNames(false), m_inputWorkspaceHistories(),
118 m_communicator(
std::make_unique<Parallel::Communicator>()), m_properties() {}
201 (Mantid::Types::Core::DateAndTime::getCurrentTime() >
m_gcTime)) {
245 if (depo !=
nullptr) {
246 res.emplace_back(
"Deprecated");
294 }
catch (std::runtime_error &) {
301 }
catch (std::runtime_error &) {
336 for (
const auto &prop : props) {
340 switch (prop->direction()) {
353 throw std::logic_error(
"Unexpected property direction found for property " + prop->name() +
" of algorithm " +
368 if (
auto group =
dynamic_cast<const WorkspaceGroup *
>(ws.get())) {
393 for (
const auto &prop : props) {
398 if (
auto ws = wsProp->getWorkspace()) {
403 wsFromADS = ads.retrieve(prop->value());
407 cacheHistories(wsFromADS);
409 }
else if (
auto strArrayProp =
dynamic_cast<ArrayPropertyString *
>(prop)) {
410 if (!isADSValidator(strArrayProp->getValidator()))
412 const auto &wsNames((*strArrayProp)());
413 for (
const auto &
name : wsNames) {
414 cacheHistories(ads.retrieve(
name));
431 throw std::logic_error(
"Algorithm::lockWorkspaces(): The workspaces have "
432 "already been locked!");
444 debugLog <<
"Write-locking " << ws->getName() <<
'\n';
445 ws->getLock()->writeLock();
460 debugLog <<
"Read-locking " << ws->getName() <<
'\n';
461 ws->getLock()->readLock();
479 debugLog <<
"Unlocking " << ws->getName() <<
'\n';
480 ws->getLock()->unlock();
485 debugLog <<
"Unlocking " << ws->getName() <<
'\n';
486 ws->getLock()->unlock();
514 bool algIsExecuted =
false;
537 Mantid::Types::Core::DateAndTime startTime;
541 throw std::runtime_error(
"Algorithm is not initialised:" + this->
name());
549 constexpr bool resetTimer{
true};
550 float timingInit = timer.
elapsed(resetTimer);
554 for (
auto &prop : props) {
556 if (wsProp && !(wsProp->getWorkspace())) {
558 prop->setValue(prop->value());
564 throw std::runtime_error(
"Some invalid Properties found");
567 const float timingPropertyValidation = timer.
elapsed(resetTimer);
576 bool callProcessGroups =
true;
580 }
catch (std::exception &ex) {
581 getLogger().
error() <<
"Error in execution of algorithm " << this->
name() <<
"\n" << ex.what() <<
"\n";
593 timingInit += timer.
elapsed(resetTimer);
595 if ((!callProcessGroups) && (executionMode != Parallel::ExecutionMode::MasterOnly ||
599 std::map<std::string, std::string> errors = this->
validateInputs();
600 if (!errors.empty()) {
601 size_t numErrors = errors.size();
605 for (
auto &
error : errors) {
607 errorLog <<
"Invalid value for " <<
error.first <<
": " <<
error.second <<
"\n";
610 warnLog <<
"validateInputs() references non-existant property \"" <<
error.first <<
"\"\n";
615 std::stringstream msg;
616 msg <<
"Some invalid Properties found: ";
617 for (
auto &
error : errors) {
618 msg <<
"\n " <<
error.first <<
": " <<
error.second;
621 throw std::runtime_error(msg.str());
625 const float timingInputValidation = timer.
elapsed(resetTimer);
637 m_history = std::make_shared<AlgorithmHistory>(algHist);
643 if (callProcessGroups) {
649 timingInit += timer.
elapsed(resetTimer);
656 startTime = Mantid::Types::Core::DateAndTime::getCurrentTime();
658 this->
exec(executionMode);
662 const float timingExec = timer.
elapsed(resetTimer);
664 const float duration = timingInit + timingPropertyValidation + timingInputValidation + timingExec;
679 algIsExecuted =
true;
683 "Time for other input validation: " +
std::to_string(timingInputValidation) +
" seconds\n" +
684 "Time for other initialization: " +
std::to_string(timingInit) +
" seconds\n" +
685 "Time to run exec: " +
std::to_string(timingExec) +
" seconds\n");
687 }
catch (std::runtime_error &ex) {
688 m_gcTime = Mantid::Types::Core::DateAndTime::getCurrentTime() +=
689 (Mantid::Types::Core::DateAndTime::ONE_SECOND * DELAY_BEFORE_GC);
696 getLogger().
error() <<
"Error in execution of algorithm " << this->
name() <<
'\n' << ex.what() <<
'\n';
699 }
catch (std::logic_error &ex) {
700 m_gcTime = Mantid::Types::Core::DateAndTime::getCurrentTime() +=
701 (Mantid::Types::Core::DateAndTime::ONE_SECOND * DELAY_BEFORE_GC);
708 getLogger().
error() <<
"Logic Error in execution of algorithm " << this->
name() <<
'\n' << ex.what() <<
'\n';
714 m_gcTime = Mantid::Types::Core::DateAndTime::getCurrentTime() +=
715 (Mantid::Types::Core::DateAndTime::ONE_SECOND * DELAY_BEFORE_GC);
723 catch (std::exception &ex) {
725 getLogger().
error() <<
"Error in execution of algorithm " << this->
name() <<
":\n" << ex.what() <<
"\n";
726 m_gcTime = Mantid::Types::Core::DateAndTime::getCurrentTime() +=
727 (Mantid::Types::Core::DateAndTime::ONE_SECOND * DELAY_BEFORE_GC);
739 m_gcTime = Mantid::Types::Core::DateAndTime::getCurrentTime() +=
740 (Mantid::Types::Core::DateAndTime::ONE_SECOND * DELAY_BEFORE_GC);
749 m_gcTime = Mantid::Types::Core::DateAndTime::getCurrentTime() +=
750 (Mantid::Types::Core::DateAndTime::ONE_SECOND * DELAY_BEFORE_GC);
770 bool executed =
false;
773 }
catch (std::runtime_error &) {
778 throw std::runtime_error(
"Unable to successfully run ChildAlgorithm " + this->
name());
789 std::vector<int> groupWsIndicies;
792 for (
unsigned int i = 0; i < props.size(); ++i) {
797 auto group = std::dynamic_pointer_cast<WorkspaceGroup>(wsProp->getWorkspace());
801 }
catch (std::runtime_error &) {
805 groupWsIndicies.emplace_back(i);
811 std::vector<int>::const_iterator wsIndex;
812 for (wsIndex = groupWsIndicies.begin(); wsIndex != groupWsIndicies.end(); ++wsIndex) {
817 }
catch (std::runtime_error &) {
843 const double endProgress,
const bool enableLogging,
const int &version) {
856 const bool enableLogging) {
859 alg->setLogging(enableLogging);
864 }
catch (std::runtime_error &) {
865 throw std::runtime_error(
"Unable to initialise Child Algorithm '" + alg->name() +
"'");
870 const std::vector<Property *> &props = alg->getProperties();
871 for (
auto prop : props) {
874 if (prop->value().empty() && !wsProp->isOptional()) {
875 prop->createTemporaryValue();
880 if (startProgress >= 0.0 && endProgress > startProgress && endProgress <= 1.0) {
891 std::weak_ptr<IAlgorithm> weakPtr(alg);
914 root[
"name"] =
name();
915 root[
"version"] = this->
version();
931 ::Json::Value jsonMap;
933 auto props =
history.getProperties();
934 const size_t numProps(props.size());
935 for (
size_t i = 0; i < numProps; ++i) {
937 if (!prop->isDefault()) {
938 jsonMap[prop->name()] = prop->value();
943 root[
"version"] =
history.version();
944 root[
"properties"] = jsonMap;
946 const std::string output = Mantid::JsonHelpers::jsonToString(root);
951 }
catch (std::invalid_argument &) {
952 throw std::runtime_error(
"Could not create algorithm from history. "
953 "Is this a child algorithm whose workspaces are not in the ADS?");
969 if (Mantid::JsonHelpers::parse(input, &root)) {
972 throw std::runtime_error(
"Cannot create algorithm, invalid string format.");
984 const std::string algName = serialized[
"name"].asString();
985 const int version = serialized.get(
"version", -1).asInt();
988 alg->setProperties(serialized[
"properties"]);
1016 for (
const auto &prop : algProperties) {
1027 bool linked =
false;
1029 const auto &childHistories =
m_history->getChildHistories();
1030 auto childIter = childHistories.rbegin();
1031 for (; childIter != childHistories.rend() && !linked; ++childIter) {
1032 const auto &props = (*childIter)->getProperties();
1033 auto propIter = props.begin();
1034 for (; propIter != props.end() && !linked; ++propIter) {
1039 std::ostringstream os;
1040 os <<
"__TMP" << wsProp->getWorkspace().get();
1041 if (os.str() == (*propIter)->value()) {
1042 (*propIter)->setValue(prop->value());
1075 const std::string &strValue,
bool checkADS) {
1081 if (checkADS && !strValue.empty()) {
1082 return ads.retrieve(strValue);
1097 for (
const auto &prop : algProperties) {
1098 const unsigned int propDirection = prop->direction();
1102 appendWS(workspaceFromWSProperty(*wsProp, ads, prop->value(), checkADS));
1112 logger.notice() <<
name() <<
" started";
1114 logger.notice() <<
" (child)";
1115 logger.notice() <<
'\n';
1119 size_t maxPropertyLength = 40;
1120 if (logger.is(Logger::Priority::PRIO_DEBUG)) {
1122 maxPropertyLength = 0;
1124 algHistory.
printSelf(logger.information(), 0, maxPropertyLength);
1155 size_t numGroups = 0;
1163 auto prop =
dynamic_cast<Property *
>(inputWorkspaceProp);
1166 auto wsGroup = std::dynamic_pointer_cast<WorkspaceGroup>(ws);
1171 if (!wsGroup && prop && !prop->value().empty()) {
1181 if (wsGroup && !wsGroupProp) {
1211 throw std::invalid_argument(
"Empty group passed as input");
1212 if (!thisGroup.empty()) {
1215 if (wsGroup && (numGroups == 1))
1219 if (thisGroup.size() > 1) {
1223 throw std::invalid_argument(
"Input WorkspaceGroups are not of the same size.");
1253 startTime = Mantid::Types::Core::DateAndTime::getCurrentTime();
1256 bool completed =
false;
1260 }
catch (std::exception &ex) {
1281 const float duration = timer.
elapsed();
1287 const bool checkADS{
true};
1320 for (
auto &outGroupItem : out) {
1321 outGroupItem->history().addHistory(in.
getHistory());
1325 for (
auto &outWS : outputWorkspaces) {
1326 auto outWSGroup = std::dynamic_pointer_cast<WorkspaceGroup>(outWS);
1330 copyHistoryToGroup(*inputWS, *outWSGroup);
1332 outWS->history().addHistory(inputWS->getHistory());
1337 for (
auto &outGroupItem : *outWSGroup) {
1338 outGroupItem->history().addHistory(
m_history);
1368 std::vector<WorkspaceGroup_sptr> outGroups;
1372 auto *prop =
dynamic_cast<Property *
>(pureOutputWorkspaceProp);
1373 if (prop && !prop->value().empty()) {
1374 auto outWSGrp = std::make_shared<WorkspaceGroup>();
1375 outGroups.emplace_back(outWSGrp);
1378 outWSGrp->observeADSNotifications(
false);
1382 double progress_proportion = 1.0 /
static_cast<double>(
m_groupSize);
1384 for (
size_t entry = 0; entry <
m_groupSize; entry++) {
1387 progress_proportion * (1 +
static_cast<double>(entry)),
1391 alg_sptr->setChild(
true);
1392 alg_sptr->setAlwaysStoreInADS(
true);
1393 alg_sptr->enableHistoryRecordingForChild(
false);
1394 alg_sptr->setRethrows(
true);
1400 std::string outputBaseName;
1405 if (!thisGroup.empty()) {
1413 if (entry < thisGroup.size()) {
1414 ws = thisGroup[entry];
1424 throw std::runtime_error(
"Unable to process over groups; consider passing workspaces "
1425 "one-by-one or override processGroup method of the algorithm.");
1429 if (!outputBaseName.empty())
1430 outputBaseName +=
"_";
1431 outputBaseName += ws->getName();
1435 if (ws->getName().empty()) {
1441 throw std::logic_error(
"Found a Workspace property which doesn't "
1442 "inherit from Property.");
1452 const std::string inName = prop->value();
1455 std::string outName;
1459 outName.append(outputBaseName).append(
"_").append(inName);
1471 if (!inputGroup.empty())
1472 outName = inputGroup[entry]->getName();
1479 outputWSNames[owp] = outName;
1481 throw std::logic_error(
"Found a Workspace property which doesn't "
1482 "inherit from Property.");
1489 }
catch (std::exception &e) {
1490 std::ostringstream msg;
1491 msg <<
"Execution of " << this->
name() <<
" for group entry " << (entry + 1) <<
" failed: ";
1493 throw std::runtime_error(msg.str());
1501 if (prop && prop->value().empty())
1504 outGroups[owp]->add(outputWSNames[owp]);
1510 for (
auto &outGroup : outGroups) {
1511 outGroup->observeADSNotifications(
true);
1525 throw std::runtime_error(
"Algorithm not created!");
1527 for (
const auto &prop : props) {
1564 return (wsProp !=
nullptr);
1575struct AsyncFlagHolder {
1585 AsyncFlagHolder() =
delete;
1634 m_progressObserver = std::make_unique<Poco::NObserver<Algorithm, ProgressNotification>>(
1651 sharedPtr->cancel();
1705 std::string optionalMessage;
1706 if (groupProcessing) {
1707 optionalMessage =
". Processed as a workspace group";
1713 std::stringstream msg;
1714 msg <<
name() <<
" successful, Duration ";
1715 double seconds = duration;
1716 if (seconds > 60.) {
1717 auto minutes =
static_cast<int>(seconds / 60.);
1718 msg << minutes <<
" minutes ";
1719 seconds = seconds -
static_cast<double>(minutes) * 60.;
1721 msg << std::fixed << std::setprecision(2) << seconds <<
" seconds" << optionalMessage;
1736 std::ostringstream oss;
1758 switch (executionMode) {
1759 case Parallel::ExecutionMode::Serial:
1760 case Parallel::ExecutionMode::Identical:
1762 case Parallel::ExecutionMode::Distributed:
1764 case Parallel::ExecutionMode::MasterOnly:
1767 throw(std::runtime_error(
"Algorithm " +
name() +
" does not support execution mode " +
1768 Parallel::toString(executionMode)));
1801 return Parallel::ExecutionMode::Serial;
1805 if (executionMode == Parallel::ExecutionMode::Invalid) {
1806 std::string
error(
"Algorithm does not support execution with input "
1807 "workspaces of the following storage types: " +
1808 Parallel::toString(storageModes) +
".");
1810 throw(std::runtime_error(
error));
1812 if (executionMode == Parallel::ExecutionMode::Serial) {
1813 std::string
error(Parallel::toString(executionMode) +
" is not a valid *parallel* execution mode.");
1815 throw(std::runtime_error(
error));
1818 << Parallel::toString(executionMode) <<
'\n';
1819 return executionMode;
1826 std::map<std::string, Parallel::StorageMode> map;
1832 if (wsProp->getWorkspace())
1833 map.emplace(prop.
name(), wsProp->getWorkspace()->storageMode());
1834 else if (!wsProp->isOptional())
1835 map.emplace(prop.
name(), Parallel::StorageMode::MasterOnly);
1838 for (
const auto &item : map)
1839 getLogger().
information() <<
" " << item.first <<
" --- " << Parallel::toString(item.second) <<
'\n';
1849Parallel::ExecutionMode
1853 return Parallel::ExecutionMode::Invalid;
1866 wsProp->setIsMasterRank(
false);
1882 :
Poco::Notification(), m_algorithm(alg) {}
1894 double estimatedTime,
int progressPrecision)
1896 progressPrecision(progressPrecision) {}
1941 const std::unordered_set<std::string> &ignoreProperties,
bool createMissing) {
1952 bool createMissing) {
1963 const std::unordered_set<std::string> &ignoreProperties) {
2148MANTID_API_DLL
API::IAlgorithm_sptr IPropertyManager::getValue<API::IAlgorithm_sptr>(
const std::string &name)
const {
2153 std::string message =
"Attempt to assign property " + name +
" to incorrect type. Expected shared_ptr<IAlgorithm>";
2154 throw std::runtime_error(message);
2166IPropertyManager::getValue<API::IAlgorithm_const_sptr>(
const std::string &name)
const {
2169 return prop->operator()();
2171 std::string message =
2172 "Attempt to assign property " + name +
" to incorrect type. Expected const shared_ptr<IAlgorithm>";
2173 throw std::runtime_error(message);
const std::string & m_value
bool & m_running_flag
Running flag.
double value
The value of the point.
IPeaksWorkspace_sptr workspace
std::map< DeltaEMode::Type, std::string > index
#define PARALLEL_CRITICAL(name)
#define UNUSED_ARG(x)
Function arguments are sometimes unused in certain implmentations but are required for documentation ...
std::vector< history_type > history
history information
ADSValidator : a validator that requires the value of a property to be present in the ADS.
This class stores information about the Command History used by algorithms on a workspace.
void printSelf(std::ostream &, const int indent=0, const size_t maxPropertyLength=0) const
print contents of object
Base class for algorithm notifications.
AlgorithmNotification(const Algorithm *const alg)
const IAlgorithm * algorithm() const
CancelException is thrown to cancel execution of the algorithm.
const char * what() const noexcept override
Returns the message string.
ErrorNotification is sent when an exception is caught during execution of the algorithm.
std::string name() const override
ErrorNotification(const Algorithm *const alg, std::string str)
Constructor.
FinishedNotification is sent after the algorithm finishes its execution.
std::string name() const override
FinishedNotification(const Algorithm *const alg, bool res)
An algorithm can report its progress by sending ProgressNotification.
ProgressNotification(const Algorithm *const alg, double p, std::string msg, double estimatedTime, int progressPrecision)
Constructor.
std::string name() const override
StartedNotification is sent when the algorithm begins execution.
StartedNotification(const Algorithm *const alg)
std::string name() const override
class name
Base class from which all concrete algorithm classes should be derived.
void clearWorkspaceCaches()
Clear any internal workspace handles so that workspaces will be deleted promptly after a managed algo...
void setRethrows(const bool rethrow) override
Set whether the algorithm will rethrow exceptions.
const std::string categorySeparator() const override
Function to return the separator token for the category string.
std::vector< std::shared_ptr< WorkspaceGroup > > m_groupWorkspaces
Pointer to the WorkspaceGroup (if any) for each input workspace property.
void declareProperty(std::unique_ptr< Kernel::Property > p, const std::string &doc="") override
Add a property to the list of managed properties.
void store()
Stores any output workspaces into the AnalysisDataService.
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...
bool isRunning() const override
True if the algorithm is running.
void setExecutionState(const ExecutionState state)
Sets the current execution state.
virtual const std::string workspaceMethodOnTypes() const
Returns a semi-colon separated list of workspace types to attach this algorithm.
Kernel::Property * getPointerToProperty(const std::string &name) const override
Get a property by name.
const std::string workspaceMethodName() const override
bool calledByAlias
Flag to indicate if the algorithm is called by its alias.
std::vector< std::string > getDeclaredPropertyNames() const noexcept override
Return the list of declared property names.
std::unique_ptr< Poco::NObserver< Algorithm, ProgressNotification > > m_progressObserver
Child algorithm progress observer.
std::vector< std::string > m_reservedList
Reserved property names.
AlgorithmID getAlgorithmID() const override
Algorithm ID.
int m_singleGroup
If only one input is a group, this is its index. -1 if they are all groups.
void setCommunicator(const Parallel::Communicator &communicator)
Sets the (MPI) communicator of the algorithm.
void clear() override
Clears all properties under management.
std::vector< IWorkspaceProperty * > m_inputWorkspaceProps
All the WorkspaceProperties that are Input or InOut. Set in execute()
bool isExecuted() const override
Has the Algorithm already been executed successfully.
::Json::Value asJson(bool withDefaultValues=false) const override
Return the property manager serialized as a json object.
void registerFeatureUsage() const
Registers the usage of the algorithm with the UsageService.
virtual void execDistributed()
Runs the algorithm in distributed execution mode.
bool existsProperty(const std::string &name) const override
Checks whether the named property is already in the list of managed property.
WorkspaceVector m_writeLockedWorkspaces
Vector of all the workspaces that have been write-locked.
bool m_rethrow
Algorithm should rethrow exceptions while executing.
bool validateProperties() const override
Validates all the properties in the collection.
double m_startChildProgress
Whether to log alg startup and closedown messages from the base class (default = true)
void setPropertyOrdinal(const int &index, const std::string &value) override
Set the value of a property by an index N.B.
void setupSkipValidationMasterOnly()
Sets up skipping workspace validation on non-master ranks for StorageMode::MasterOnly.
void afterPropertySet(const std::string &) override
Override this method to perform a custom action right after a property was set.
bool m_usingBaseProcessGroups
distinguish between base processGroups() and overriden/algorithm specific versions
void setAlgStartupLogging(const bool enabled) override
disable Logging of start and end messages
void removeProperty(const std::string &name, const bool delproperty=true) override
Removes the property from management.
std::string getPropertyValue(const std::string &name) const override
Get the value of a property as a string.
std::vector< std::weak_ptr< IAlgorithm > > m_ChildAlgorithms
A list of weak pointers to any child algorithms created.
Kernel::Property * getPointerToPropertyOrdinal(const int &index) const override
Get a property by an index.
std::unique_ptr< Kernel::Property > takeProperty(const size_t index) override
Removes the property from management and returns a pointer to it.
void copyNonWorkspaceProperties(IAlgorithm *alg, int periodNum)
Copy all the non-workspace properties from this to alg.
std::atomic< bool > m_cancel
Set to true to stop execution.
void setLogging(const bool value) override
Logging can be disabled by passing a value of false.
std::shared_ptr< AlgorithmHistory > m_parentHistory
Pointer to the parent history object (if set)
TypedValue getProperty(const std::string &name) const override
Get the value of a property.
virtual void fillHistory()
Copy workspace history for input workspaces to output workspaces and record the history for ths algor...
void setResultState(const ResultState state)
Sets the result execution state.
void handleChildProgressNotification(const Poco::AutoPtr< ProgressNotification > &pNf)
Observation slot for child algorithm progress notification messages, these are scaled and then signal...
void addObserver(const Poco::AbstractObserver &observer) const override
Add an observer for a notification.
std::string toString() const override
Serialize an object to a string.
std::shared_ptr< AlgorithmHistory > m_history
Pointer to the history for the algorithm being executed.
std::vector< IWorkspaceProperty * > m_outputWorkspaceProps
All the WorkspaceProperties that are Output or InOut. Set in execute()
void initialize() override
Initialization method invoked by the framework.
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.
virtual Parallel::ExecutionMode getParallelExecutionMode(const std::map< std::string, Parallel::StorageMode > &storageModes) const
Get correct execution mode based on input storage modes for an MPI run.
std::vector< IWorkspaceProperty * > m_pureOutputWorkspaceProps
All the WorkspaceProperties that are Output (not inOut). Set in execute()
size_t propertyCount() const override
Count the number of properties under management.
Parallel::ExecutionMode getExecutionMode() const
Get a (valid) execution mode for this algorithm.
virtual void execMasterOnly()
Runs the algorithm in master-only execution mode.
bool isChild() const override
To query whether algorithm is a child.
void setLoggingOffset(const int value) override
gets the logging priority offset
size_t m_groupSize
Size of the group(s) being processed.
static IAlgorithm_sptr fromString(const std::string &input)
De-serialize an object from a string.
WorkspaceVector m_readLockedWorkspaces
Vector of all the workspaces that have been read-locked.
virtual void init()=0
Virtual method - must be overridden by concrete algorithm.
std::vector< std::shared_ptr< Workspace > > WorkspaceVector
void progress(double p, const std::string &msg="", double estimatedTime=0.0, int progressPrecision=0)
Sends ProgressNotification.
virtual void setOtherProperties(IAlgorithm *alg, const std::string &propertyName, const std::string &propertyValue, int periodNum)
Virtual method to set the non workspace properties for this algorithm.
bool isInitialized() const override
Has the Algorithm already been initialized.
bool m_alwaysStoreInADS
Always store in the ADS, even for child algos.
ExecutionState executionState() const override
Gets the current execution state.
bool m_isAlgStartupLoggingEnabled
bool trackingHistory()
get whether we are tracking the history for this algorithm,
bool execute() override final
The actions to be performed by the algorithm on a dataset.
void setAlwaysStoreInADS(const bool doStore) override
Do we ALWAYS store in the AnalysisDataService? This is set to true for python algorithms' child algor...
void linkHistoryWithLastChild()
Link the name of the output workspaces on this parent algorithm.
bool isLogging() const override
returns the status of logging, True = enabled
bool getAlgStartupLogging() const override
get the state of Logging of start and end messages
bool isWorkspaceProperty(const Kernel::Property *const prop) const
checks the property is a workspace property
void setProperties(const std::string &propertiesJson, const std::unordered_set< std::string > &ignoreProperties=std::unordered_set< std::string >(), bool createMissing=false) override
Set the ordered list of properties by one string of values, separated by semicolons.
std::atomic< ResultState > m_resultState
the current result State
bool isReadyForGarbageCollection() const override
True if the algorithm is ready for garbage collection.
Poco::NotificationCenter & notificationCenter() const
Return a reference to the algorithm's notification dispatcher.
int getLoggingOffset() const override
returns the logging priority offset
std::unique_ptr< Poco::ActiveMethod< bool, Poco::Void, Algorithm, Poco::ActiveStarter< Algorithm > > > m_executeAsync
Poco::ActiveMethod used to implement asynchronous execution.
std::vector< WorkspaceVector > m_unrolledInputWorkspaces
One vector of workspaces for each input workspace property.
void resetProperties() override
Reset property values back to initial values (blank or default values)
void removeObserver(const Poco::AbstractObserver &observer) const override
Remove an observer.
void logAlgorithmInfo() const
Sends out algorithm parameter information to the logger.
void reportCompleted(const double &duration, const bool groupProcessing=false)
Report that the algorithm has completed.
bool m_isChildAlgorithm
Algorithm is a child algorithm.
bool getAlwaysStoreInADS() const override
Returns true if we always store in the AnalysisDataService.
void setPropertiesWithString(const std::string &propertiesString, const std::unordered_set< std::string > &ignoreProperties=std::unordered_set< std::string >()) override
Sets all the declared properties from a string.
bool executeInternal()
Invoced internally in execute()
Mantid::Kernel::PropertyManagerOwner m_properties
ResultState resultState() const override
Gets the current result State.
const std::string category() const override
function to return a category of the algorithm.
virtual void exec()=0
Virtual method - must be overridden by concrete algorithm.
void executeAsChildAlg() override
Execute as a Child Algorithm.
bool isDefault(const std::string &name) const
void trackAlgorithmHistory(std::shared_ptr< AlgorithmHistory > parentHist)
set whether we wish to track the child algorithm's history and pass it the parent object to fill.
const std::string workspaceMethodInputProperty() const override
std::string asString(bool withDefaultValues=false) const override
Return the property manager serialized as a string.
void declareOrReplaceProperty(std::unique_ptr< Kernel::Property > p, const std::string &doc="") override
Add or replace property in the list of managed properties.
void interruption_point()
This is called during long-running operations, and check if the algorithm has requested that it be ca...
const std::vector< std::string > categories() const override
Function to return all of the categories that contain this algorithm.
void cancel() override
Raises the cancel flag.
const std::vector< std::string > workspaceMethodOn() const override
void setPropertyValue(const std::string &name, const std::string &value) override
Set the value of a property by string N.B.
~Algorithm() override
Virtual destructor.
void enableHistoryRecordingForChild(const bool on) override
Change the state of the history recording flag.
bool m_runningAsync
Algorithm is running asynchronously.
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
static bool isEmpty(const NumT toCheck)
checks that the value was not set by users, uses the value in empty double/int.
bool m_groupsHaveSimilarNames
All the groups have similar names (group_1, group_2 etc.)
Poco::ActiveResult< bool > executeAsync() override
Asynchronous execution.
std::map< std::string, std::string > validateInputs() override
Perform validation of ALL the input properties of the algorithm.
void lockWorkspaces()
Go through the workspace properties of this algorithm and lock the workspaces for reading or writing.
void setupAsChildAlgorithm(const Algorithm_sptr &algorithm, const double startProgress=-1., const double endProgress=-1., const bool enableLogging=true)
Setup algorithm as child algorithm.
bool getCancel() const
Returns the cancellation state.
bool doCallProcessGroups(Mantid::Types::Core::DateAndTime &start_time)
Calls process groups with the required timing checks and algorithm execution finalization steps.
const Parallel::Communicator & communicator() const
Returns a const reference to the (MPI) communicator of the algorithm.
void cacheWorkspaceProperties()
Go through the properties and cache the input/output workspace properties for later use.
::Json::Value toJson() const override
Serialize an object to a json object.
void findWorkspaces(WorkspaceVector &workspaces, unsigned int direction, bool checkADS=false) const
Populate lists of the workspace properties for a given direction (InOut workspaces are included in bo...
std::unique_ptr< Parallel::Communicator > m_communicator
(MPI) communicator used when executing the algorithm.
std::map< std::string, Parallel::StorageMode > getInputWorkspaceStorageModes() const
Get map of storage modes of all input workspaces.
Kernel::Logger & getLogger() const
Returns a reference to the logger.
void cacheInputWorkspaceHistories()
Cache the histories of any input workspaces so they can be copied over after algorithm completion.
double m_endChildProgress
Keeps value for algorithm's progress at Child Algorithm's finish.
virtual bool checkGroups()
Check the input workspace properties for groups.
bool isCompoundProperty(const std::string &name) const
Mantid::Types::Core::DateAndTime m_gcTime
The earliest this class should be considered for garbage collection.
std::unique_ptr< Poco::NotificationCenter > m_notificationCenter
Sends notifications to observers.
void setChild(const bool isChild) override
To set whether algorithm is a child.
void setPropertyValueFromJson(const std::string &name, const Json::Value &value) override
Set the value of a property by Json::Value object.
static size_t g_execCount
Counter to keep track of algorithm execution order.
bool m_recordHistoryForChild
Flag to indicate whether history should be recorded.
static IAlgorithm_sptr fromHistory(const AlgorithmHistory &history)
Construct an object from a history entry.
static IAlgorithm_sptr fromJson(const Json::Value &input)
De-serialize an object from a Json.
void unlockWorkspaces()
Unlock any previously locked workspaces.
const std::vector< Kernel::Property * > & getProperties() const override
Get the list of managed properties.
virtual bool processGroups()
Process WorkspaceGroup inputs.
const std::string name() const override=0
function to return a name of the algorithm, must be overridden in all algorithms
bool executeAsyncImpl(const Poco::Void &i)
Callback when an algorithm is executed asynchronously.
const Poco::AbstractObserver & progressObserver() const
Return a reference to the algorithm's object that is reporting progress.
The Analysis data service stores instances of the Workspace objects and anything that derives from te...
Class for marking algorithms as deprecated.
DeprecatedAlias : Class for making algorithm with deprecated names (aliases).
IAlgorithm is the interface implemented by the Algorithm base class.
virtual const std::string name() const =0
function to return a name of the algorithm, must be overridden in all algorithms
An interface that is implemented by WorkspaceProperty.
virtual bool store()=0
Store a workspace into the AnalysisDataService.
virtual Workspace_sptr getWorkspace() const =0
Get a pointer to the workspace.
Class to hold a set of workspaces.
A property class for workspaces.
Workspace_sptr getWorkspace() const override
Get a pointer to the workspace.
Base Workspace Abstract Class.
const WorkspaceHistory & getHistory() const
Returns a reference to the WorkspaceHistory const.
Support for a property that holds an array of values.
Exception for when an item is not found in a collection.
virtual void setPropertyValue(const std::string &name, const std::string &value)=0
Sets property value from a string.
IPropertyManager * setProperty(const std::string &name, const T &value)
Templated method to set the value of a PropertyWithValue.
The Logger class is in charge of the publishing messages from the framework through various channels.
void debug(const std::string &msg)
Logs at debug level.
void notice(const std::string &msg)
Logs at notice level.
void setName(const std::string &name)
Update the name of the logger.
int getLevelOffset() const
Gets the Logger's log offset level.
void error(const std::string &msg)
Logs at error level.
void warning(const std::string &msg)
Logs at warning level.
void setEnabled(const bool enabled)
set if the logging is enabled
bool getEnabled() const
returns true if the log is enabled
void fatal(const std::string &msg)
Logs at Fatal level.
void setLevelOffset(int level)
Sets the Logger's log offset level.
void information(const std::string &msg)
Logs at information level.
Property * getPointerToProperty(const std::string &name) const override
Get a property by name.
bool validateProperties() const override
Validates all the properties in the collection.
void afterPropertySet(const std::string &) override
Override this method to perform a custom action right after a property was set.
void setProperties(const std::string &propertiesJson, const std::unordered_set< std::string > &ignoreProperties=std::unordered_set< std::string >(), bool createMissing=false) override
Set the ordered list of properties by one string of values, separated by semicolons.
void setPropertyValue(const std::string &name, const std::string &value) override
Set the value of a property by string N.B.
void declareOrReplaceProperty(std::unique_ptr< Property > p, const std::string &doc="") override
Add or replace property in the list of managed properties.
std::string getPropertyValue(const std::string &name) const override
Get the value of a property as a string.
void clear() override
Clears all properties under management.
void setPropertyOrdinal(const int &index, const std::string &value) override
Set the value of a property by an index N.B.
void declareProperty(std::unique_ptr< Property > p, const std::string &doc="") override
Add a property to the list of managed properties.
::Json::Value asJson(bool withDefaultValues=false) const override
Return the property manager serialized as a json object.
void setPropertyValueFromJson(const std::string &name, const Json::Value &value) override
Set the value of a property by Json::Value object.
const std::vector< Property * > & getProperties() const override
Get the list of managed properties.
std::vector< std::string > getDeclaredPropertyNames() const noexcept override
Return the list of declared property names.
TypedValue getProperty(const std::string &name) const override
Get the value of a property.
void setPropertiesWithString(const std::string &propertiesString, const std::unordered_set< std::string > &ignoreProperties=std::unordered_set< std::string >()) override
Sets all the declared properties from a string.
bool existsProperty(const std::string &name) const override
Checks whether the named property is already in the list of managed property.
Property * getPointerToPropertyOrdinal(const int &index) const override
Get a property by an index.
size_t propertyCount() const override
Count the number of properties under management.
void removeProperty(const std::string &name, const bool delproperty=true) override
Removes the property from management.
void resetProperties() override
Reset property values back to initial values (blank or default values)
std::unique_ptr< Property > takeProperty(const size_t index) override
Removes the property from management returning a pointer to it.
std::string asString(bool withDefaultValues=false) const override
Return the property manager serialized as a string.
The concrete, templated class for properties.
Base class for properties.
virtual bool isDefault() const =0
Overriden function that returns if property has the same value that it was initialised with,...
const std::string & name() const
Get the property's name.
virtual std::string value() const =0
Returns the value of the property as a string.
static T & Instance()
Return a reference to the Singleton instance, creating it if it does not already exist Creation is do...
@ TOK_IGNORE_EMPTY
ignore empty tokens
@ TOK_TRIM
remove leading and trailing whitespace from tokens
const TokenVec & asVector()
Returns a vector of tokenized strings.
A simple class that provides a wall-clock (not processor time) timer.
float elapsed(bool reset=true)
Returns the wall-clock time elapsed in seconds since the Timer object's creation, or the last call to...
std::shared_ptr< IAlgorithm > IAlgorithm_sptr
shared pointer to Mantid::API::IAlgorithm
std::shared_ptr< WorkspaceGroup > WorkspaceGroup_sptr
shared pointer to Mantid::API::WorkspaceGroup
std::shared_ptr< const IAlgorithm > IAlgorithm_const_sptr
shared pointer to Mantid::API::IAlgorithm (const version)
std::shared_ptr< Workspace > Workspace_sptr
shared pointer to Mantid::API::Workspace
Kernel::Logger g_log("ExperimentInfo")
static logger object
ResultState
The validity of the results of the algorithm object.
ExecutionState
The current state of the algorithm object.
std::shared_ptr< Algorithm > Algorithm_sptr
Typedef for a shared pointer to an Algorithm.
Mantid::Kernel::StringTokenizer tokenizer
std::string toString(const T &value)
Convert a number to a string.
std::shared_ptr< PropertyHistory > PropertyHistory_sptr
std::shared_ptr< IValidator > IValidator_sptr
A shared_ptr to an IValidator.
Helper class which provides the Collimation Length for SANS instruments.
constexpr int EMPTY_INT() noexcept
Returns what we consider an "empty" integer within a property.
constexpr double EMPTY_DBL() noexcept
Returns what we consider an "empty" double within a property.
std::string to_string(const wide_integer< Bits, Signed > &n)
@ InOut
Both an input & output workspace.
@ Input
An input workspace.
@ Output
An output workspace.
Utility class that enables the getProperty() method to effectively be templated on the return type.