| helics 3.6.1

application_api/Federate.hpp
1 /*
2 Copyright (c) 2017-2025,
3 Battelle Memorial Institute; Lawrence Livermore National Security, LLC; Alliance for Sustainable
4 Energy, LLC. See the top-level NOTICE for additional details. All rights reserved.
5 SPDX-License-Identifier: BSD-3-Clause
6 */
7 #pragma once
8 #include "../core/LocalFederateId.hpp"
9 #include "../core/helicsTime.hpp"
10 #include "../helics_enums.h"
11 #include "FederateInfo.hpp"
12 #include "helics/helics-config.h"
13 #include "helicsTypes.hpp"
14 #include "helics_cxx_export.h"
15
16 #include <atomic>
17 #include <functional>
18 #include <memory>
19 #include <mutex>
20 #include <optional>
21 #include <stdexcept>
22 #include <string>
23 #include <utility>
24
25 namespace gmlc::libguarded {
26 template<class T, class M>
27 class shared_guarded;
28 } // namespace gmlc::libguarded
29
33 namespace helics {
34 class Core;
35 class CoreApp;
36 class AsyncFedCallInfo;
37 class MessageOperator;
38 class ConnectorFederateManager;
39 class PotentialInterfacesManager;
40 class Filter;
41 class Translator;
42 class CloningFilter;
43 class Federate;
44 enum class FilterTypes;
45
48 class HELICS_CXX_EXPORT Federate {
49 public:
51 enum class Modes : char {
53 STARTUP = 0,
55 INITIALIZING = 1,
57 EXECUTING = 2,
59 FINALIZE = 3,
61 ERROR_STATE = 4,
62 // the following states are for asynchronous operations
64 PENDING_INIT = 5,
66 PENDING_EXEC = 6,
68 PENDING_TIME = 7,
70 PENDING_ITERATIVE_TIME = 8,
72 PENDING_FINALIZE = 9,
74 FINISHED = 10,
75
77 PENDING_ITERATIVE_INIT = 12,
78 };
79
80 protected:
81 std::atomic<Modes> currentMode{Modes::STARTUP};
82 char nameSegmentSeparator = '/';
84 bool strictConfigChecking{true};
86 bool useJsonSerialization{false};
88 bool observerMode{false};
90 bool retriggerTimeRequest{false};
91 /*** specify that the federate will only be used on a single thread*/
92 bool singleThreadFederate{false};
93 /*** specify that the federate has potential interfaces*/
94 bool hasPotentialInterfaces{false};
95
96 private:
97 LocalFederateId fedID;
98 protected:
99 std::shared_ptr<Core> coreObject;
100 Time mCurrentTime = Time::minVal();
101 Time mStopTime = Time::maxVal();
102 std::string configFile;
103 private:
105 std::unique_ptr<gmlc::libguarded::shared_guarded<AsyncFedCallInfo, std::mutex>> asyncCallInfo;
106 std::unique_ptr<ConnectorFederateManager> cManager;
108 std::unique_ptr<PotentialInterfacesManager> potManager;
109 std::atomic<int> potInterfacesSequence{0};
110 std::string mName;
111 std::function<void(Time, Time, bool)> timeRequestEntryCallback;
112 std::function<void(Time, bool)> timeUpdateCallback;
113 std::function<void(Modes, Modes)> modeUpdateCallback;
114 std::function<void(Time, bool)> timeRequestReturnCallback;
115 std::function<void(bool)> initializingEntryCallback;
116 std::function<void()> executingEntryCallback;
117 std::function<void()> cosimulationTerminationCallback;
118 std::function<void(int, std::string_view)> errorHandlerCallback;
119
120 public:
125 Federate(std::string_view fedname, const FederateInfo& fedInfo);
131 Federate(std::string_view fedname,
132 const std::shared_ptr<Core>& core,
133 const FederateInfo& fedInfo = FederateInfo{});
134
140 Federate(std::string_view fedname, CoreApp& core, const FederateInfo& fedInfo = FederateInfo{});
144 explicit Federate(const std::string& configString);
150 Federate(std::string_view fedname, const std::string& configString);
152 Federate() noexcept;
154 Federate(Federate&& fed) noexcept;
156 Federate(const Federate& fed) = delete;
158 virtual ~Federate();
160 Federate& operator=(Federate&& fed) noexcept;
162 Federate& operator=(const Federate& fed) = delete;
166 void enterInitializingMode();
167
172 void enterInitializingModeAsync();
177 bool isAsyncOperationCompleted() const;
181 void enterInitializingModeComplete();
182
188 void enterInitializingModeIterative();
189
194 void enterInitializingModeIterativeAsync();
195
200 void enterInitializingModeIterativeComplete();
201
206 IterationResult enterExecutingMode(IterationRequest iterate = IterationRequest::NO_ITERATIONS);
212 void enterExecutingModeAsync(IterationRequest iterate = IterationRequest::NO_ITERATIONS);
217 IterationResult enterExecutingModeComplete();
221 void finalize();
224 void finalizeAsync();
226 void finalizeComplete();
230 void processCommunication(std::chrono::milliseconds period = std::chrono::milliseconds(0));
233 virtual void disconnect();
234
239 void localError(int errorcode, std::string_view message);
240
246 void globalError(int errorcode, std::string_view message);
247
251 void localError(int errorcode);
252
256 void globalError(int errorcode);
257
265 void setSeparator(char separator) { nameSegmentSeparator = separator; }
269 Time requestTime(Time nextInternalTimeStep);
270
273 Time requestNextStep() { return requestTime(timeZero); }
274
278 Time requestTimeAdvance(Time timeDelta) { return requestTime(mCurrentTime + timeDelta); }
279
284 iteration_time requestTimeIterative(Time nextInternalTimeStep, IterationRequest iterate);
285
290 void requestTimeAsync(Time nextInternalTimeStep);
291
298 void requestTimeIterativeAsync(Time nextInternalTimeStep, IterationRequest iterate);
299
302 Time requestTimeComplete();
303
307 iteration_time requestTimeIterativeComplete();
308
314 void setTag(std::string_view tag, std::string_view value);
321 const std::string& getTag(std::string_view tag) const;
322
327 virtual void setProperty(int32_t option, double timeValue);
328
333 virtual void setProperty(int32_t option, Time timeValue);
334
339 virtual void setFlagOption(int flag, bool flagValue = true);
344 virtual void setProperty(int32_t option, int32_t optionValue);
345
349 virtual Time getTimeProperty(int32_t option) const;
350
354 virtual bool getFlagOption(int flag) const;
358 virtual int getIntegerProperty(int32_t option) const;
359
366 void setLoggingCallback(
367 const std::function<void(int, std::string_view, std::string_view)>& logFunction);
368
376 void setInitializingEntryCallback(std::function<void(bool)> callback);
377
383 void setExecutingEntryCallback(std::function<void()> callback);
384
392 void setTimeRequestEntryCallback(std::function<void(Time, Time, bool)> callback);
393
402 void setTimeUpdateCallback(std::function<void(Time, bool)> callback);
403
412 void setModeUpdateCallback(std::function<void(Modes, Modes)> callback);
413
421 void setTimeRequestReturnCallback(std::function<void(Time, bool)> callback);
422
428 void setCosimulationTerminatedCallback(std::function<void()> callback);
429
436 void setErrorHandlerCallback(std::function<void(int, std::string_view)> errorHandlerCallback);
437
451 std::string query(std::string_view target,
452 std::string_view queryStr,
453 HelicsSequencingModes mode = HELICS_SEQUENCING_MODE_FAST);
454
467 std::string query(std::string_view queryStr,
468 HelicsSequencingModes mode = HELICS_SEQUENCING_MODE_FAST);
469
481 QueryId queryAsync(std::string_view target,
482 std::string_view queryStr,
483 HelicsSequencingModes mode = HELICS_SEQUENCING_MODE_FAST);
484
494 QueryId queryAsync(std::string_view queryStr,
495 HelicsSequencingModes mode = HELICS_SEQUENCING_MODE_FAST);
496
506 std::string queryComplete(QueryId queryIndex);
507
511 bool isQueryCompleted(QueryId queryIndex) const;
512
521 void setQueryCallback(const std::function<std::string(std::string_view)>& queryFunction);
522
528 void setGlobal(std::string_view valueName, std::string_view value);
533 void addAlias(std::string_view interfaceName, std::string_view alias);
542 void sendCommand(
543 std::string_view target,
544 std::string_view commandStr,
545 HelicsSequencingModes mode = HelicsSequencingModes::HELICS_SEQUENCING_MODE_FAST);
546
551 std::pair<std::string, std::string> getCommand();
552
557 std::pair<std::string, std::string> waitCommand();
558
563 void addDependency(std::string_view fedName);
564
570 Filter& registerGlobalFilter(std::string_view filterName,
571 std::string_view inputType = std::string_view{},
572 std::string_view outputType = std::string_view{});
573
580 CloningFilter& registerGlobalCloningFilter(std::string_view filterName,
581 std::string_view inputType = std::string_view{},
582 std::string_view outputType = std::string_view{});
583
590 Filter& registerFilter(std::string_view filterName,
591 std::string_view inputType = std::string_view{},
592 std::string_view outputType = std::string_view{});
593
602 CloningFilter& registerCloningFilter(std::string_view filterName,
603 std::string_view inputType = std::string_view{},
604 std::string_view outputType = std::string_view{});
605
608 Filter& registerFilter()
609 {
610 return registerGlobalFilter(std::string(), std::string_view{}, std::string_view{});
611 }
612
619 Translator& registerGlobalTranslator(std::int32_t translatorType,
620 std::string_view translatorName,
621 std::string_view endpointType = std::string_view{},
622 std::string_view units = std::string_view{});
623
631 Translator& registerTranslator(std::int32_t translatorType,
632 std::string_view translatorName,
633 std::string_view endpointType = std::string_view{},
634 std::string_view units = std::string_view{});
635
641 Translator& registerGlobalTranslator(std::string_view translatorName,
642 std::string_view endpointType = std::string_view{},
643 std::string_view units = std::string_view{})
644 {
645 return registerGlobalTranslator(0, translatorName, endpointType, units);
646 }
647
654 Translator& registerTranslator(std::string_view translatorName,
655 std::string_view endpointType = std::string_view{},
656 std::string_view units = std::string_view{})
657 {
658 return registerTranslator(0, translatorName, endpointType, units);
659 }
660
663 Translator& registerTranslator() { return registerGlobalTranslator(""); }
666 CloningFilter& registerCloningFilter()
667 {
668 return registerGlobalCloningFilter(std::string(), std::string(), std::string());
669 }
670
674 const Filter& getFilter(std::string_view filterName) const;
675
679 const Filter& getFilter(int index) const;
680
684 Filter& getFilter(std::string_view filterName);
685
689 Filter& getFilter(int index);
690
700 [[deprecated]] static void setFilterOperator(Filter& filt,
701 std::shared_ptr<FilterOperator> filtOp);
702
704 int getFilterCount() const;
705
706 // translator retrieval
711 const Translator& getTranslator(std::string_view translatorName) const;
712
717 const Translator& getTranslator(int index) const;
718
723 Translator& getTranslator(std::string_view translatorName);
724
729 Translator& getTranslator(int index);
730
740 [[deprecated]] static void setTranslatorOperator(Translator& trans,
741 std::shared_ptr<TranslatorOperator> transOp);
742
744 int getTranslatorCount() const;
746 const std::string& getConfigFile() const { return configFile; }
747
748 protected:
750 void enteringInitializingMode(IterationResult iterating);
751
753 void enteringExecutingMode(iteration_time res);
755 void finalizeOperations();
756 void preTimeRequestOperations(Time nextStep, bool iterating);
757 void postTimeRequestOperations(Time newTime, bool iterating);
759 virtual void updateTime(Time newTime, Time oldTime);
762 virtual void startupToInitializeStateTransition();
765 virtual void initializeToExecuteStateTransition(iteration_time iterate);
767 virtual void disconnectTransition();
770 virtual std::string localQuery(std::string_view queryStr) const;
773 std::string localNameGenerator(std::string_view addition) const;
775 void handleError(int errorCode, std::string_view errorString, bool noThrow);
776 void setAsyncCheck(std::function<bool()> asyncCheck);
777
778 public:
784 virtual void registerInterfaces(const std::string& configString);
790 void registerConnectorInterfaces(const std::string& configString);
796 void registerFilterInterfaces(const std::string& configString)
797 {
798 registerConnectorInterfaces(configString);
799 }
801 auto getID() const noexcept { return fedID; }
803 Modes getCurrentMode() const noexcept { return currentMode.load(); }
806 Time getCurrentTime() const noexcept { return mCurrentTime; }
808 const std::string& getName() const { return mName; }
810 const std::shared_ptr<Core>& getCorePointer() { return coreObject; }
811
816 void logMessage(int level, std::string_view message) const;
817
821 void logErrorMessage(std::string_view message) const
822 {
823 logMessage(HELICS_LOG_LEVEL_ERROR, message);
824 }
828 void logWarningMessage(std::string_view message) const
829 {
830 logMessage(HELICS_LOG_LEVEL_WARNING, message);
831 }
835 void logInfoMessage(std::string_view message) const
836 {
837 logMessage(HELICS_LOG_LEVEL_SUMMARY, message);
838 }
842 void logDebugMessage(std::string_view message) const
843 {
844 logMessage(HELICS_LOG_LEVEL_DEBUG, message);
845 }
847 void completeOperation();
848
849 private:
850 void getCore(const FederateInfo& fedInfo);
852 void verifyCore();
854 void registerFederate(const FederateInfo& fedInfo);
855
857 void updateFederateMode(Modes newMode);
859 void potentialInterfacesStartupSequence();
861 void updateSimulationTime(Time newTime, Time oldTime, bool iterating);
866 void registerConnectorInterfacesJson(const std::string& jsonString);
871 void registerConnectorInterfacesToml(const std::string& tomlString);
874 void registerConnectorInterfacesJsonDetail(const fileops::JsonBuffer& json);
875 bool
876 checkValidFilterType(bool useTypes, FilterTypes opType, const std::string& operation) const;
877 };
878
880 class HELICS_CXX_EXPORT Interface {
881 protected:
882 Core* mCore{nullptr};
883 InterfaceHandle handle{};
884 std::string mName;
885 public:
886 Interface() = default;
887 Interface(Federate* federate, InterfaceHandle hid, std::string_view actName);
888 Interface(Core* core, InterfaceHandle hid, std::string_view actName):
889 mCore(core), handle(hid), mName(actName)
890 {
891 }
892 virtual ~Interface() = default;
895 InterfaceHandle getHandle() const { return handle; }
897 operator InterfaceHandle() const { return handle; }
899 bool isValid() const { return handle.isValid(); }
900 bool operator<(const Interface& inp) const { return (handle < inp.handle); }
901 bool operator>(const Interface& inp) const { return (handle > inp.handle); }
902 bool operator==(const Interface& inp) const { return (handle == inp.handle); }
903 bool operator!=(const Interface& inp) const { return (handle != inp.handle); }
906 const std::string& getLocalName() const { return mName; }
909 const std::string& getName() const;
911 [[deprecated]] const std::string& getTarget() const;
913 void addSourceTarget(std::string_view newTarget, InterfaceType hint = InterfaceType::UNKNOWN);
915 void addDestinationTarget(std::string_view newTarget,
916 InterfaceType hint = InterfaceType::UNKNOWN);
918 void removeTarget(std::string_view targetToRemove);
920 void addAlias(std::string_view alias);
922 const std::string& getInfo() const;
924 void setInfo(std::string_view info);
930 void setTag(std::string_view tag, std::string_view value);
937 const std::string& getTag(std::string_view tag) const;
939 virtual void setOption(int32_t option, int32_t value = 1);
940
942 virtual int32_t getOption(int32_t option) const;
943
949 const std::string& getInjectionType() const;
950
956 const std::string& getExtractionType() const;
957
963 const std::string& getInjectionUnits() const;
964
969 const std::string& getExtractionUnits() const;
972 virtual const std::string& getDisplayName() const = 0;
975 const std::string& getSourceTargets() const;
978 const std::string& getDestinationTargets() const;
980 std::size_t getSourceTargetCount() const;
982 std::size_t getDestinationTargetCount() const;
984 void close();
986 void disconnectFromCore();
987 };
988
992 HELICS_CXX_EXPORT void cleanupHelicsLibrary();
993 } // namespace helics
gmlc::libguarded::shared_guarded
Definition: application_api/Federate.hpp:27
helics::CloningFilter
Definition: Filters.hpp:111
helics::Core
Definition: core/Core.hpp:41
helics::FederateInfo
Definition: FederateInfo.hpp:28
helics::Federate
Definition: application_api/Federate.hpp:48
helics::Federate::getCurrentMode
Modes getCurrentMode() const noexcept
Definition: application_api/Federate.hpp:803
helics::Federate::registerTranslator
Translator & registerTranslator(std::string_view translatorName, std::string_view endpointType=std::string_view{}, std::string_view units=std::string_view{})
Definition: application_api/Federate.hpp:654
helics::Federate::getName
const std::string & getName() const
Definition: application_api/Federate.hpp:808
helics::Federate::getConfigFile
const std::string & getConfigFile() const
Definition: application_api/Federate.hpp:746
helics::Federate::logErrorMessage
void logErrorMessage(std::string_view message) const
Definition: application_api/Federate.hpp:821
helics::Federate::requestNextStep
Time requestNextStep()
Definition: application_api/Federate.hpp:273
helics::Federate::getCorePointer
const std::shared_ptr< Core > & getCorePointer()
Definition: application_api/Federate.hpp:810
helics::Federate::getID
auto getID() const noexcept
Definition: application_api/Federate.hpp:801
helics::Federate::logDebugMessage
void logDebugMessage(std::string_view message) const
Definition: application_api/Federate.hpp:842
helics::Federate::registerCloningFilter
CloningFilter & registerCloningFilter()
Definition: application_api/Federate.hpp:666
helics::Federate::coreObject
std::shared_ptr< Core > coreObject
reference to the core simulation API
Definition: application_api/Federate.hpp:99
helics::Federate::configFile
std::string configFile
any config file used
Definition: application_api/Federate.hpp:102
helics::Federate::registerFilterInterfaces
void registerFilterInterfaces(const std::string &configString)
Definition: application_api/Federate.hpp:796
helics::Federate::logWarningMessage
void logWarningMessage(std::string_view message) const
Definition: application_api/Federate.hpp:828
helics::Federate::getCurrentTime
Time getCurrentTime() const noexcept
Definition: application_api/Federate.hpp:806
helics::Federate::registerTranslator
Translator & registerTranslator()
Definition: application_api/Federate.hpp:663
helics::Federate::Modes
Modes
Definition: application_api/Federate.hpp:51
helics::Federate::requestTimeAdvance
Time requestTimeAdvance(Time timeDelta)
Definition: application_api/Federate.hpp:278
helics::Federate::registerFilter
Filter & registerFilter()
Definition: application_api/Federate.hpp:608
helics::Federate::registerGlobalTranslator
Translator & registerGlobalTranslator(std::string_view translatorName, std::string_view endpointType=std::string_view{}, std::string_view units=std::string_view{})
Definition: application_api/Federate.hpp:641
helics::Federate::logInfoMessage
void logInfoMessage(std::string_view message) const
Definition: application_api/Federate.hpp:835
helics::Filter
Definition: Filters.hpp:39
helics::IdentifierId< IdentifierType, Identifiers::QUERY, invalid_id_value >
helics::InterfaceHandle
Definition: LocalFederateId.hpp:65
helics::Interface
Definition: application_api/Federate.hpp:880
helics::Interface::handle
InterfaceHandle handle
the id as generated by the Federate
Definition: application_api/Federate.hpp:883
helics::Interface::getLocalName
const std::string & getLocalName() const
Definition: application_api/Federate.hpp:906
helics::Interface::isValid
bool isValid() const
Definition: application_api/Federate.hpp:899
helics::Interface::getHandle
InterfaceHandle getHandle() const
Definition: application_api/Federate.hpp:895
helics::Interface::mName
std::string mName
the name or key of the interface
Definition: application_api/Federate.hpp:884
helics::Translator
Definition: application_api/Translator.hpp:35
helics::fileops::JsonBuffer
Definition: JsonProcessingFunctions.hpp:25
helicsTypes.hpp
HELICS_LOG_LEVEL_ERROR
@ HELICS_LOG_LEVEL_ERROR
Definition: helics_enums.h:208
HELICS_LOG_LEVEL_SUMMARY
@ HELICS_LOG_LEVEL_SUMMARY
Definition: helics_enums.h:214
HELICS_LOG_LEVEL_DEBUG
@ HELICS_LOG_LEVEL_DEBUG
Definition: helics_enums.h:225
HELICS_LOG_LEVEL_WARNING
@ HELICS_LOG_LEVEL_WARNING
Definition: helics_enums.h:212
HelicsSequencingModes
HelicsSequencingModes
Definition: helics_enums.h:427
HELICS_SEQUENCING_MODE_FAST
@ HELICS_SEQUENCING_MODE_FAST
Definition: helics_enums.h:429
helics
the main namespace for the helics co-simulation library User functions will be in the helics namespac...
Definition: AsyncFedCallInfo.hpp:14
helics::operator!=
bool operator!=(const SmallBuffer &sb1, const SmallBuffer &sb2)
Definition: SmallBuffer.hpp:412
helics::IterationResult
IterationResult
Definition: CoreTypes.hpp:94
helics::FederateStates::FINISHED
@ FINISHED
the federation has finished its execution
helics::FederateStates::INITIALIZING
@ INITIALIZING
helics::FederateStates::EXECUTING
@ EXECUTING
the federation has entered execution state and it now advancing in time
helics::timeZero
constexpr Time timeZero
Definition: helicsTime.hpp:31
helics::cleanupHelicsLibrary
void cleanupHelicsLibrary()
Definition: Federate.cpp:42
helics::IterationRequest
IterationRequest
Definition: CoreTypes.hpp:103
helics::InterfaceType
InterfaceType
Definition: CoreTypes.hpp:112
helics::FilterTypes
FilterTypes
Definition: Filters.hpp:21
helics::operator==
bool operator==(const SmallBuffer &sb1, const SmallBuffer &sb2)
Definition: SmallBuffer.hpp:406
helics::Time
TimeRepresentation< count_time< 9 > > Time
Definition: helicsTime.hpp:27
helics::iteration_time
Definition: helicsTime.hpp:43