11#include <pybind11/complex.h>
12#include <pybind11/eigen.h>
13#include <pybind11/functional.h>
14#include <pybind11/iostream.h>
15#include <pybind11/pybind11.h>
16#include <pybind11/stl.h>
25namespace py = pybind11;
26using namespace pybind11::literals;
29void addFMIBindings(py::module_ root);
35 const py::handle &item) {
36 if (py::isinstance<CPS::TopologicalNode>(item))
38 else if (py::isinstance<CPS::IdentifiedObject>(item))
41 throw py::type_error(
"SystemTopology.add expects a node, a component, "
42 "or a list of nodes and components");
48 -----------------------
49 The Python bindings provide access to most of the DPsim features implemented in C++.
50 It is possible to run powerflow, quasi-static, dynamic phasor and electromagnetic transient simulations
51 and to parameterize all components of the network from Python.
55 py::enum_<CPS::Logger::Level>(m,
"LogLevel")
56 .value(
"trace", CPS::Logger::Level::trace)
57 .value(
"debug", CPS::Logger::Level::debug)
58 .value(
"info", CPS::Logger::Level::info)
59 .value(
"warn", CPS::Logger::Level::warn)
60 .value(
"err", CPS::Logger::Level::err)
61 .value(
"critical", CPS::Logger::Level::critical)
62 .value(
"off", CPS::Logger::Level::off);
64 py::class_<CPS::Math>(m,
"Math")
65 .def_static(
"single_phase_variable_to_three_phase",
67 .def_static(
"single_phase_parameter_to_three_phase",
69 .def_static(
"single_phase_power_to_three_phase",
72 py::enum_<DPsim::Solver::Behaviour>(m,
"SolverBehaviour")
76 py::enum_<DPsim::Solver::SystemMatrixRecomputationMode>(
77 m,
"SystemMatrixRecomputationMode")
83 py::enum_<CPS::Domain>(m,
"Domain")
88 py::enum_<CPS::PhaseType>(m,
"PhaseType")
96 py::enum_<CPS::PowerflowBusType>(m,
"PowerflowBusType")
102 py::enum_<CPS::GeneratorType>(m,
"GeneratorType")
115 py::enum_<CPS::CouplingMethod>(m,
"CouplingMethod")
120 py::enum_<DPsim::Solver::Type>(m,
"Solver")
125 py::enum_<DPsim::DirectLinearSolverImpl>(m,
"DirectLinearSolverImpl")
135 .value(
"MetalSparseBiCGSTAB",
140 .value(
"HIPSparseBiCGStab",
142 .value(
"HIPSparseLURefactor",
148 py::enum_<DPsim::SCALING_METHOD>(m,
"scaling_method")
153 py::enum_<DPsim::FILL_IN_REDUCTION_METHOD>(m,
"fill_in_reduction_method")
159 py::enum_<DPsim::PARTIAL_REFACTORIZATION_METHOD>(
160 m,
"partial_refactorization_method")
161 .value(
"no_partial_refactorization",
163 .value(
"factorization_path",
165 .value(
"refactorization_restart",
168 py::enum_<DPsim::USE_BTF>(m,
"use_btf")
172 py::enum_<CPS::CSVReader::Mode>(m,
"CSVReaderMode")
176 py::enum_<CPS::CSVReader::DataFormat>(m,
"CSVReaderFormat")
182 py::enum_<DPsim::StateSpaceAnalysisFrame>(m,
"StateSpaceAnalysisFrame")
186 py::enum_<DPsim::StateSpacePoleMapping>(m,
"StateSpacePoleMapping")
190 py::enum_<CPS::WindingReference>(m,
"WindingReference")
202 py::class_<DPsim::DirectLinearSolverConfiguration>(
203 m,
"DirectLinearSolverConfiguration")
205 .def(
"set_fill_in_reduction_method",
207 .def(
"set_scaling_method",
209 .def(
"set_partial_refactorization_method",
211 setPartialRefactorizationMethod)
213 .def(
"get_scaling_method",
215 .def(
"get_fill_in_reduction_method",
217 .def(
"get_partial_refactorization_method",
219 getPartialRefactorizationMethod)
222 py::class_<DPsim::MNAStateSpaceExtractor>(m,
"MNAStateSpaceExtractor")
226 .def(
"get_discrete_state_matrix",
228 py::return_value_policy::reference_internal);
230 py::class_<DPsim::StateSpaceModalAnalysis>(m,
"StateSpaceModalAnalysis")
231 .def(py::init<const DPsim::MNAStateSpaceExtractor &>(),
232 py::keep_alive<1, 2>())
233 .def(
"set_analysis_frame",
235 .def(
"set_global_dq0_frame",
240 .def(
"get_discrete_eigenvalues",
242 py::return_value_policy::reference_internal)
243 .def(
"get_continuous_eigenvalues",
245 py::return_value_policy::reference_internal)
246 .def(
"get_right_eigenvectors",
248 py::return_value_policy::reference_internal)
249 .def(
"get_left_eigenvectors",
251 py::return_value_policy::reference_internal)
252 .def(
"get_participation_factors",
254 py::return_value_policy::reference_internal)
256 py::return_value_policy::reference_internal);
258 py::class_<DPsim::Simulation>(m,
"Simulation")
259 .def(py::init<std::string, CPS::Logger::Level>(),
"name"_a,
260 "loglevel"_a = CPS::Logger::Level::off)
269 "set_sequential_scheduler",
272 std::make_shared<DPsim::SequentialScheduler>(measurementFile));
274 "measurement_file"_a =
"")
277 .def(
"set_pf_keep_last_solution",
279 .def(
"get_pf_keep_last_solution",
281 .def(
"set_pf_base_apparent_power_fallback",
283 .def(
"get_pf_base_apparent_power_fallback",
291 .def(
"set_pf_solver_enforce_q_limits",
293 .def(
"get_pf_solver_enforce_q_limits",
295 .def(
"set_pf_solver_base_voltage_loose_tolerance",
297 .def(
"get_pf_solver_base_voltage_loose_tolerance",
299 .def(
"set_pf_solver_base_voltage_strict_tolerance",
301 .def(
"get_pf_solver_base_voltage_strict_tolerance",
314 .def(
"do_init_from_nodes_and_terminals",
316 .def(
"set_system_matrix_recomputation_mode",
318 .def(
"do_system_matrix_recomputation",
320 .def(
"do_state_space_extraction",
322 py::arg_v(
"value",
true,
"True"))
323 .def(
"get_state_space_extractor",
325 py::return_value_policy::reference_internal)
327 .def(
"set_steady_state_init_acc_limit",
329 .def(
"set_steady_state_init_time_limit",
331 .def(
"do_frequency_parallelization",
336 .def(
"set_solver_component_behaviour",
338 .def(
"set_direct_solver_implementation",
340 .def(
"set_direct_linear_solver_configuration",
345 py::class_<DPsim::RealTimeSimulation, DPsim::Simulation>(m,
346 "RealTimeSimulation")
347 .def(py::init<std::string, CPS::Logger::Level>(),
"name"_a,
348 "loglevel"_a = CPS::Logger::Level::info)
361 py::class_<CPS::SystemTopology, std::shared_ptr<CPS::SystemTopology>>(
367 .def(py::init<CPS::Real>())
376 if (PyErr_WarnEx(PyExc_DeprecationWarning,
377 "SystemTopology.add is deprecated; use "
378 "add_component for components and add_node "
379 "for nodes instead.",
381 throw py::error_already_set();
383 if (py::isinstance<py::list>(obj) ||
384 py::isinstance<py::tuple>(obj)) {
385 for (
const py::handle &item : obj)
391 "Deprecated alias for add_component and add_node.")
392 .def(
"node", py::overload_cast<std::string_view>(
394 .def(
"node", py::overload_cast<CPS::UInt>(
396 .def(
"connect_component",
400 .def(
"connect_component",
408 .def(
"_repr_svg_", &DPsim::SystemTopology::render)
409 .def(
"render_to_file", &DPsim::SystemTopology::renderToFile)
413 .def_property_readonly(
"components_at_node",
422 "systemPF"_a,
"domain"_a)
427 py::class_<DPsim::Interface, std::shared_ptr<DPsim::Interface>>(m,
431 std::shared_ptr<DPsim::DataLoggerInterface>>(m,
432 "DataLoggerInterface")
433 .def(
"log_attribute",
437 "name"_a,
"attr"_a,
"max_cols"_a = 0,
"max_rows"_a = 0)
439 .def(
"log_attribute",
440 py::overload_cast<
const std::vector<CPS::String> &,
445 .def(
"log_attribute",
447 const std::vector<CPS::String> &names,
const CPS::String &attr,
453 std::shared_ptr<DPsim::DataLogger>>(m,
"Logger")
454 .def(py::init<std::string>())
455 .def(py::init<std::string, CPS::Bool, CPS::UInt>(),
"name"_a,
"enabled"_a,
459 .def(
"log_attribute",
463 "name"_a,
"attr"_a,
"max_cols"_a = 0,
"max_rows"_a = 0)
465 .def(
"log_attribute",
466 py::overload_cast<
const std::vector<CPS::String> &,
478 "name"_a,
"attr"_a,
"comp"_a,
"rows_max"_a = 0,
"cols_max"_a = 0)
480 .def(
"log_attribute",
487 std::shared_ptr<DPsim::RealTimeDataLogger>>(m,
488 "RealTimeDataLogger")
490 .def(py::init([](py::object filename,
DPsim::Real final_time,
493 py::module_::import(
"os").attr(
"fspath")(filename);
494 std::string s = py::cast<std::string>(fspath);
495 std::filesystem::path p(s);
496 return std::make_shared<DPsim::RealTimeDataLogger>(p, final_time,
499 "filename"_a,
"final_time"_a,
"time_step"_a)
501 .def(py::init([](py::object filename, std::size_t row_number) {
503 py::module_::import(
"os").attr(
"fspath")(filename);
504 std::string s = py::cast<std::string>(fspath);
505 std::filesystem::path p(s);
506 return std::make_shared<DPsim::RealTimeDataLogger>(p, row_number);
508 "filename"_a,
"row_number"_a)
510 .def(
"log_attribute",
514 "name"_a,
"attr"_a,
"max_cols"_a = 0,
"max_rows"_a = 0)
516 .def(
"log_attribute",
517 py::overload_cast<
const std::vector<CPS::String> &,
529 "name"_a,
"attr"_a,
"comp"_a,
"rows_max"_a = 0,
"cols_max"_a = 0)
534 const std::vector<CPS::String> &names,
const CPS::String &attr,
538 "names"_a,
"attr"_a,
"comp"_a);
541 py::class_<CPS::IdentifiedObject, std::shared_ptr<CPS::IdentifiedObject>>(
542 m,
"IdentifiedObject")
553 py::enum_<CPS::CIM::Reader::VoltageTargetUnit>(m,
554 "CIMReaderVoltageTargetUnit")
559 py::class_<CPS::CIM::Reader>(m,
"CIMReader")
560 .def(py::init<std::string, CPS::Logger::Level, CPS::Logger::Level>(),
561 "name"_a,
"loglevel"_a = CPS::Logger::Level::info,
562 "comploglevel"_a = CPS::Logger::Level::off)
564 CPS::Real,
const std::list<CPS::String> &,
567 .def(
"set_extnet_voltage_target_unit",
571 py::class_<CPS::CSVReader>(m,
"CSVReader")
572 .def(py::init<std::string,
const std::string &,
580 m,
"TopologicalPowerComp");
581 py::class_<CPS::SimPowerComp<CPS::Complex>,
582 std::shared_ptr<CPS::SimPowerComp<CPS::Complex>>,
589 py::class_<CPS::SimPowerComp<CPS::Real>,
590 std::shared_ptr<CPS::SimPowerComp<CPS::Real>>,
596 py::class_<CPS::TopologicalNode, std::shared_ptr<CPS::TopologicalNode>,
598 .def(
"initial_single_voltage",
604 m,
"TopologicalTerminal")
607 .def(
"set_power", py::overload_cast<CPS::MatrixComp>(
610 py::class_<CPS::SimTerminal<CPS::Complex>,
611 std::shared_ptr<CPS::SimTerminal<CPS::Complex>>,
613 py::class_<CPS::SimTerminal<CPS::Real>,
614 std::shared_ptr<CPS::SimTerminal<CPS::Real>>,
618 py::module mEvent = m.def_submodule(
"event",
"events");
619 py::class_<DPsim::Event, std::shared_ptr<DPsim::Event>>(mEvent,
"Event");
620 py::class_<DPsim::SwitchEvent, std::shared_ptr<DPsim::SwitchEvent>,
621 DPsim::Event>(mEvent,
"SwitchEvent", py::multiple_inheritance())
622 .def(py::init<
CPS::Real,
const std::shared_ptr<CPS::Base::Ph1::Switch>,
624 py::class_<DPsim::SwitchEvent3Ph, std::shared_ptr<DPsim::SwitchEvent3Ph>,
625 DPsim::Event>(mEvent,
"SwitchEvent3Ph", py::multiple_inheritance())
626 .def(py::init<
CPS::Real,
const std::shared_ptr<CPS::Base::Ph3::Switch>,
630 py::module mBase = m.def_submodule(
"base",
"base models");
633 py::module mDP = m.def_submodule(
"dp",
"dynamic phasor models");
636 py::module mEMT = m.def_submodule(
"emt",
"electromagnetic-transient models");
639 py::module mSP = m.def_submodule(
"sp",
"static phasor models");
640 mSP.attr(
"SimNode") = mDP.attr(
"SimNode");
643 py::module mSignal = m.def_submodule(
"signal",
"signal models");
651 m.attr(
"__version__") = VERSION_INFO;
653 m.attr(
"__version__") =
"dev";
void addAttributes(py::module_ m)
void addBaseComponents(py::module_ mBase)
void addDPComponents(py::module_ mDP)
void addEMTComponents(py::module_ mEMT)
void addSPComponents(py::module_ mSP)
void addSignalComponents(py::module_ mSignal)
AttributePointer< AttributeBase > Ptr
void setExtnetVoltageTargetUnit(VoltageTargetUnit unit)
SystemTopology loadCIM(Real systemFrequency, const fs::path &filename, Domain domain=Domain::DP, PhaseType phase=PhaseType::Single, GeneratorType genType=GeneratorType::None)
Parses data from CIM files into the CPS data structure.
void assignLoadProfile(SystemTopology &sys, Real start_time=-1, Real time_step=1, Real end_time=-1, CSVReader::Mode mode=CSVReader::Mode::AUTO, CSVReader::DataFormat format=CSVReader::DataFormat::SECONDS)
assign load profile to corresponding load object
std::shared_ptr< IdentifiedObject > Ptr
AttributeBase::Ptr attribute(const String &name) const
Return pointer to an attribute.
spdlog::level::level_enum Level
static void setLogDir(String path)
Set env variable CPS_LOG_DIR and overwrite.
static Matrix singlePhasePowerToThreePhase(Real power)
To convert single phase power to symmetrical three phase.
static Matrix singlePhaseParameterToThreePhase(Real parameter)
To convert single phase parameters to symmetrical three phase ones.
static MatrixComp singlePhaseVariableToThreePhase(Complex var_1ph)
To convert single phase complex variables (voltages, currents) to symmetrical three phase ones.
SimTerminal< VarType >::Ptr terminal(UInt index)
Get pointer to Terminal.
void connect(typename SimNode< VarType >::List nodes)
Sets all nodes and checks for nominal number of Nodes for this Component.
void setIntfVoltage(MatrixVar< VarType > voltage)
void setIntfCurrent(MatrixVar< VarType > current)
std::shared_ptr< SimPowerComp< VarType > > Ptr
void removeNode(const String &name)
Remove node and all components connected to it.
IdentifiedObject::List mComponents
List of network components.
std::shared_ptr< Type > node(UInt index)
Returns TopologicalNode by index in node list.
void initWithPowerflow(const SystemTopology &systemPF, CPS::Domain domain)
Initialize nodes and SG power from PowerFlow.
void removeComponent(const String &name)
Remove system component.
void addNode(TopologicalNode::Ptr topNode)
Adds node and initializes frequencies.
std::map< String, String, std::less<> > listIdObjects() const
void addTearComponent(IdentifiedObject::Ptr component)
Adds component and initializes frequencies.
std::shared_ptr< Type > component(const String &name)
Returns Component by name.
void componentsAtNodeList()
TopologicalNode::List mNodes
List of network nodes.
void addComponents(const IdentifiedObject::List &components)
Add multiple components.
void connectComponentToNodes(typename SimPowerComp< VarType >::Ptr component, typename SimNode< VarType >::List simNodes)
Connect component to simNodes.
void addComponent(IdentifiedObject::Ptr component)
Adds component and initializes frequencies.
IdentifiedObject::List mTearComponents
std::map< TopologicalNode::Ptr, TopologicalPowerComp::List > mComponentsAtNode
Map of network components connected to network nodes.
std::shared_ptr< TopologicalNode > Ptr
Complex initialSingleVoltage(PhaseType phaseType=PhaseType::Single)
void setPower(Complex power)
virtual void logAttribute(const String &name, CPS::AttributeBase::Ptr attr, UInt rowsMax=0, UInt colsMax=0)
void setScalingMethod(SCALING_METHOD scalingMethod)
void setFillInReductionMethod(FILL_IN_REDUCTION_METHOD fillInReductionMethod)
void setBTF(USE_BTF useBTF)
SCALING_METHOD getScalingMethod() const
FILL_IN_REDUCTION_METHOD getFillInReductionMethod() const
Extending Simulation class by real-time functionality.
void run(const Timer::StartClock::duration &startIn=std::chrono::seconds(1))
The Simulation holds a SystemTopology and a Solver.
void setDirectLinearSolverImplementation(DirectLinearSolverImpl directImpl)
void doFrequencyParallelization(Bool value)
Compute phasors of different frequencies in parallel.
void logIdObjAttribute(const String &comp, const String &attr)
void setSteadStIniAccLimit(Real v)
set steady state initialization accuracy limit
CPS::UInt getPFMaxIterations() const
void logLUTimes()
Write LU decomposition times measurements to log file.
void setSolverType(Solver::Type solverType=Solver::Type::MNA)
void setSystem(const CPS::SystemTopology &system)
void setFinalTime(Real finalTime)
void setPFSolverBaseVoltageLooseTolerance(Real tolerance)
void setSystemMatrixRecomputationMode(Solver::SystemMatrixRecomputationMode mode)
Set the system-matrix recomputation mode.
void setSteadStIniTimeLimit(Real v)
set steady state initialization time limit
void setTimeStep(Real timeStep)
void setTearingComponents(CPS::IdentifiedObject::List tearComponents=CPS::IdentifiedObject::List())
Bool getZeroSkipping() const
void setPFKeepLastSolution(Bool value)
Real next()
Run until next time step.
void logStepTimes(String logName)
Write step time measurements to log file.
void setDirectLinearSolverConfiguration(const DirectLinearSolverConfiguration &configuration)
Bool getPFSolverEnforceReactiveLimits() const
void addLogger(DataLoggerInterface::Ptr logger)
Add a new data logger.
void setZeroSkipping(Bool enabled)
Enable or disable exact-zero skipping in matrix assembly and power flow.
void doInitFromNodesAndTerminals(Bool f=true)
void setPFMaxIterations(CPS::UInt value)
void setPFBaseApparentPowerFallback(Real value)
Bool getPFSolverUseSparse() const
void setScheduler(const std::shared_ptr< Scheduler > &scheduler)
Set the scheduling method.
void doSplitSubnets(Bool splitSubnets=true)
void setSolverAndComponentBehaviour(Solver::Behaviour behaviour)
set solver and component to initialization or simulation behaviour
void setDomain(CPS::Domain domain=CPS::Domain::DP)
Real getPFBaseApparentPowerFallback() const
Bool getPFKeepLastSolution() const
void setLogStepTimes(Bool f)
void setPFSolverUseSparse(Bool value)
void setPFSolverEnforceReactiveLimits(Bool value)
Real getPFSolverBaseVoltageLooseTolerance() const
CPS::AttributeBase::Ptr getIdObjAttribute(const String &comp, const String &attr)
CHECK: Can these be deleted? getIdObjAttribute + "**attr =" should suffice.
void addInterface(Interface::Ptr eint)
void start()
Start simulation without advancing in time.
void doSteadyStateInit(Bool f)
activate steady state initialization
void addEvent(Event::Ptr e)
Schedule an event in the simulation.
void doStateSpaceExtraction(Bool value=true)
Enable extraction of the MNA-coupled discrete-time state matrix.
void run()
Run simulation until total time is elapsed.
void setPFSolverBaseVoltageStrictTolerance(Real tolerance)
void logAttribute(String name, CPS::AttributeBase::Ptr attr)
CHECK: Can we store the attribute name / UID intrinsically inside the attribute?
const MNAStateSpaceExtractor & getStateSpaceExtractor(UInt solverIndex=0) const
Real getPFSolverBaseVoltageStrictTolerance() const
void stop()
Stop simulation including scheduler and interfaces.
void doSystemMatrixRecomputation(Bool value)
@ Enabled
Always enable system-matrix recomputation.
@ Auto
Select the mode automatically based on the system topology.
@ Disabled
Always disable system-matrix recomputation.
void setAnalysisFrame(StateSpaceAnalysisFrame frame)
const std::vector< String > & getStateNames() const
const CPS::VectorComp & getContinuousEigenvalues() const
const CPS::VectorComp & getDiscreteEigenvalues() const
Eigenvalues of the extracted discrete-time state matrix in the selected analysis frame.
void setPoleMapping(StateSpacePoleMapping mapping)
void update()
Update modal quantities from the current extracted state matrix.
void setGlobalDq0Frame(Real omega, Real theta0=0.0)
const CPS::MatrixComp & getLeftEigenvectors() const
const CPS::MatrixComp & getRightEigenvectors() const
const CPS::MatrixComp & getParticipationFactors() const
#define RMS3PH_TO_PEAK1PH
#define PEAK1PH_TO_RMS3PH
PYBIND11_DECLARE_HOLDER_TYPE(T, CPS::AttributePointer< T >)
static void systemTopologyAddSingle(DPsim::SystemTopology &sys, const py::handle &item)
PYBIND11_MODULE(dpsimpy, m)
Eigen::Matrix< Real, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor > Matrix
Dense matrix for real numbers.
@ NO_PARTIAL_REFACTORIZATION
@ REFACTORIZATION_RESTART
CPS::SystemTopology SystemTopology
void printAttribute(CPS::IdentifiedObject &obj, std::string attrName)
std::string getAttributeList(CPS::IdentifiedObject &obj)
void printAttributes(CPS::IdentifiedObject &obj)