DPsim
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1/* Copyright 2017-2021 Institute for Automation of Complex Power Systems,
2 * EONERC, RWTH Aachen University
3 *
4 * This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
7 *********************************************************************************/
8
9#include <iomanip>
10
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>
17
18#include <DPsim.h>
20
21#include <DPsimPy.h>
22
24
25namespace py = pybind11;
26using namespace pybind11::literals;
27
28#ifdef DPSIM_WITH_FMI
29void addFMIBindings(py::module_ root);
30#endif
31
35 const py::handle &item) {
36 if (py::isinstance<CPS::TopologicalNode>(item))
37 sys.addNode(item.cast<CPS::TopologicalNode::Ptr>());
38 else if (py::isinstance<CPS::IdentifiedObject>(item))
40 else
41 throw py::type_error("SystemTopology.add expects a node, a component, "
42 "or a list of nodes and components");
43}
44
45PYBIND11_MODULE(dpsimpy, m) {
46 m.doc() = R"pbdoc(
47 DPsim Python bindings
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.
52 )pbdoc";
53
54 //Enums
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);
63
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",
71
72 py::enum_<DPsim::Solver::Behaviour>(m, "SolverBehaviour")
73 .value("Initialization", DPsim::Solver::Behaviour::Initialization)
74 .value("Simulation", DPsim::Solver::Behaviour::Simulation);
75
76 py::enum_<DPsim::Solver::SystemMatrixRecomputationMode>(
77 m, "SystemMatrixRecomputationMode")
80 .value("Disabled",
82
83 py::enum_<CPS::Domain>(m, "Domain")
84 .value("SP", CPS::Domain::SP)
85 .value("DP", CPS::Domain::DP)
86 .value("EMT", CPS::Domain::EMT);
87
88 py::enum_<CPS::PhaseType>(m, "PhaseType")
89 .value("A", CPS::PhaseType::A)
90 .value("B", CPS::PhaseType::B)
91 .value("C", CPS::PhaseType::C)
92 .value("ABC", CPS::PhaseType::ABC)
93 .value("Single", CPS::PhaseType::Single)
94 .value("DC", CPS::PhaseType::DC);
95
96 py::enum_<CPS::PowerflowBusType>(m, "PowerflowBusType")
97 .value("PV", CPS::PowerflowBusType::PV)
98 .value("PQ", CPS::PowerflowBusType::PQ)
99 .value("VD", CPS::PowerflowBusType::VD)
100 .value("None", CPS::PowerflowBusType::None);
101
102 py::enum_<CPS::GeneratorType>(m, "GeneratorType")
103 .value("PVNode", CPS::GeneratorType::PVNode)
104 .value("TransientStability", CPS::GeneratorType::TransientStability)
105 .value("IdealVoltageSource", CPS::GeneratorType::IdealVoltageSource)
106 .value("SG3OrderVBR", CPS::GeneratorType::SG3OrderVBR)
107 .value("SG4OrderVBR", CPS::GeneratorType::SG4OrderVBR)
108 .value("SG5OrderVBR", CPS::GeneratorType::SG5OrderVBR)
109 .value("SG6aOrderVBR", CPS::GeneratorType::SG6aOrderVBR)
110 .value("SG6bOrderVBR", CPS::GeneratorType::SG6bOrderVBR)
111 .value("FullOrderVBR", CPS::GeneratorType::FullOrderVBR)
112 .value("FullOrder", CPS::GeneratorType::FullOrder)
113 .value("NONE", CPS::GeneratorType::None);
114
115 py::enum_<CPS::CouplingMethod>(m, "CouplingMethod")
116 .value("DELAY", CPS::CouplingMethod::DELAY)
117 .value("EXTRAPOLATION_ZOH", CPS::CouplingMethod::EXTRAPOLATION_ZOH)
118 .value("EXTRAPOLATION_LINEAR", CPS::CouplingMethod::EXTRAPOLATION_LINEAR);
119
120 py::enum_<DPsim::Solver::Type>(m, "Solver")
121 .value("MNA", DPsim::Solver::Type::MNA)
122 .value("DAE", DPsim::Solver::Type::DAE)
123 .value("NRP", DPsim::Solver::Type::NRP);
124
125 py::enum_<DPsim::DirectLinearSolverImpl>(m, "DirectLinearSolverImpl")
133#ifdef WITH_METAL
135 .value("MetalSparseBiCGSTAB",
137#endif
138#ifdef WITH_HIP
140 .value("HIPSparseBiCGStab",
142 .value("HIPSparseLURefactor",
144 .value("HIPSparseQR", DPsim::DirectLinearSolverImpl::HIPSparseQR)
145#endif
146 ;
147
148 py::enum_<DPsim::SCALING_METHOD>(m, "scaling_method")
149 .value("no_scaling", DPsim::SCALING_METHOD::NO_SCALING)
150 .value("sum_scaling", DPsim::SCALING_METHOD::SUM_SCALING)
151 .value("max_scaling", DPsim::SCALING_METHOD::MAX_SCALING);
152
153 py::enum_<DPsim::FILL_IN_REDUCTION_METHOD>(m, "fill_in_reduction_method")
158
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",
167
168 py::enum_<DPsim::USE_BTF>(m, "use_btf")
169 .value("no_btf", DPsim::USE_BTF::NO_BTF)
170 .value("do_btf", DPsim::USE_BTF::DO_BTF);
171
172 py::enum_<CPS::CSVReader::Mode>(m, "CSVReaderMode")
173 .value("AUTO", CPS::CSVReader::Mode::AUTO)
174 .value("MANUAL", CPS::CSVReader::Mode::MANUAL);
175
176 py::enum_<CPS::CSVReader::DataFormat>(m, "CSVReaderFormat")
177 .value("HHMMSS", CPS::CSVReader::DataFormat::HHMMSS)
178 .value("SECONDS", CPS::CSVReader::DataFormat::SECONDS)
179 .value("HOURS", CPS::CSVReader::DataFormat::HOURS)
180 .value("MINUTES", CPS::CSVReader::DataFormat::MINUTES);
181
182 py::enum_<DPsim::StateSpaceAnalysisFrame>(m, "StateSpaceAnalysisFrame")
185
186 py::enum_<DPsim::StateSpacePoleMapping>(m, "StateSpacePoleMapping")
188 .value("Logarithmic", DPsim::StateSpacePoleMapping::Logarithmic);
189
190 py::enum_<CPS::WindingReference>(m, "WindingReference")
191 .value("Auto", CPS::WindingReference::Auto)
192 .value("Primary", CPS::WindingReference::Primary)
193 .value("Secondary", CPS::WindingReference::Secondary)
194 .value("Tertiary", CPS::WindingReference::Tertiary);
195
196 m.attr("RMS3PH_TO_PEAK1PH") = RMS3PH_TO_PEAK1PH;
197 m.attr("PEAK1PH_TO_RMS3PH") = PEAK1PH_TO_RMS3PH;
198 m.attr("DOUBLE_EPSILON") = DOUBLE_EPSILON;
199
200 addAttributes(m);
201
202 py::class_<DPsim::DirectLinearSolverConfiguration>(
203 m, "DirectLinearSolverConfiguration")
204 .def(py::init<>())
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)
221
222 py::class_<DPsim::MNAStateSpaceExtractor>(m, "MNAStateSpaceExtractor")
223 .def("is_initialized", &DPsim::MNAStateSpaceExtractor::isInitialized)
224 .def("get_state_count", &DPsim::MNAStateSpaceExtractor::getStateCount)
225 .def("get_time_step", &DPsim::MNAStateSpaceExtractor::getTimeStep)
226 .def("get_discrete_state_matrix",
228 py::return_value_policy::reference_internal);
229
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",
237 "theta0"_a = 0.0)
238 .def("set_pole_mapping", &DPsim::StateSpaceModalAnalysis::setPoleMapping)
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)
255 .def("get_state_names", &DPsim::StateSpaceModalAnalysis::getStateNames,
256 py::return_value_policy::reference_internal);
257
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)
261 .def("name", &DPsim::Simulation::name)
262 .def("set_time_step", &DPsim::Simulation::setTimeStep)
263 .def("set_final_time", &DPsim::Simulation::setFinalTime)
264 .def("add_logger", &DPsim::Simulation::addLogger)
265 .def("set_system", &DPsim::Simulation::setSystem)
266 .def("run", &DPsim::Simulation::run)
267 .def("set_solver", &DPsim::Simulation::setSolverType)
268 .def(
269 "set_sequential_scheduler",
270 [](DPsim::Simulation &sim, const std::string &measurementFile) {
271 sim.setScheduler(
272 std::make_shared<DPsim::SequentialScheduler>(measurementFile));
273 },
274 "measurement_file"_a = "")
275 .def("set_log_step_times", &DPsim::Simulation::setLogStepTimes)
276 .def("log_step_times", &DPsim::Simulation::logStepTimes)
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",
285 .def("set_pf_max_iterations", &DPsim::Simulation::setPFMaxIterations)
286 .def("get_pf_max_iterations", &DPsim::Simulation::getPFMaxIterations)
287 .def("set_pf_solver_use_sparse", &DPsim::Simulation::setPFSolverUseSparse)
288 .def("get_pf_solver_use_sparse", &DPsim::Simulation::getPFSolverUseSparse)
289 .def("set_zero_skipping", &DPsim::Simulation::setZeroSkipping)
290 .def("get_zero_skipping", &DPsim::Simulation::getZeroSkipping)
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",
303 .def("set_domain", &DPsim::Simulation::setDomain)
304 .def("start", &DPsim::Simulation::start)
305 .def("next", &DPsim::Simulation::next)
306 .def("stop", &DPsim::Simulation::stop)
307 .def("get_idobj_attr", &DPsim::Simulation::getIdObjAttribute, "comp"_a,
308 "attr"_a)
309 .def("add_interface", &DPsim::Simulation::addInterface, "interface"_a)
310 .def("log_idobj_attribute", &DPsim::Simulation::logIdObjAttribute,
311 "comp"_a, "attr"_a)
312 .def("log_attribute", &DPsim::Simulation::logAttribute, "name"_a,
313 "attr"_a)
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",
324 &DPsim::Simulation::getStateSpaceExtractor, "solver_index"_a = 0,
325 py::return_value_policy::reference_internal)
326 .def("do_steady_state_init", &DPsim::Simulation::doSteadyStateInit)
327 .def("set_steady_state_init_acc_limit",
329 .def("set_steady_state_init_time_limit",
331 .def("do_frequency_parallelization",
333 .def("do_split_subnets", &DPsim::Simulation::doSplitSubnets)
334 .def("set_tearing_components", &DPsim::Simulation::setTearingComponents)
335 .def("add_event", &DPsim::Simulation::addEvent)
336 .def("set_solver_component_behaviour",
338 .def("set_direct_solver_implementation",
340 .def("set_direct_linear_solver_configuration",
342 .def("log_lu_times", &DPsim::Simulation::logLUTimes);
343
344#ifdef WITH_RT
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)
350 .def("set_time_step", &DPsim::RealTimeSimulation::setTimeStep)
351 .def("set_final_time", &DPsim::RealTimeSimulation::setFinalTime)
352 .def("add_logger", &DPsim::RealTimeSimulation::addLogger)
353 .def("set_system", &DPsim::RealTimeSimulation::setSystem)
354 .def("run",
355 static_cast<void (DPsim::RealTimeSimulation::*)(CPS::Int startIn)>(
358 .def("set_domain", &DPsim::RealTimeSimulation::setDomain);
359#endif
360
361 py::class_<CPS::SystemTopology, std::shared_ptr<CPS::SystemTopology>>(
362 m, "SystemTopology")
367 .def(py::init<CPS::Real>())
368 .def("add_component", &DPsim::SystemTopology::addComponent)
369 .def("add_component", &DPsim::SystemTopology::addComponents)
370 .def("add_node", &DPsim::SystemTopology::addNode)
371 // Deprecated alias for add_component/add_node, kept so that scripts
372 // written before the rename keep working
373 .def(
374 "add",
375 [](DPsim::SystemTopology &sys, const py::object &obj) {
376 if (PyErr_WarnEx(PyExc_DeprecationWarning,
377 "SystemTopology.add is deprecated; use "
378 "add_component for components and add_node "
379 "for nodes instead.",
380 1) == -1)
381 throw py::error_already_set();
382
383 if (py::isinstance<py::list>(obj) ||
384 py::isinstance<py::tuple>(obj)) {
385 for (const py::handle &item : obj)
386 systemTopologyAddSingle(sys, item);
387 } else {
388 systemTopologyAddSingle(sys, obj);
389 }
390 },
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",
397 py::overload_cast<CPS::SimPowerComp<CPS::Real>::Ptr,
400 .def("connect_component",
401 py::overload_cast<CPS::SimPowerComp<CPS::Complex>::Ptr,
404 .def("component",
406 .def("add_tear_component", &DPsim::SystemTopology::addTearComponent)
407#ifdef WITH_GRAPHVIZ
408 .def("_repr_svg_", &DPsim::SystemTopology::render)
409 .def("render_to_file", &DPsim::SystemTopology::renderToFile)
410#endif
411 .def_readwrite("nodes", &DPsim::SystemTopology::mNodes)
412 .def_readwrite("components", &DPsim::SystemTopology::mComponents)
413 .def_property_readonly("components_at_node",
414 [](DPsim::SystemTopology &sys) {
415 // Derived view: rebuild before every read (see #635)
417 return sys.mComponentsAtNode;
418 })
419 .def_readonly("tear_components", &DPsim::SystemTopology::mTearComponents)
420 .def("list_idobjects", &DPsim::SystemTopology::listIdObjects)
421 .def("init_with_powerflow", &DPsim::SystemTopology::initWithPowerflow,
422 "systemPF"_a, "domain"_a)
423 .def("add_components", &DPsim::SystemTopology::addComponents)
424 .def("remove_component", &DPsim::SystemTopology::removeComponent)
425 .def("remove_node", &DPsim::SystemTopology::removeNode);
426
427 py::class_<DPsim::Interface, std::shared_ptr<DPsim::Interface>>(m,
428 "Interface");
429
431 std::shared_ptr<DPsim::DataLoggerInterface>>(m,
432 "DataLoggerInterface")
433 .def("log_attribute",
434 py::overload_cast<const CPS::String &, CPS::AttributeBase::Ptr,
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> &,
443 "names"_a, "attr"_a)
445 .def("log_attribute",
447 const std::vector<CPS::String> &names, const CPS::String &attr,
448 const CPS::IdentifiedObject &comp) {
449 logger.logAttribute(names, comp.attribute(attr));
450 });
451
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,
456 "downsampling"_a)
457 .def_static("set_log_dir", &CPS::Logger::setLogDir)
458 .def_static("get_log_dir", &CPS::Logger::logDir)
459 .def("log_attribute",
460 py::overload_cast<const CPS::String &, CPS::AttributeBase::Ptr,
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> &,
469 "names"_a, "attr"_a)
471 .def(
472 "log_attribute",
473 [](DPsim::DataLogger &logger, const CPS::String &name,
474 const CPS::String &attr, const CPS::IdentifiedObject &comp,
475 CPS::UInt rowsMax, CPS::UInt colsMax) {
476 logger.logAttribute(name, comp.attribute(attr), rowsMax, colsMax);
477 },
478 "name"_a, "attr"_a, "comp"_a, "rows_max"_a = 0, "cols_max"_a = 0)
480 .def("log_attribute",
481 [](DPsim::DataLogger &logger, const std::vector<CPS::String> &names,
482 const CPS::String &attr, const CPS::IdentifiedObject &comp) {
483 logger.logAttribute(names, comp.attribute(attr));
484 });
485#ifdef WITH_RT
487 std::shared_ptr<DPsim::RealTimeDataLogger>>(m,
488 "RealTimeDataLogger")
489
490 .def(py::init([](py::object filename, DPsim::Real final_time,
491 DPsim::Real time_step) {
492 py::object fspath =
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,
497 time_step);
498 }),
499 "filename"_a, "final_time"_a, "time_step"_a)
500
501 .def(py::init([](py::object filename, std::size_t row_number) {
502 py::object fspath =
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);
507 }),
508 "filename"_a, "row_number"_a)
509
510 .def("log_attribute",
511 py::overload_cast<const CPS::String &, CPS::AttributeBase::Ptr,
514 "name"_a, "attr"_a, "max_cols"_a = 0, "max_rows"_a = 0)
515
516 .def("log_attribute",
517 py::overload_cast<const std::vector<CPS::String> &,
520 "names"_a, "attr"_a)
521
522 .def(
523 "log_attribute",
524 [](DPsim::RealTimeDataLogger &logger, const CPS::String &name,
525 const CPS::String &attr, const CPS::IdentifiedObject &comp,
526 CPS::UInt rowsMax, CPS::UInt colsMax) {
527 logger.logAttribute(name, comp.attribute(attr), rowsMax, colsMax);
528 },
529 "name"_a, "attr"_a, "comp"_a, "rows_max"_a = 0, "cols_max"_a = 0)
530
531 .def(
532 "log_attribute",
533 [](DPsim::RealTimeDataLogger &logger,
534 const std::vector<CPS::String> &names, const CPS::String &attr,
535 const CPS::IdentifiedObject &comp) {
536 logger.logAttribute(names, comp.attribute(attr));
537 },
538 "names"_a, "attr"_a, "comp"_a);
539#endif
540
541 py::class_<CPS::IdentifiedObject, std::shared_ptr<CPS::IdentifiedObject>>(
542 m, "IdentifiedObject")
543 .def("name", &CPS::IdentifiedObject::name)
547 .def("attr", &CPS::IdentifiedObject::attribute, "name"_a)
548 .def("print_attribute_list", &printAttributes)
549 .def("print_attribute", &printAttribute, "attribute_name"_a)
550 .def("__str__", &getAttributeList);
551
552#ifdef WITH_CIM
553 py::enum_<CPS::CIM::Reader::VoltageTargetUnit>(m,
554 "CIMReaderVoltageTargetUnit")
558
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)
563 .def("loadCIM", (CPS::SystemTopology(CPS::CIM::Reader::*)(
564 CPS::Real, const std::list<CPS::String> &,
567 .def("set_extnet_voltage_target_unit",
569#endif
570
571 py::class_<CPS::CSVReader>(m, "CSVReader")
572 .def(py::init<std::string, const std::string &,
573 std::map<std::string, std::string> &, CPS::Logger::Level>())
574 .def("assignLoadProfile", &CPS::CSVReader::assignLoadProfile);
575
576 //Base Classes
577
578 py::class_<CPS::TopologicalPowerComp,
579 std::shared_ptr<CPS::TopologicalPowerComp>, CPS::IdentifiedObject>(
580 m, "TopologicalPowerComp");
581 py::class_<CPS::SimPowerComp<CPS::Complex>,
582 std::shared_ptr<CPS::SimPowerComp<CPS::Complex>>,
583 CPS::TopologicalPowerComp>(m, "SimPowerCompComplex")
585 .def("set_intf_current", &CPS::SimPowerComp<CPS::Complex>::setIntfCurrent)
586 .def("set_intf_voltage", &CPS::SimPowerComp<CPS::Complex>::setIntfVoltage)
587 .def("get_terminal", &CPS::SimPowerComp<CPS::Complex>::terminal,
588 "index"_a);
589 py::class_<CPS::SimPowerComp<CPS::Real>,
590 std::shared_ptr<CPS::SimPowerComp<CPS::Real>>,
591 CPS::TopologicalPowerComp>(m, "SimPowerCompReal")
593 .def("set_intf_current", &CPS::SimPowerComp<CPS::Real>::setIntfCurrent)
594 .def("set_intf_voltage", &CPS::SimPowerComp<CPS::Real>::setIntfVoltage)
595 .def("get_terminal", &CPS::SimPowerComp<CPS::Real>::terminal, "index"_a);
596 py::class_<CPS::TopologicalNode, std::shared_ptr<CPS::TopologicalNode>,
597 CPS::IdentifiedObject>(m, "TopologicalNode")
598 .def("initial_single_voltage",
600 "phase_type"_a = CPS::PhaseType::Single);
601
602 py::class_<CPS::TopologicalTerminal,
603 std::shared_ptr<CPS::TopologicalTerminal>, CPS::IdentifiedObject>(
604 m, "TopologicalTerminal")
605 .def("set_power",
606 py::overload_cast<CPS::Complex>(&CPS::TopologicalTerminal::setPower))
607 .def("set_power", py::overload_cast<CPS::MatrixComp>(
609
610 py::class_<CPS::SimTerminal<CPS::Complex>,
611 std::shared_ptr<CPS::SimTerminal<CPS::Complex>>,
612 CPS::TopologicalTerminal>(m, "SimTerminalComplex");
613 py::class_<CPS::SimTerminal<CPS::Real>,
614 std::shared_ptr<CPS::SimTerminal<CPS::Real>>,
615 CPS::TopologicalTerminal>(m, "SimTerminalReal");
616
617 //Events
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>,
623 CPS::Bool>());
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>,
627 CPS::Bool>());
628
629 //Components
630 py::module mBase = m.def_submodule("base", "base models");
631 addBaseComponents(mBase);
632
633 py::module mDP = m.def_submodule("dp", "dynamic phasor models");
634 addDPComponents(mDP);
635
636 py::module mEMT = m.def_submodule("emt", "electromagnetic-transient models");
637 addEMTComponents(mEMT);
638
639 py::module mSP = m.def_submodule("sp", "static phasor models");
640 mSP.attr("SimNode") = mDP.attr("SimNode");
641 addSPComponents(mSP);
642
643 py::module mSignal = m.def_submodule("signal", "signal models");
644 addSignalComponents(mSignal);
645
646#ifdef DPSIM_WITH_FMI
647 addFMIBindings(m);
648#endif
649
650#ifdef VERSION_INFO
651 m.attr("__version__") = VERSION_INFO;
652#else
653 m.attr("__version__") = "dev";
654#endif
655}
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
Definition Attribute.h:122
void setExtnetVoltageTargetUnit(VoltageTargetUnit unit)
Definition Reader.cpp:62
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.
Definition Reader.cpp:249
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
std::vector< Ptr > List
AttributeBase::Ptr attribute(const String &name) const
Return pointer to an attribute.
spdlog::level::level_enum Level
Definition Logger.h:33
static void setLogDir(String path)
Set env variable CPS_LOG_DIR and overwrite.
Definition Logger.cpp:88
static String logDir()
Definition Logger.cpp:81
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.
std::vector< Ptr > List
Definition SimNode.h:35
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.
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::vector< Ptr > List
std::shared_ptr< TopologicalNode > Ptr
Complex initialSingleVoltage(PhaseType phaseType=PhaseType::Single)
virtual void logAttribute(const String &name, CPS::AttributeBase::Ptr attr, UInt rowsMax=0, UInt colsMax=0)
void setFillInReductionMethod(FILL_IN_REDUCTION_METHOD fillInReductionMethod)
FILL_IN_REDUCTION_METHOD getFillInReductionMethod() const
const Matrix & getDiscreteStateMatrix() 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.
Definition Simulation.h:31
void setDirectLinearSolverImplementation(DirectLinearSolverImpl directImpl)
Definition Simulation.h:210
void doFrequencyParallelization(Bool value)
Compute phasors of different frequencies in parallel.
Definition Simulation.h:240
void logIdObjAttribute(const String &comp, const String &attr)
void setSteadStIniAccLimit(Real v)
set steady state initialization accuracy limit
Definition Simulation.h:267
CPS::UInt getPFMaxIterations() const
void logLUTimes()
Write LU decomposition times measurements to log file.
void setSolverType(Solver::Type solverType=Solver::Type::MNA)
Definition Simulation.h:202
void setSystem(const CPS::SystemTopology &system)
Definition Simulation.h:194
String name() const
Definition Simulation.h:346
void setFinalTime(Real finalTime)
Definition Simulation.h:198
void setPFSolverBaseVoltageLooseTolerance(Real tolerance)
void setSystemMatrixRecomputationMode(Solver::SystemMatrixRecomputationMode mode)
Set the system-matrix recomputation mode.
Definition Simulation.h:243
void setSteadStIniTimeLimit(Real v)
set steady state initialization time limit
Definition Simulation.h:265
void setTimeStep(Real timeStep)
Definition Simulation.h:196
void setTearingComponents(CPS::IdentifiedObject::List tearComponents=CPS::IdentifiedObject::List())
Definition Simulation.h:231
Bool getZeroSkipping() const
Definition Simulation.h:288
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)
Definition Simulation.h:214
Bool getPFSolverEnforceReactiveLimits() const
void addLogger(DataLoggerInterface::Ptr logger)
Add a new data logger.
Definition Simulation.h:323
void setZeroSkipping(Bool enabled)
Enable or disable exact-zero skipping in matrix assembly and power flow.
Definition Simulation.h:286
void doInitFromNodesAndTerminals(Bool f=true)
Definition Simulation.h:223
void setPFMaxIterations(CPS::UInt value)
void setPFBaseApparentPowerFallback(Real value)
Bool getPFSolverUseSparse() const
void setScheduler(const std::shared_ptr< Scheduler > &scheduler)
Set the scheduling method.
Definition Simulation.h:236
void doSplitSubnets(Bool splitSubnets=true)
Definition Simulation.h:227
void setSolverAndComponentBehaviour(Solver::Behaviour behaviour)
set solver and component to initialization or simulation behaviour
Definition Simulation.h:206
void setDomain(CPS::Domain domain=CPS::Domain::DP)
Definition Simulation.h:200
Real getPFBaseApparentPowerFallback() const
Bool getPFKeepLastSolution() const
void setLogStepTimes(Bool f)
Definition Simulation.h:259
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)
Definition Simulation.h:335
void start()
Start simulation without advancing in time.
void doSteadyStateInit(Bool f)
activate steady state initialization
Definition Simulation.h:263
void addEvent(Event::Ptr e)
Schedule an event in the simulation.
Definition Simulation.h:321
void doStateSpaceExtraction(Bool value=true)
Enable extraction of the MNA-coupled discrete-time state matrix.
Definition Simulation.h:254
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)
Definition Simulation.h:248
@ Initialization
Definition Solver.h:40
@ Enabled
Always enable system-matrix recomputation.
Definition Solver.h:47
@ Auto
Select the mode automatically based on the system topology.
Definition Solver.h:45
@ Disabled
Always disable system-matrix recomputation.
Definition Solver.h:49
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
Definition Definitions.h:50
#define PEAK1PH_TO_RMS3PH
Definition Definitions.h:51
#define DOUBLE_EPSILON
Definition Definitions.h:14
PYBIND11_DECLARE_HOLDER_TYPE(T, CPS::AttributePointer< T >)
static void systemTopologyAddSingle(DPsim::SystemTopology &sys, const py::handle &item)
Definition main.cpp:34
PYBIND11_MODULE(dpsimpy, m)
Definition main.cpp:45
Eigen::Matrix< Real, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor > Matrix
Dense matrix for real numbers.
Definition Definitions.h:79
std::string String
Definition Definitions.h:63
double Real
Definition Definitions.h:60
int Int
Definition Definitions.h:59
bool Bool
Definition Definitions.h:62
GeneratorType
unsigned int UInt
Definition Definitions.h:58
CPS::Real Real
Definition Definitions.h:18
CPS::SystemTopology SystemTopology
Definition DPsim.h:37
@ HIPSparseLURefactor
@ HIPSparseBiCGStab
@ MetalSparseBiCGSTAB
void printAttribute(CPS::IdentifiedObject &obj, std::string attrName)
Definition Utils.cpp:74
std::string getAttributeList(CPS::IdentifiedObject &obj)
Definition Utils.cpp:13
void printAttributes(CPS::IdentifiedObject &obj)
Definition Utils.cpp:70