20#include "MantidJson/Json.h"
31#include <Poco/ActiveMethod.h>
32#include <Poco/ActiveResult.h>
33#include <Poco/NotificationCenter.h>
34#include <Poco/RWLock.h>
55const std::string WORKSPACE_TYPES_SEPARATOR =
";";
59const size_t DELAY_BEFORE_GC = 5;
61class WorkspacePropertyValueIs {
65 auto *prop =
dynamic_cast<Property *
>(property);
75template <
typename T>
struct RunOnFinish {
76 RunOnFinish(T &&task) :
m_onfinsh(std::move(task)) {}
90 return static_cast<int>(toCheck) ==
EMPTY_INT();
98template MANTID_API_DLL
bool Algorithm::isEmpty<int>(
const int);
99template MANTID_API_DLL
bool Algorithm::isEmpty<int64_t>(
const int64_t);
100template MANTID_API_DLL
bool Algorithm::isEmpty<std::size_t>(
const std::size_t);
113 : m_cancel(false), m_parallelException(false), m_log(
"Algorithm"),
g_log(m_log), m_groupSize(0),
114 m_executeAsync(nullptr), m_notificationCenter(nullptr), m_progressObserver(nullptr),
116 m_isChildAlgorithm(false), m_recordHistoryForChild(false), m_checkForStringArrayWorkspaceOutputs(false),
117 m_alwaysStoreInADS(true), m_runningAsync(false), m_rethrow(false), m_isAlgStartupLoggingEnabled(true),
118 m_startChildProgress(0.), m_endChildProgress(0.), m_algorithmID(this), m_singleGroup(-1),
119 m_groupsHaveSimilarNames(false), m_inputWorkspaceHistories(), m_properties() {}
216 (Mantid::Types::Core::DateAndTime::getCurrentTime() >
m_gcTime)) {
260 if (depo !=
nullptr) {
261 res.emplace_back(
"Deprecated");
308 }
catch (std::runtime_error &) {
315 }
catch (std::runtime_error &) {
350 for (
const auto &prop : props) {
354 switch (prop->direction()) {
367 throw std::logic_error(
"Unexpected property direction found for property " + prop->name() +
" of algorithm " +
404 const auto &ads = AnalysisDataService::Instance();
407 for (
const auto &prop : props) {
412 if (
auto ws = wsProp->getWorkspace()) {
417 wsFromADS = ads.retrieve(prop->value());
421 cacheHistories(wsFromADS);
423 }
else if (
auto strArrayProp =
dynamic_cast<ArrayPropertyString *
>(prop)) {
424 if (!isADSValidator(strArrayProp->getValidator()))
426 const auto &wsNames((*strArrayProp)());
427 for (
const auto &wsName : wsNames) {
428 cacheHistories(ads.retrieve(wsName));
445 throw std::logic_error(
"Algorithm::lockWorkspaces(): The workspaces have "
446 "already been locked!");
458 debugLog <<
"Write-locking " << ws->getName() <<
'\n';
459 ws->getLock()->writeLock();
474 debugLog <<
"Read-locking " << ws->getName() <<
'\n';
475 ws->getLock()->readLock();
493 debugLog <<
"Unlocking " << ws->getName() <<
'\n';
494 ws->getLock()->unlock();
499 debugLog <<
"Unlocking " << ws->getName() <<
'\n';
500 ws->getLock()->unlock();
528 bool algIsExecuted =
false;
529 AlgorithmManager::Instance().notifyAlgorithmStarting(this->
getAlgorithmID());
551 Mantid::Types::Core::DateAndTime startTime;
555 throw std::runtime_error(
"Algorithm is not initialised:" + this->
name());
563 constexpr bool resetTimer{
true};
564 float timingInit = timer.
elapsed(resetTimer);
568 for (
auto &prop : props) {
570 if (wsProp && !(wsProp->getWorkspace())) {
572 prop->setValue(prop->value());
578 throw std::runtime_error(
"Some invalid Properties found");
581 const float timingPropertyValidation = timer.
elapsed(resetTimer);
590 bool callProcessGroups =
true;
594 }
catch (std::exception &ex) {
595 getLogger().
error() <<
"Error in execution of algorithm " << this->
name() <<
"\n" << ex.what() <<
"\n";
604 timingInit += timer.
elapsed(resetTimer);
606 if ((!callProcessGroups))
608 std::map<std::string, std::string> errors = this->
validateInputs();
609 if (!errors.empty()) {
610 size_t numErrors = errors.size();
614 for (
auto &
error : errors) {
616 errorLog <<
"Invalid value for " <<
error.first <<
": " <<
error.second <<
"\n";
619 warnLog <<
"validateInputs() references non-existant property \"" <<
error.first <<
"\"\n";
624 std::stringstream msg;
625 msg <<
"Some invalid Properties found: ";
626 for (
const auto &
error : errors) {
627 msg <<
"\n " <<
error.first <<
": " <<
error.second;
630 throw std::runtime_error(msg.str());
634 const float timingInputValidation = timer.
elapsed(resetTimer);
646 m_history = std::make_shared<AlgorithmHistory>(algHist);
652 if (callProcessGroups) {
658 timingInit += timer.
elapsed(resetTimer);
665 startTime = Mantid::Types::Core::DateAndTime::getCurrentTime();
671 const float timingExec = timer.
elapsed(resetTimer);
673 const float duration = timingInit + timingPropertyValidation + timingInputValidation + timingExec;
688 algIsExecuted =
true;
692 "Time for other input validation: " +
std::to_string(timingInputValidation) +
" seconds\n" +
693 "Time for other initialization: " +
std::to_string(timingInit) +
" seconds\n" +
694 "Time to run exec: " +
std::to_string(timingExec) +
" seconds\n");
696 }
catch (std::runtime_error &ex) {
697 m_gcTime = Mantid::Types::Core::DateAndTime::getCurrentTime() +=
698 (Mantid::Types::Core::DateAndTime::ONE_SECOND * DELAY_BEFORE_GC);
705 getLogger().
error() <<
"Error in execution of algorithm " << this->
name() <<
'\n' << ex.what() <<
'\n';
708 }
catch (std::logic_error &ex) {
709 m_gcTime = Mantid::Types::Core::DateAndTime::getCurrentTime() +=
710 (Mantid::Types::Core::DateAndTime::ONE_SECOND * DELAY_BEFORE_GC);
717 getLogger().
error() <<
"Logic Error in execution of algorithm " << this->
name() <<
'\n' << ex.what() <<
'\n';
722 m_gcTime = Mantid::Types::Core::DateAndTime::getCurrentTime() +=
723 (Mantid::Types::Core::DateAndTime::ONE_SECOND * DELAY_BEFORE_GC);
731 catch (std::exception &ex) {
732 getLogger().
error() <<
"Error in execution of algorithm " << this->
name() <<
":\n" << ex.what() <<
"\n";
733 m_gcTime = Mantid::Types::Core::DateAndTime::getCurrentTime() +=
734 (Mantid::Types::Core::DateAndTime::ONE_SECOND * DELAY_BEFORE_GC);
742 catch (H5::Exception &ex) {
744 errmsg.append(ex.getCFuncName()).append(
": ").append(ex.getCDetailMsg());
745 getLogger().
error() <<
"H5 Exception in execution of algorithm " << this->
name() <<
":\n" << errmsg <<
"\n";
746 m_gcTime = Mantid::Types::Core::DateAndTime::getCurrentTime() +=
747 (Mantid::Types::Core::DateAndTime::ONE_SECOND * DELAY_BEFORE_GC);
757 m_gcTime = Mantid::Types::Core::DateAndTime::getCurrentTime() +=
758 (Mantid::Types::Core::DateAndTime::ONE_SECOND * DELAY_BEFORE_GC);
767 m_gcTime = Mantid::Types::Core::DateAndTime::getCurrentTime() +=
768 (Mantid::Types::Core::DateAndTime::ONE_SECOND * DELAY_BEFORE_GC);
788 bool executed =
false;
791 }
catch (std::runtime_error &) {
796 throw std::runtime_error(
"Unable to successfully run ChildAlgorithm " + this->
name());
807 std::vector<int> groupWsIndicies;
810 for (
unsigned int i = 0; i < props.size(); ++i) {
815 auto group = std::dynamic_pointer_cast<WorkspaceGroup>(wsProp->getWorkspace());
819 }
catch (std::runtime_error &) {
823 groupWsIndicies.emplace_back(i);
829 std::vector<int>::const_iterator wsIndex;
830 for (wsIndex = groupWsIndicies.begin(); wsIndex != groupWsIndicies.end(); ++wsIndex) {
835 }
catch (std::runtime_error &) {
861 const double endProgress,
const bool enableLogging,
const int &version) {
874 const bool enableLogging) {
877 alg->setLogging(enableLogging);
882 }
catch (std::runtime_error &) {
883 throw std::runtime_error(
"Unable to initialise Child Algorithm '" + alg->name() +
"'");
888 const std::vector<Property *> &props = alg->getProperties();
889 for (
auto prop : props) {
892 if (prop->value().empty() && !wsProp->isOptional()) {
893 prop->createTemporaryValue();
898 if (startProgress >= 0.0 && endProgress > startProgress && endProgress <= 1.0) {
909 std::weak_ptr<IAlgorithm> weakPtr(alg);
932 root[
"name"] =
name();
933 root[
"version"] = this->
version();
949 ::Json::Value jsonMap;
951 auto props =
history.getProperties();
952 const size_t numProps(props.size());
953 for (
size_t i = 0; i < numProps; ++i) {
955 if (!prop->isDefault()) {
956 jsonMap[prop->name()] = prop->value();
961 root[
"version"] =
history.version();
962 root[
"properties"] = jsonMap;
964 const std::string output = Mantid::JsonHelpers::jsonToString(root);
969 }
catch (std::invalid_argument &) {
970 throw std::runtime_error(
"Could not create algorithm from history. "
971 "Is this a child algorithm whose workspaces are not in the ADS?");
987 if (Mantid::JsonHelpers::parse(input, &root)) {
990 throw std::runtime_error(
"Cannot create algorithm, invalid string format.");
1002 const std::string algName = serialized[
"name"].asString();
1003 const int versionNumber = serialized.get(
"version", -1).asInt();
1004 auto alg = AlgorithmManager::Instance().createUnmanaged(algName, versionNumber);
1006 alg->setProperties(serialized[
"properties"]);
1034 for (
const auto &prop : algProperties) {
1045 bool linked =
false;
1047 const auto &childHistories =
m_history->getChildHistories();
1048 auto childIter = childHistories.rbegin();
1049 for (; childIter != childHistories.rend() && !linked; ++childIter) {
1050 const auto &props = (*childIter)->getProperties();
1051 auto propIter = props.begin();
1052 for (; propIter != props.end() && !linked; ++propIter) {
1057 std::ostringstream os;
1058 os <<
"__TMP" << wsProp->getWorkspace().get();
1059 if (os.str() == (*propIter)->value()) {
1060 (*propIter)->setValue(prop->value());
1093 const std::string &strValue,
bool checkADS) {
1099 if (checkADS && !strValue.empty()) {
1100 return ads.retrieve(strValue);
1114 const auto &ads = AnalysisDataService::Instance();
1115 for (
const auto &prop : algProperties) {
1116 const unsigned int propDirection = prop->direction();
1120 appendWS(workspaceFromWSProperty(*wsProp, ads, prop->value(), checkADS));
1126 const auto &wsNames((*strArrProp)());
1127 for (
const auto &wsName : wsNames) {
1128 if (ads.doesExist(wsName)) {
1129 appendWS(ads.retrieve(wsName));
1141 logger.notice() <<
name() <<
" started";
1143 logger.notice() <<
" (child)";
1144 logger.notice() <<
'\n';
1148 size_t maxPropertyLength = 40;
1149 if (logger.is(Logger::Priority::PRIO_DEBUG)) {
1151 maxPropertyLength = 0;
1153 algHistory.
printSelf(logger.information(), 0, maxPropertyLength);
1184 size_t numGroups = 0;
1185 bool doProcessGroups =
false;
1188 const auto &ads = AnalysisDataService::Instance();
1192 auto const prop =
dynamic_cast<Property *
>(inputWorkspaceProp);
1195 auto wsGroup = std::dynamic_pointer_cast<WorkspaceGroup>(ws);
1200 if (!wsGroup && prop && !prop->value().empty()) {
1210 if (wsGroup && !wsGroupProp) {
1212 doProcessGroups =
true;
1228 return doProcessGroups;
1240 throw std::invalid_argument(
"Empty group passed as input");
1241 if (!thisGroup.empty()) {
1244 if (wsGroup && (numGroups == 1))
1248 if (thisGroup.size() > 1) {
1252 throw std::invalid_argument(
"Input WorkspaceGroups are not of the same size.");
1265 return doProcessGroups;
1282 startTime = Mantid::Types::Core::DateAndTime::getCurrentTime();
1285 bool completed =
false;
1289 }
catch (std::exception &ex) {
1308 const float duration = timer.
elapsed();
1318 const bool checkADS{
true};
1354 for (
auto &outGroupItem : out) {
1355 outGroupItem->history().addHistory(in.
getHistory());
1359 for (
auto &outWS : outputWorkspaces) {
1360 auto outWSGroup = std::dynamic_pointer_cast<WorkspaceGroup>(outWS);
1364 copyHistoryToGroup(*inputWS, *outWSGroup);
1366 outWS->history().addHistory(inputWS->getHistory());
1371 for (
auto &outGroupItem : *outWSGroup) {
1372 outGroupItem->history().addHistory(
m_history);
1402 std::vector<WorkspaceGroup_sptr> outGroups;
1406 auto *prop =
dynamic_cast<Property *
>(pureOutputWorkspaceProp);
1407 if (prop && !prop->value().empty()) {
1408 auto outWSGrp = std::make_shared<WorkspaceGroup>();
1409 outGroups.emplace_back(outWSGrp);
1411 AnalysisDataService::Instance().addOrReplace(prop->value(), outWSGrp);
1414 *workspaceProperty = outputWorkspace;
1416 outWSGrp->observeADSNotifications(
false);
1420 double progress_proportion = 1.0 /
static_cast<double>(
m_groupSize);
1422 for (
size_t entry = 0; entry <
m_groupSize; entry++) {
1425 progress_proportion * (1 +
static_cast<double>(entry)),
1429 alg_sptr->setChild(
true);
1430 alg_sptr->setAlwaysStoreInADS(
true);
1431 alg_sptr->enableHistoryRecordingForChild(
false);
1432 alg_sptr->setRethrows(
true);
1438 std::string outputBaseName;
1443 if (!thisGroup.empty()) {
1451 if (entry < thisGroup.size()) {
1452 ws = thisGroup[entry];
1462 throw std::runtime_error(
"Unable to process over groups; consider passing workspaces "
1463 "one-by-one or override processGroup method of the algorithm.");
1467 if (!outputBaseName.empty())
1468 outputBaseName +=
"_";
1469 outputBaseName += ws->getName();
1473 if (ws->getName().empty()) {
1479 throw std::logic_error(
"Found a Workspace property which doesn't "
1480 "inherit from Property.");
1490 const std::string inName = prop->value();
1493 std::string outName;
1497 outName.append(outputBaseName).append(
"_").append(inName);
1509 if (!inputGroup.empty())
1510 outName = inputGroup[entry]->getName();
1517 outputWSNames[owp] = outName;
1519 throw std::logic_error(
"Found a Workspace property which doesn't "
1520 "inherit from Property.");
1527 }
catch (std::exception &e) {
1528 std::ostringstream msg;
1529 msg <<
"Execution of " << this->
name() <<
" for group entry " << (entry + 1) <<
" failed: ";
1531 throw std::runtime_error(msg.str());
1539 if (prop && prop->value().empty())
1542 outGroups[owp]->add(outputWSNames[owp]);
1548 for (
auto &outGroup : outGroups) {
1549 outGroup->observeADSNotifications(
true);
1563 throw std::runtime_error(
"Algorithm not created!");
1565 for (
const auto &prop : props) {
1602 return (wsProp !=
nullptr);
1613struct AsyncFlagHolder {
1623 AsyncFlagHolder() =
delete;
1678 m_progressObserver = std::make_unique<Poco::NObserver<Algorithm, ProgressNotification>>(
1695 sharedPtr->cancel();
1742 std::string optionalMessage;
1743 if (groupProcessing) {
1744 optionalMessage =
". Processed as a workspace group";
1750 std::stringstream msg;
1751 msg <<
name() <<
" successful, Duration ";
1752 double seconds = duration;
1753 if (seconds > 60.) {
1754 auto minutes =
static_cast<int>(seconds / 60.);
1755 msg << minutes <<
" minutes ";
1756 seconds = seconds -
static_cast<double>(minutes) * 60.;
1758 msg << std::fixed << std::setprecision(2) << seconds <<
" seconds" << optionalMessage;
1772 if (UsageService::Instance().isEnabled()) {
1773 std::ostringstream oss;
1775 UsageService::Instance().registerFeatureUsage(FeatureType::Algorithm, oss.str(),
isChild());
1802 :
Poco::Notification(), m_algorithm(alg) {}
1814 double estimatedTime,
int progressPrecision)
1816 progressPrecision(progressPrecision) {}
1861 const std::unordered_set<std::string> &ignoreProperties,
bool createMissing) {
1872 bool createMissing) {
1883 const std::unordered_set<std::string> &ignoreProperties) {
2073 std::string message =
"Attempt to assign property " +
name +
" to incorrect type. Expected shared_ptr<IAlgorithm>";
2074 throw std::runtime_error(message);
2086IPropertyManager::getValue<API::IAlgorithm_const_sptr>(
const std::string &
name)
const {
2089 return prop->operator()();
2091 std::string message =
2092 "Attempt to assign property " +
name +
" to incorrect type. Expected const shared_ptr<IAlgorithm>";
2093 throw std::runtime_error(message);
const std::string & m_value
std::atomic_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)
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 scheduled or 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 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.
void enableCheckForStringArrayWorkspaceOutputs(const bool on)
enable flag to scan output StringArrayProperties for workspace names
::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.
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 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.
bool m_recordHistoryForProcessGroups
Opt-in for overridden processGroups() implementations that want the parent algorithm history recorded...
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 from input workspaces to output workspaces and record the history for ths algo...
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.
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.
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
bool m_checkForStringArrayWorkspaceOutputs
Flag to indicate checking of output StringArrayProperty outputs for valid workspaces.
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.
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.
std::atomic_bool m_runningAsync
Algorithm is scheduled or running asynchronously.
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.
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...
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.
void enableHistoryRecordingForProcessGroups(const bool on) override
Change the state of the processGroups history recording flag.
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.
bool areNamesSimilar() const
Are the members of this group of similar names, e.g.
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.
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.
@ 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.
MANTID_API_DLL void setPropertyModeForWorkspaceProperty(Mantid::Kernel::Property *prop, const PropertyMode::Type &optional)
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.