DPsim
Loading...
Searching...
No Matches
Utils.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
10#include <string>
11
12#include <dpsim/Config.h>
13#include <dpsim/Utils.h>
14
15using namespace DPsim;
16using namespace DPsim::Utils;
17using namespace CPS;
18
19#ifdef HAVE_GETOPT
20#include <getopt.h>
21#else
22#include <dpsim/Compat/getopt.h>
23#endif
24
25CommandLineArgs::CommandLineArgs(int argc, char *argv[], String nm, Real dt,
26 Real d, Real sf, Int s, CPS::Logger::Level ll,
27 CPS::Logger::Level clill, Bool ss, Bool b,
28 Bool si, CPS::Domain sd, Solver::Type st,
30 String ps)
31 : mProgramName(argv[0]),
33 {"start-synch", no_argument, 0, 'S', NULL, ""},
34 {"steady-init", no_argument, 0, 'I', NULL, ""},
35 {"blocking", no_argument, 0, 'b', NULL, ""},
36 {"help", no_argument, 0, 'h', NULL, ""},
37 {"timestep", required_argument, 0, 't', "SECS",
38 "Simulation time-step"},
39 {"duration", required_argument, 0, 'd', "SECS",
40 "Simulation duration"},
41 {"system-freq", required_argument, 0, 'f', "HZ", "System Frequency"},
42 {"scenario", required_argument, 0, 's', "NUM", "Scenario selection"},
43 {"log-level", required_argument, 0, 'l', "(NONE|INFO|DEBUG|WARN|ERR)",
44 "Logging level"},
45 {"start-at", required_argument, 0, 'a', "ISO8601",
46 "Start time of real-time simulation"},
47 {"start-in", required_argument, 0, 'i', "SECS", ""},
48 {"solver-domain", required_argument, 0, 'D', "(SP|DP|EMT)",
49 "Domain of solver"},
50 {"solver-type", required_argument, 0, 'T', "(NRP|MNA)",
51 "Type of solver"},
52 {"linear-solver-impl", required_argument, 0, 'U',
53 "(DenseLU|SparseLU|KLU|CUDADense|CUDASparse|MetalDense|"
54 "MetalSparseBiCGSTAB)",
55 "Type of direct linear solver implementation"},
56 {"option", required_argument, 0, 'o', "KEY=VALUE",
57 "User-definable options"},
58 {"name", required_argument, 0, 'n', "NAME", "Name of log files"},
59 {"params", required_argument, 0, 'p', "PATH",
60 "Json file containing parametrization"},
61 {0}},
62 timeStep(dt), duration(d), sysFreq(sf), scenario(s), logLevel(ll),
63 cliLogLevel(clill), name(nm), params(ps), startSynch(ss), blocking(b),
64 steadyInit(si), solver{sd, st}, directImpl(mi), solverPluginName(spn) {
65 parseArguments(argc, argv);
66}
67
70 CPS::Logger::Level clill, Bool ss, Bool b,
71 Bool si, CPS::Domain sd, Solver::Type st,
73 : mProgramName("dpsim"),
75 {"start-synch", no_argument, 0, 'S', NULL, ""},
76 {"steady-init", no_argument, 0, 'I', NULL, ""},
77 {"blocking", no_argument, 0, 'b', NULL, ""},
78 {"help", no_argument, 0, 'h', NULL, ""},
79 {"timestep", required_argument, 0, 't', "SECS",
80 "Simulation time-step"},
81 {"duration", required_argument, 0, 'd', "SECS",
82 "Simulation duration"},
83 {"system-freq", required_argument, 0, 'f', "HZ", "System Frequency"},
84 {"scenario", required_argument, 0, 's', "NUM", "Scenario selection"},
85 {"log-level", required_argument, 0, 'l', "(NONE|INFO|DEBUG|WARN|ERR)",
86 "Logging level"},
87 {"start-at", required_argument, 0, 'a', "ISO8601",
88 "Start time of real-time simulation"},
89 {"start-in", required_argument, 0, 'i', "SECS", ""},
90 {"solver-domain", required_argument, 0, 'D', "(SP|DP|EMT)",
91 "Domain of solver"},
92 {"solver-type", required_argument, 0, 'T', "(NRP|MNA)",
93 "Type of solver"},
94 {"linear-solver-impl", required_argument, 0, 'U',
95 "(DenseLU|SparseLU|KLU|CUDADense|CUDASparse|MetalDense|"
96 "MetalSparseBiCGSTAB)",
97 "Type of direct linear solver implementation"},
98 {"option", required_argument, 0, 'o', "KEY=VALUE",
99 "User-definable options"},
100 {"name", required_argument, 0, 'n', "NAME", "Name of log files"},
101 {0}},
102 timeStep(dt), duration(d), sysFreq(sf), scenario(s), logLevel(ll),
103 cliLogLevel(clill), name(nm), startSynch(ss), blocking(b), steadyInit(si),
104 solver{sd, st}, directImpl(mi), solverPluginName(spn) {}
105
106void CommandLineArgs::parseArguments(int argc, char *argv[]) {
107 mProgramName = argv[0];
108 std::vector<option> long_options;
109 for (auto a : mArguments)
110 long_options.push_back({a.name, a.has_arg, a.flag, a.val});
111
112 int c;
113 while (1) {
114 /* getopt_long stores the option index here. */
115 int option_index = 0;
116
117 c = getopt_long(argc, argv,
118 "ht:d:s:l:a:i:f:D:P:T:U:o:Sbn:", long_options.data(),
119 &option_index);
120
121 /* Detect the end of the options. */
122 if (c == -1)
123 break;
124
125 switch (c) {
126 case 'S':
127 startSynch = true;
128 break;
129
130 case 'I':
131 steadyInit = true;
132 break;
133
134 case 'b':
135 blocking = true;
136 break;
137
138 case 't':
139 timeStep = std::stod(optarg);
140 break;
141
142 case 'd':
143 duration = std::stod(optarg);
144 break;
145
146 case 'f':
147 sysFreq = std::stod(optarg);
148 break;
149
150 case 's':
151 scenario = std::stoi(optarg);
152 break;
153
154 case 'o': {
155 String arg = optarg;
156
157 auto p = arg.find("=");
158 auto key = arg.substr(0, p);
159 auto value = arg.substr(p + 1);
160 if (p != String::npos)
161 options[key] = value;
162
163 break;
164 }
165
166 case 'l': {
167 String arg = optarg;
168
169 if (arg == "DEBUG")
170 logLevel = Logger::Level::debug;
171 else if (arg == "INFO")
172 logLevel = Logger::Level::info;
173 else if (arg == "ERR")
174 logLevel = Logger::Level::err;
175 else if (arg == "WARN")
176 logLevel = Logger::Level::warn;
177 else if (arg == "NONE")
178 logLevel = Logger::Level::off;
179 else
180 throw std::invalid_argument("Invalid value for --log-level: must be a "
181 "string of DEBUG, INFO, ERR, WARN or NONE");
182 break;
183 }
184
185 case 'D': {
186 String arg = optarg;
187
188 if (arg == "DP")
189 solver.domain = Domain::DP;
190 else if (arg == "EMT")
191 solver.domain = Domain::EMT;
192 else if (arg == "SP")
193 solver.domain = Domain::SP;
194 else
195 throw std::invalid_argument("Invalid value for --solver-domain: must "
196 "be a string of SP, DP, EMT");
197 break;
198 }
199
200 case 'T': {
201 String arg = optarg;
202
203 if (arg == "MNA")
205 else if (arg == "NRP")
207 else
208 throw std::invalid_argument(
209 "Invalid value for --solver-type: must be a string of NRP or MNA");
210 break;
211 }
212 case 'U': {
213 String arg = optarg;
214 if (arg == "DenseLU") {
216 } else if (arg == "SparseLU") {
218 } else if (arg == "KLU") {
220 } else if (arg == "CUDADense") {
222 } else if (arg == "CUDASparse") {
224 } else if (arg == "CUDAMagma") {
226 } else if (arg == "MetalDense") {
228 } else if (arg == "MetalSparseBiCGSTAB") {
230 } else if (arg == "HIPDense") {
232 } else if (arg == "HIPSparseBiCGStab") {
234 } else if (arg == "HIPSparseLURefactor") {
236 } else if (arg == "HIPSparseQR") {
238 } else if (arg == "Plugin") {
240 } else {
241 throw std::invalid_argument("Invalid value for --solver-mna-impl");
242 }
243 break;
244 }
245 case 'P': {
247 break;
248 }
249
250 case 'i': {
251 double deltaT = std::stod(optarg);
252
253 startTime = Timer::StartClock::now() +
254 std::chrono::milliseconds(static_cast<int>(deltaT * 1e3));
255
256 break;
257 }
258
259 case 'a': {
260 std::tm t;
261 std::istringstream ss(optarg);
262
263 ss >> std::get_time(&t, "%Y%m%dT%H%M%S");
264
265 if (ss.fail())
266 throw std::invalid_argument(
267 "Invalid value for --start-at: must be a ISO8601 date");
268
269 std::time_t tt = std::mktime(&t);
270
271 startTime = Timer::StartClock::from_time_t(tt);
272
273 break;
274 }
275
276 case 'n':
277 name = optarg;
278 break;
279
280 case 'p':
281 params = optarg;
282 break;
283
284 case 'h':
285 showUsage();
286 exit(0);
287
288 case '?':
289 default:
290 showUsage();
291 exit(-1);
292 }
293 }
294
295 /* Positional arguments like files */
296 while (optind < argc)
297 positional.push_back(argv[optind++]);
298}
299
301 std::cout << "Usage: " << mProgramName << " [OPTIONS] [FILES]" << std::endl;
302 std::cout << std::endl;
303 std::cout << " Available options:" << std::endl;
304
305 for (auto a : mArguments) {
306 if (!a.val)
307 continue;
308
309 std::cout << " -" << static_cast<char>(a.val) << ", --" << a.name;
310
311 if (a.valdesc)
312 std::cout << " " << a.valdesc;
313
314 if (a.desc)
315 std::cout << " " << a.desc;
316
317 std::cout << std::endl;
318 }
319
320 std::cout << std::endl;
321}
322
323std::list<fs::path> CommandLineArgs::positionalPaths() const {
324 std::list<fs::path> paths;
325
326 for (auto p : positional) {
327 paths.emplace_back(p);
328 }
329
330 return paths;
331}
332
334 String buffer;
335 buffer.reserve(data.size());
336 for (size_t pos = 0; pos != data.size(); ++pos) {
337 switch (data[pos]) {
338 case '&':
339 buffer.append("&amp;");
340 break;
341 case '\"':
342 buffer.append("&quot;");
343 break;
344 case '\'':
345 buffer.append("&apos;");
346 break;
347 case '<':
348 buffer.append("&lt;");
349 break;
350 case '>':
351 buffer.append("&gt;");
352 break;
353 default:
354 buffer.append(&data[pos], 1);
355 break;
356 }
357 }
358
359 return buffer;
360}
361
362std::vector<std::string> DPsim::Utils::tokenize(std::string s, char delimiter) {
363 std::vector<std::string> tokens;
364
365 size_t lastPos = 0;
366 size_t curentPos;
367
368 while ((curentPos = s.find(delimiter, lastPos)) != std::string::npos) {
369 const size_t tokenLength = curentPos - lastPos;
370 tokens.push_back(s.substr(lastPos, tokenLength));
371
372 /* Advance in string */
373 lastPos = curentPos + 1;
374 }
375
376 /* Check if there's a last token behind the last delimiter. */
377 if (lastPos != s.length()) {
378 const size_t lastTokenLength = s.length() - lastPos;
379 tokens.push_back(s.substr(lastPos, lastTokenLength));
380 }
381
382 return tokens;
383}
384
385fs::path DPsim::Utils::findFile(const fs::path &name, const fs::path &hint,
386 const std::string &useEnv) {
387#ifdef _WIN32
388 char sep = ';';
389#else
390 char sep = ':';
391#endif
392
393 std::vector<fs::path> searchPaths = {fs::current_path()};
394
395 if (!hint.empty()) {
396 searchPaths.push_back(hint);
397 }
398
399 if (!useEnv.empty() && getenv(useEnv.c_str())) {
400 std::vector<std::string> envPaths = tokenize(getenv(useEnv.c_str()), sep);
401
402 for (std::string envPath : envPaths) {
403 searchPaths.emplace_back(envPath);
404 }
405 }
406
407 for (auto searchPath : searchPaths) {
408 fs::path fullPath;
409
410 if (searchPath.is_relative())
411 fullPath /= fs::current_path();
412
413 fullPath /= searchPath;
414 fullPath /= name;
415
416 if (fs::exists(fullPath)) {
417 return fs::absolute(fullPath);
418 }
419 }
420
421 String searchPathsString;
422 for (auto searchPath : searchPaths)
423 searchPathsString.append(searchPath.string().append("\n"));
424
425 throw std::runtime_error(fmt::format("File not found: {}\nSearch paths:\n{}",
426 name.string(), searchPathsString));
427}
428
429std::list<fs::path> DPsim::Utils::findFiles(std::list<fs::path> filennames,
430 const fs::path &hint,
431 const std::string &useEnv) {
432
433 std::list<fs::path> foundnames;
434
435 for (auto filename : filennames) {
436 auto foundname = findFile(filename, hint, useEnv);
437
438 foundnames.emplace_back(foundname);
439 }
440
441 return foundnames;
442}
443
444#ifdef WITH_JSON
445void DPsim::Utils::applySimulationParametersFromJson(const json config,
446 Simulation &sim) {
447 if (config.contains("timestep"))
448 sim.setTimeStep(config["timestep"].get<double>());
449 if (config.contains("duration"))
450 sim.setFinalTime(config["duration"].get<double>());
451}
452
453void DPsim::Utils::applySynchronousGeneratorParametersFromJson(
454 const json config,
455 std::shared_ptr<CPS::EMT::Ph3::SynchronGeneratorDQ> syngen) {
456 if (config.contains("options")) {
457 Bool containsSyngenOptions = false;
458 for (String attrName : syngen->attrParamNames) {
459 if (config["options"].contains(attrName)) {
460 syngen->attributeTyped<Real>(attrName)->set(
461 config["options"][attrName].get<double>());
462 containsSyngenOptions = true;
463 }
464 }
465 if (containsSyngenOptions)
466 syngen->applyParametersOperationalPerUnit();
467 }
468}
469#endif
spdlog::level::level_enum Level
Definition Logger.h:33
String solverPluginName
Definition Utils.h:96
std::list< String > positional
Definition Utils.h:100
void parseArguments(int argc, char *argv[])
Definition Utils.cpp:106
DPsim::DirectLinearSolverImpl directImpl
Definition Utils.h:95
std::list< fs::path > positionalPaths() const
Definition Utils.cpp:323
CommandLineArgs(int argc, char *argv[], String name="dpsim", Real dt=0.001, Real d=1, Real sf=50, Int s=-1, CPS::Logger::Level ll=CPS::Logger::Level::info, CPS::Logger::Level clill=CPS::Logger::Level::off, Bool ss=false, Bool b=false, Bool si=false, CPS::Domain sd=CPS::Domain::DP, Solver::Type st=Solver::Type::MNA, DirectLinearSolverImpl mi=DirectLinearSolverImpl::KLU, String spn="plugin.so", String params="default.json")
Definition Utils.cpp:25
struct DPsim::CommandLineArgs::@006274247107050243354147375320272025065223106110 solver
std::map< String, String > options
Definition Utils.h:103
std::vector< Argument > mArguments
Definition Utils.h:50
DPsim::Timer::StartClock::time_point startTime
Definition Utils.h:98
CPS::Logger::Level logLevel
Definition Utils.h:82
The Simulation holds a SystemTopology and a Solver.
Definition Simulation.h:31
void setFinalTime(Real finalTime)
Definition Simulation.h:198
void setTimeStep(Real timeStep)
Definition Simulation.h:196
@ required_argument
Definition getopt.h:263
@ no_argument
Definition getopt.h:262
int getopt_long(int nargc, char *const *nargv, const char *options, const struct option *long_options, int *idx)
Definition getopt.h:582
int optind
Definition getopt.h:81
char * optarg
Definition getopt.h:86
struct dps_magma_data data
std::list< fs::path > findFiles(std::list< fs::path > filennames, const fs::path &hint, const std::string &useEnv=std::string())
Definition Utils.cpp:429
String encodeXml(String &data)
Definition Utils.cpp:333
std::vector< std::string > tokenize(std::string s, char delimiter)
Definition Utils.cpp:362
fs::path findFile(const fs::path &name, const fs::path &hint=fs::path(), const std::string &useEnv=std::string())
Definition Utils.cpp:385
CPS::Real Real
Definition Definitions.h:18
CPS::String String
Definition Definitions.h:20
CPS::Int Int
Definition Definitions.h:22
CPS::Bool Bool
Definition Definitions.h:21
DirectLinearSolverImpl
@ HIPSparseLURefactor
@ HIPSparseBiCGStab
@ MetalSparseBiCGSTAB