GCC Code Coverage Report


Directory: ./
Coverage: low: ≥ 0% medium: ≥ 75.0% high: ≥ 90.0%
Coverage Exec / Excl / Total
Lines: 0.0% 0 / 1 / 392
Functions: 0.0% 0 / 1 / 31
Branches: 0.0% 0 / 1 / 482

src/workflow/RunModelica.cpp
Line Branch Exec Source
1 /***********************************************************************************************************************
2 * OpenStudio(R), Copyright (c) Alliance for Energy Innovation, LLC.
3 * See also https://openstudio.net/license
4 ***********************************************************************************************************************/
5
6 #include "OSWorkflow.hpp"
7 #include "../utilities/core/ApplicationPathHelpers.hpp"
8 #include "../utilities/core/Filesystem.hpp"
9 #include <fmt/format.h>
10 #include <fmt/ranges.h>
11 #include <boost/process.hpp>
12 #include <fstream>
13 #include <thread>
14 #include <set>
15 #include <cstdlib>
16 #include <sstream>
17 #include <stdexcept>
18 #include <string_view>
19 #include <vector>
20 #include <optional>
21
22 namespace openstudio {
23
24 − REGISTER_LOGGER("openstudio.workflow.RunModelica");
25
26 namespace {
27 // The Modelica compilers print lightweight XML-ish tags in their stdout to signal structured events.
28 // Current tags:
29 // <Modelica-Error> ... </Modelica-Error> Fatal errors detected while setting parameters or running simulate().
30 // <Modelica-Warn> ... </Modelica-Warn> Non-fatal issues (eg, setParameterValue failure).
31 // <Modelica-ResultFile>path</Modelica-ResultFile> Absolute result-file path when a run succeeds.
32 // Each payload may span multiple lines; the parser below preserves newlines and trims outer whitespace before logging.
33 // The reader loop feeds compiler stdout/stderr through parseModelicaTaggedOutput and logs the structured messages,
34 // keeping raw stdout/stderr logs intact for debugging while still surfacing key events in OpenStudio logs.
35 struct ModelicaCompilerOutput
36 {
37 std::vector<std::string> errors;
38 std::vector<std::string> warnings;
39 std::optional<std::string> simulationResultFile;
40
41 ✗ bool empty() const {
42 ✗ return errors.empty() && warnings.empty() && !simulationResultFile.has_value();
43 }
44 };
45
46 struct ModelicaTagParserState
47 {
48 bool collecting = false;
49 bool needsNewline = false;
50 std::string activeTag;
51 std::string closingTag;
52 std::string buffer;
53 };
54
55 ✗ std::string trimTagPayload(std::string_view view) {
56 ✗ const auto start = view.find_first_not_of(" \t\r\n");
57 ✗ if (start == std::string_view::npos) {
58 ✗ return {};
59 }
60 ✗ const auto end = view.find_last_not_of(" \t\r\n");
61 ✗ return std::string(view.substr(start, end - start + 1));
62 }
63
64 ✗ void recordCompilerSegment(const std::string& tag, std::string payload, ModelicaCompilerOutput& output) {
65 ✗ auto message = trimTagPayload(payload);
66 ✗ if (message.empty()) {
67 ✗ message = std::move(payload);
68 }
69 ✗ if (tag == "Modelica-Error") {
70 ✗ output.errors.push_back(std::move(message));
71 ✗ } else if (tag == "Modelica-Warn") {
72 ✗ output.warnings.push_back(std::move(message));
73 ✗ } else if (tag == "Modelica-Simulation-ResultFile") {
74 ✗ output.simulationResultFile = std::move(message);
75 }
76 ✗ }
77
78 constexpr const char* kWorkflowLogChannel = "openstudio.workflow.OSWorkflow";
79
80 ✗ void logCompilerOutput(const ModelicaCompilerOutput& output, bool echoingStdout) {
81 ✗ if (!echoingStdout) {
82 ✗ for (const auto& err : output.errors) {
83 ✗ LOG_FREE(Error, kWorkflowLogChannel, "Modelica compiler reported error: " << err);
84 }
85 ✗ for (const auto& warn : output.warnings) {
86 ✗ LOG_FREE(Warn, kWorkflowLogChannel, "Modelica compiler reported warning: " << warn);
87 }
88 ✗ if (output.simulationResultFile) {
89 ✗ LOG_FREE(Info, kWorkflowLogChannel, "Modelica compiler produced simulation result file: " << *output.simulationResultFile);
90 }
91 }
92 ✗ }
93
94 ✗ ModelicaCompilerOutput parseModelicaTaggedOutput(std::string_view text, ModelicaTagParserState& state) {
95 ✗ ModelicaCompilerOutput output;
96
97 ✗ auto flushActiveTag = [&](const std::string& finalChunk) {
98 ✗ if (!finalChunk.empty()) {
99 ✗ if (!state.buffer.empty()) {
100 ✗ state.buffer.append(finalChunk);
101 } else {
102 ✗ state.buffer = finalChunk;
103 }
104 }
105 ✗ recordCompilerSegment(state.activeTag, state.buffer, output);
106 ✗ state.collecting = false;
107 ✗ state.needsNewline = false;
108 ✗ state.activeTag.clear();
109 ✗ state.closingTag.clear();
110 ✗ state.buffer.clear();
111 ✗ };
112
113 ✗ size_t cursor = 0;
114 ✗ while (cursor < text.size()) {
115 ✗ if (state.collecting) {
116 ✗ if (state.needsNewline && !state.buffer.empty()) {
117 ✗ state.buffer.push_back('\n');
118 }
119 ✗ state.needsNewline = false;
120
121 ✗ const auto closingPos = text.find(state.closingTag, cursor);
122 ✗ if (closingPos == std::string::npos) {
123 ✗ if (cursor < text.size()) {
124 ✗ state.buffer.append(text.substr(cursor));
125 }
126 ✗ state.needsNewline = true;
127 ✗ cursor = text.size();
128 ✗ break;
129 }
130
131 ✗ if (closingPos > cursor) {
132 ✗ state.buffer.append(text.substr(cursor, closingPos - cursor));
133 }
134 ✗ const size_t closingTagLen = state.closingTag.size();
135 ✗ flushActiveTag({});
136 ✗ cursor = closingPos + closingTagLen;
137 ✗ continue;
138 ✗ }
139
140 ✗ const auto startPos = text.find('<', cursor);
141 ✗ if (startPos == std::string::npos) {
142 ✗ break;
143 }
144 ✗ const auto closePos = text.find('>', startPos);
145 ✗ if (closePos == std::string::npos) {
146 ✗ break;
147 }
148
149 ✗ auto tagNameView = text.substr(startPos + 1, closePos - startPos - 1);
150 ✗ if (tagNameView.empty() || tagNameView.front() == '/') {
151 ✗ cursor = closePos + 1;
152 ✗ continue;
153 }
154
155 ✗ std::string tagName(tagNameView);
156 ✗ std::string closingTag = "</" + tagName + ">";
157 ✗ const size_t payloadStart = closePos + 1;
158 ✗ const auto closingPos = text.find(closingTag, payloadStart);
159 ✗ if (closingPos == std::string::npos) {
160 ✗ state.collecting = true;
161 ✗ state.activeTag = std::move(tagName);
162 ✗ state.closingTag = std::move(closingTag);
163 ✗ state.buffer.assign(text.substr(payloadStart));
164 ✗ state.needsNewline = true;
165 ✗ break;
166 }
167
168 ✗ std::string payload(text.substr(payloadStart, closingPos - payloadStart));
169 ✗ recordCompilerSegment(tagName, std::move(payload), output);
170 ✗ cursor = closingPos + closingTag.size();
171 ✗ }
172
173 ✗ return output;
174 ✗ }
175
176 ✗ ModelicaCompilerOutput finalizeModelicaTaggedOutput(ModelicaTagParserState& state) {
177 ✗ ModelicaCompilerOutput output;
178 ✗ if (state.collecting && !state.buffer.empty()) {
179 ✗ recordCompilerSegment(state.activeTag, state.buffer, output);
180 }
181 ✗ state.collecting = false;
182 ✗ state.needsNewline = false;
183 ✗ state.activeTag.clear();
184 ✗ state.closingTag.clear();
185 ✗ state.buffer.clear();
186 ✗ return output;
187 ✗ }
188
189 struct ModelicaSetup
190 {
191 std::vector<openstudio::path> files;
192 std::vector<openstudio::path> searchPaths;
193 };
194
195 ✗ std::string_view compilerDisplayName(ModelicaCompilerType type) {
196 ✗ switch (type) {
197 ✗ case ModelicaCompilerType::OpenModelica:
198 ✗ return "OpenModelica";
199 ✗ case ModelicaCompilerType::Dymola:
200 ✗ return "Dymola";
201 }
202 ✗ return "";
203 }
204
205 ✗ std::string modelicaStringLiteral(std::string_view raw) {
206 ✗ std::string escaped;
207 ✗ escaped.reserve(raw.size() * 2);
208 ✗ for (const char ch : raw) {
209 ✗ if (ch == '\\' || ch == '"') {
210 ✗ escaped.push_back('\\');
211 }
212 ✗ escaped.push_back(ch);
213 }
214 ✗ return fmt::format("\"{}\"", escaped);
215 ✗ }
216
217 ✗ std::vector<openstudio::path> getModelicaPathEnvEntries() {
218 ✗ std::vector<openstudio::path> result;
219 ✗ const char* raw = std::getenv("MODELICAPATH"); // NOLINT
220 ✗ if (!raw) {
221 ✗ return result;
222 }
223
224 #ifdef _WIN32
225 constexpr char separator = ';';
226 #else
227 ✗ constexpr char separator = ':';
228 #endif
229
230 ✗ std::string pathList(raw);
231 ✗ std::stringstream ss(pathList);
232 ✗ std::string token;
233 ✗ while (std::getline(ss, token, separator)) {
234 ✗ if (token.empty()) {
235 ✗ continue;
236 }
237 ✗ result.emplace_back(openstudio::toPath(token));
238 }
239 ✗ return result;
240 ✗ }
241
242 ✗ void dedupePaths(std::vector<openstudio::path>& paths) {
243 ✗ std::set<std::string> seen;
244 ✗ std::vector<openstudio::path> unique;
245 ✗ unique.reserve(paths.size());
246
247 ✗ for (const auto& path : paths) {
248 ✗ if (path.empty()) {
249 ✗ continue;
250 }
251 ✗ const auto absolutePath = boost::filesystem::absolute(path);
252 ✗ const std::string& key = absolutePath.generic_string();
253 ✗ if (seen.insert(key).second) {
254 ✗ unique.push_back(absolutePath);
255 }
256 ✗ }
257
258 ✗ paths = std::move(unique);
259 ✗ }
260
261 ✗ ModelicaSetup getModelicaSetup(const WorkflowJSON& workflowJSON, const boost::optional<openstudio::path>& finalSeedModelicaFile) {
262 ✗ ModelicaSetup setup;
263
264 ✗ auto addSearchPath = [&setup](const openstudio::path& dir) {
265 ✗ if (dir.empty()) {
266 ✗ return;
267 }
268 ✗ setup.searchPaths.push_back(dir);
269 ✗ };
270
271 ✗ auto addFileToLoad = [&setup, &addSearchPath](const openstudio::path& file) {
272 ✗ if (file.empty()) {
273 ✗ return;
274 }
275 ✗ const auto absoluteFile = boost::filesystem::absolute(file);
276 ✗ setup.files.push_back(absoluteFile);
277 ✗ addSearchPath(absoluteFile.parent_path());
278 ✗ };
279
280 ✗ const auto handleDirectory = [&addFileToLoad, &addSearchPath](const openstudio::path& dir) {
281 ✗ const auto absoluteDir = boost::filesystem::absolute(dir);
282 ✗ addSearchPath(absoluteDir);
283 ✗ const auto packageMo = absoluteDir / toPath("package.mo");
284 ✗ if (openstudio::filesystem::exists(packageMo)) {
285 ✗ addFileToLoad(packageMo);
286 }
287 ✗ };
288
289 ✗ for (const auto& envPath : getModelicaPathEnvEntries()) {
290 ✗ addSearchPath(envPath);
291 ✗ }
292
293 ✗ for (const auto& packageSpec : workflowJSON.modelicaPackages()) {
294 ✗ openstudio::path resolved;
295 ✗ if (packageSpec.is_absolute()) {
296 ✗ resolved = packageSpec;
297 } else {
298 ✗ if (auto located = workflowJSON.findFile(packageSpec)) {
299 ✗ resolved = *located;
300 ✗ }
301 }
302
303 ✗ if (resolved.empty()) {
304 ✗ throw std::runtime_error(fmt::format("Modelica package '{}' could not be resolved", toString(packageSpec)));
305 }
306
307 ✗ if (!openstudio::filesystem::exists(resolved)) {
308 ✗ throw std::runtime_error(fmt::format("Modelica package '{}' does not exist at '{}'", toString(packageSpec), resolved.generic_string()));
309 }
310
311 ✗ if (openstudio::filesystem::is_directory(resolved)) {
312 ✗ handleDirectory(resolved);
313 } else {
314 ✗ addFileToLoad(resolved);
315 }
316 ✗ }
317
318 ✗ if (finalSeedModelicaFile) {
319 ✗ if (openstudio::filesystem::is_directory(*finalSeedModelicaFile)) {
320 ✗ handleDirectory(*finalSeedModelicaFile);
321 } else {
322 ✗ addFileToLoad(*finalSeedModelicaFile);
323 }
324 ✗ } else if (auto seedModelicaFile = workflowJSON.seedModelicaFile()) {
325 ✗ if (auto resolved = workflowJSON.findFile(seedModelicaFile.get())) {
326 ✗ if (openstudio::filesystem::is_directory(*resolved)) {
327 ✗ handleDirectory(*resolved);
328 } else {
329 ✗ addFileToLoad(*resolved);
330 }
331 ✗ }
332 ✗ }
333
334 ✗ dedupePaths(setup.files);
335 ✗ dedupePaths(setup.searchPaths);
336
337 ✗ return setup;
338 ✗ }
339
340 ✗ std::string buildDymolaSetModelicaPathCommand(const std::vector<openstudio::path>& searchPaths) {
341 #ifdef _WIN32
342 constexpr const char* separatorLiteral = "\";\"";
343 #else
344 ✗ constexpr const char* separatorLiteral = "\":\"";
345 #endif
346
347 // Dymola reads MODELICAPATH directly, so build a single path string that can
348 // be applied via Modelica.Utilities.System.setEnvironmentVariable before
349 // loading any packages.
350
351 ✗ std::string expression;
352 ✗ for (const auto& searchPath : searchPaths) {
353 ✗ if (expression.empty()) {
354 ✗ expression = modelicaStringLiteral(searchPath.generic_string());
355 } else {
356 ✗ expression = fmt::format("{} + {} + {}", expression, separatorLiteral, modelicaStringLiteral(searchPath.generic_string()));
357 }
358 }
359
360 ✗ if (expression.empty()) {
361 ✗ expression = "\"\"";
362 }
363
364 ✗ return fmt::format("Modelica.Utilities.System.setEnvironmentVariable(\"MODELICAPATH\", {});\n", expression);
365 ✗ }
366
367 ✗ std::string buildSetModelicaPathCommand(ModelicaCompilerType compilerType, const std::vector<openstudio::path>& searchPaths) {
368 ✗ switch (compilerType) {
369 ✗ case ModelicaCompilerType::OpenModelica:
370 ✗ return {};
371 ✗ case ModelicaCompilerType::Dymola:
372 ✗ return buildDymolaSetModelicaPathCommand(searchPaths);
373 }
374 ✗ return {};
375 }
376
377 template <typename T, typename Formatter>
378 ✗ std::string formatModelicaArray(const std::vector<T>& values, Formatter formatter) {
379 ✗ std::string buffer = "{";
380 ✗ bool first = true;
381 ✗ for (const auto& value : values) {
382 ✗ if (!first) {
383 ✗ buffer.append(", ");
384 }
385 ✗ buffer.append(formatter(value));
386 ✗ first = false;
387 }
388 ✗ buffer.push_back('}');
389 ✗ return buffer;
390 ✗ }
391
392 ✗ openstudio::path createOpenModelicaScript(const WorkflowJSON& workflowJSON, const ModelicaSetup& setup, const measure::ModelicaParameters& params) {
393 ✗ auto seedModelicaModel = workflowJSON.seedModelicaModel();
394 // There is a check for seedModelicaModel, prior to reaching this point.
395 // In other words, we shouldn't be trying to "runModelica" if there is no seed model.
396 ✗ OS_ASSERT(seedModelicaModel);
397
398 // Generate a temporary OpenModelica script (run.mos) that mirrors what the CLI achieves manually.
399 ✗ constexpr auto mosPath = "run.mos";
400 ✗ std::ofstream mosFile(mosPath);
401
402 ✗ mosFile << "echo(false);\n";
403
404 ✗ auto loadFile = [&mosFile](const openstudio::path& file) {
405 ✗ mosFile << fmt::format(R"(
406 clearMessages();
407 res := loadFile("{0}");
408 if not res then
409 err := getErrorString();
410 if err == "" then
411 print("<Modelica-Warn>OpenModelica loadFile(...) produced an unspecified error.</Modelica-Warn>\n");
412 else
413 print("<Modelica-Error>OpenModleica loadFile(...) error: " + err + "</Modelica-Error>\n");
414 end if;
415 end if;
416 clearMessages();
417 )",
418 ✗ file.generic_string());
419 ✗ };
420
421 // Open Modelica does not seem to load some (all?) package out of MODELICAPATH.
422 // This has been especially true for MBL.
423 // This is a workaround. Look in the path for package.mo and load those
424 ✗ for (const auto& searchPath : setup.searchPaths) {
425 ✗ const auto packageMo = searchPath / toPath("package.mo");
426 ✗ if (openstudio::filesystem::exists(packageMo)) {
427 ✗ loadFile(packageMo);
428 }
429 ✗ }
430
431 // Load every explicit file (seed model + auxiliary .mo files) provided by the setup.
432 ✗ for (const auto& file : setup.files) {
433 ✗ loadFile(file);
434 }
435
436 // Apply all parameters from the Measure so the upcoming simulation reflects user overrides.
437 ✗ const auto allParams = params.getAllParameters();
438 ✗ for (const auto& param : allParams) {
439 ✗ mosFile << fmt::format(R"(
440 clearMessages();
441 res := setParameterValue({}, {}, {});
442 if not res then
443 err := getErrorString();
444 if err == "" then
445 print("<Modelica-Warn>OpenModelica setParameterValue(...) produced an unspecified error.</Modelica-Warn>\n");
446 else
447 print("<Modelica-Error>OpenModleica setParameterValue(...) produced an error: " + err + "</Modelica-Error>\n");
448 end if;
449 end if;
450 clearMessages();
451 )",
452 ✗ param.model(), param.key(), param.value());
453 }
454
455 // Run simulation and look for errors
456 ✗ mosFile << fmt::format(R"(
457 clearMessages();
458 res := simulate({}, stopTime=604800, stepSize=10);
459 resFile := res.resultFile;
460 messages := res.messages;
461 print("<Modelica-Messages>" + messages + "</Modelica-Messages>\n");
462 if regularFileExists(resFile) then
463 print("Modelica simulation was successful\n");
464 print("<Modelica-ResultFile>" + resFile + "</Modelica-ResultFile>\n");
465 else
466 err := getErrorString();
467 if err == "" then
468 print("<Modelica-Error>The OpenModelica simulation completed, but did not produce a results file. The file `run/stdout-modelica` or --show-stdout may provide additional information.</Modelica-Error>\n");
469 else
470 print("<Modelica-Error>" + err + "</Modelica-Error>\n");
471 end if;
472 end if;
473 clearMessages();
474 )",
475 ✗ *seedModelicaModel);
476 ✗ mosFile.close();
477
478 ✗ return mosPath;
479 ✗ }
480
481 ✗ [[maybe_unused]] openstudio::path createDymolaScript(const WorkflowJSON& workflowJSON, const ModelicaSetup& setup,
482 const measure::ModelicaParameters& params) {
483 ✗ auto seedModelicaModel = workflowJSON.seedModelicaModel();
484 ✗ OS_ASSERT(seedModelicaModel);
485
486 ✗ constexpr auto mosPath = "run.mos";
487 ✗ std::ofstream mosFile(mosPath);
488
489 ✗ mosFile << buildSetModelicaPathCommand(ModelicaCompilerType::Dymola, setup.searchPaths);
490 ✗ for (const auto& file : setup.files) {
491 ✗ mosFile << fmt::format("openModel({});\n", modelicaStringLiteral(file.generic_string()));
492 }
493
494 ✗ const auto allParams = params.getAllParameters();
495 ✗ std::vector<measure::ModelicaParameter> filtered;
496 ✗ filtered.reserve(allParams.size());
497 ✗ for (const auto& param : allParams) {
498 ✗ if (param.model() == *seedModelicaModel) {
499 ✗ filtered.push_back(param);
500 }
501 }
502
503 // Dymola's simulateModel expects modifier names/values arrays; map the
504 // ModelicaParameter collection into those two arrays before issuing the
505 // simulateModel call.
506 ✗ const auto finalNames = formatModelicaArray(filtered, [](const auto& p) { return modelicaStringLiteral(p.key()); });
507 ✗ const auto finalValues = formatModelicaArray(filtered, [](const auto& p) { return p.value(); });
508 ✗ mosFile << fmt::format("finalNames := {};\n", finalNames);
509 ✗ mosFile << fmt::format("finalValues := {};\n", finalValues);
510 ✗ mosFile << fmt::format("simulateModel({}, stopTime=604800, stepSize=10, finalNames=finalNames, finalValues=finalValues);\n",
511 ✗ modelicaStringLiteral(*seedModelicaModel));
512 ✗ mosFile << "Modelica.Utilities.Streams.print(getLastError());\n";
513 ✗ mosFile.close();
514
515 ✗ return mosPath;
516 ✗ }
517
518 ✗ openstudio::path createModelicaScript(const WorkflowJSON& workflowJSON, const ModelicaSetup& setup, const measure::ModelicaParameters& params,
519 ModelicaCompilerType compilerType) {
520 ✗ switch (compilerType) {
521 ✗ case ModelicaCompilerType::OpenModelica:
522 ✗ return createOpenModelicaScript(workflowJSON, setup, params);
523 ✗ case ModelicaCompilerType::Dymola:
524 ✗ LOG_AND_THROW("This OpenStudio build only supports OpenModelica; set OS_MODELICA_COMPILER=openmodelica and ensure omc is installed.");
525 }
526 ✗ OS_ASSERT(false);
527 ✗ return {};
528 }
529
530 ✗ std::string quoteCommandArgument(const std::string& arg) {
531 ✗ std::string quoted;
532 ✗ quoted.reserve(arg.size() + 2);
533 ✗ quoted.push_back('"');
534 ✗ for (const char ch : arg) {
535 ✗ if (ch == '"') {
536 ✗ quoted.push_back('\\');
537 }
538 ✗ quoted.push_back(ch);
539 }
540 ✗ quoted.push_back('"');
541 ✗ return quoted;
542 ✗ }
543
544 ✗ std::string buildCommandLine(const ModelicaCompilerInfo& compiler, const openstudio::path& scriptPath) {
545 ✗ std::vector<std::string> parts;
546 ✗ parts.emplace_back(quoteCommandArgument(compiler.executable.string()));
547 ✗ for (const auto& arg : compiler.defaultArgs) {
548 ✗ parts.emplace_back(quoteCommandArgument(arg));
549 }
550 ✗ parts.emplace_back(quoteCommandArgument(scriptPath.string()));
551 ✗ return fmt::format("{}", fmt::join(parts, " "));
552 ✗ }
553 } // namespace
554
555 ✗ void OSWorkflow::runModelica() {
556 ✗ const auto curDirPath = boost::filesystem::current_path();
557 try {
558 ✗ auto runDirPath = workflowJSON.absoluteRunDir();
559 ✗ boost::filesystem::current_path(runDirPath);
560 // Switch into the workflow's run directory so every generated file is scoped to the current job.
561 //PrepareRunDirResults runDirResults(runDirPath);
562 ✗ LOG(Info, "Starting Modelica simulation in run directory: " << runDirPath);
563
564 // Mirror the EnergyPlus workflow convention by capturing the solver output locally.
565 ✗ std::ofstream stdout_ofs(openstudio::toString(runDirPath / "stdout-modelica"), std::ofstream::trunc);
566 ✗ std::ofstream stderr_ofs(openstudio::toString(runDirPath / "stderr-modelica"), std::ofstream::trunc);
567
568 ✗ state = State::Modelica;
569 ✗ m_lastModelicaResultPath.reset();
570
571 ✗ int result = 0;
572 ✗ OS_ASSERT(workspace_);
573
574 ✗ const auto compiler = getModelicaCompiler();
575 ✗ LOG(Info, fmt::format("Using {} compiler at '{}'", compilerDisplayName(compiler.type), compiler.executable.generic_string()));
576 ✗ const auto params = runner.modelicaParameters();
577 ✗ const auto setup = getModelicaSetup(workflowJSON, m_latestModelicaFilePath);
578 // The script encodes the files to load, parameter overrides, and the simulate command for the chosen compiler.
579 ✗ const auto script_path = createModelicaScript(workflowJSON, setup, params, compiler.type);
580 // Capture the exact command line so it can be logged/replayed, then feed it through the platform shell below.
581 ✗ const auto cmd = buildCommandLine(compiler, script_path);
582
583 ✗ const char* shellExe = nullptr;
584 ✗ const char* shellArg = nullptr;
585 #ifdef _WIN32
586 shellExe = "cmd.exe";
587 shellArg = "/C";
588 #else
589 ✗ shellExe = "/bin/sh";
590 ✗ shellArg = "-c";
591 #endif
592
593 // Spawn through the platform shell so that the command line mirrors what we log/print for reproduction while still
594 // letting boost::process capture stdout/stderr for log files.
595 ✗ std::optional<openstudio::path> detectedModelicaResultPath;
596
597 ✗ detailedTimeBlock("Running Modelica", [this, shellExe, shellArg, &cmd, &result, &stdout_ofs, &stderr_ofs, &detectedModelicaResultPath] {
598 namespace bp = boost::process;
599 ✗ bp::ipstream stdout_is;
600 ✗ bp::ipstream stderr_is;
601 // Run the compiler command via the shell and hook up pipes so we can tee output to log files.
602 ✗ bp::child c(shellExe, shellArg, cmd, bp::std_out > stdout_is, bp::std_err > stderr_is);
603
604 ✗ ModelicaTagParserState stdoutTagState;
605 ✗ ModelicaTagParserState stderrTagState;
606
607 // Reads a stream line-by-line, mirroring output to disk while optionally echoing and extracting tagged payloads.
608 ✗ auto reader = [this, &detectedModelicaResultPath](bp::ipstream& stream, std::ofstream& ofs, bool parseTaggedOutput,
609 ModelicaTagParserState& tagState, bool echo) {
610 ✗ std::string line;
611 ✗ while (std::getline(stream, line)) {
612 ✗ if (!line.empty() && line.back() == '\r') {
613 ✗ line.pop_back();
614 }
615 ✗ if (parseTaggedOutput) {
616 ✗ const auto taggedOutput = parseModelicaTaggedOutput(line, tagState);
617 ✗ if (!taggedOutput.empty()) {
618 ✗ logCompilerOutput(taggedOutput, echo && m_show_stdout);
619 ✗ if (taggedOutput.simulationResultFile) {
620 ✗ detectedModelicaResultPath = openstudio::toPath(*taggedOutput.simulationResultFile);
621 }
622 }
623 ✗ }
624 ✗ if (ofs.is_open()) {
625 ✗ ofs << line << '\n';
626 }
627 ✗ if (echo && m_show_stdout) {
628 ✗ fmt::print("{}\n", line);
629 }
630 }
631 ✗ if (parseTaggedOutput) {
632 ✗ const auto trailingOutput = finalizeModelicaTaggedOutput(tagState);
633 ✗ if (!trailingOutput.empty()) {
634 ✗ logCompilerOutput(trailingOutput, echo && m_show_stdout);
635 ✗ if (trailingOutput.simulationResultFile) {
636 ✗ detectedModelicaResultPath = openstudio::toPath(*trailingOutput.simulationResultFile);
637 }
638 }
639 ✗ }
640 ✗ };
641
642 ✗ std::thread stdoutThread(reader, std::ref(stdout_is), std::ref(stdout_ofs), true, std::ref(stdoutTagState), true);
643 ✗ std::thread stderrThread(reader, std::ref(stderr_is), std::ref(stderr_ofs), false, std::ref(stderrTagState), false);
644 ✗ c.wait();
645 ✗ stdoutThread.join();
646 ✗ stderrThread.join();
647 ✗ result = c.exit_code();
648 ✗ });
649
650 ✗ if (detectedModelicaResultPath) {
651 ✗ auto resolvedPath = *detectedModelicaResultPath;
652 ✗ if (openstudio::filesystem::exists(resolvedPath)) {
653 ✗ m_lastModelicaResultPath = openstudio::filesystem::canonical(resolvedPath);
654 } else {
655 ✗ LOG(Warn, "Modelica reported a result file at '" << resolvedPath << "', but it does not exist.");
656 ✗ m_lastModelicaResultPath.reset();
657 }
658 ✗ } else {
659 ✗ m_lastModelicaResultPath.reset();
660 }
661
662 ✗ LOG(Info, "Modelica returned '" << result << "'");
663 ✗ if (result != 0) {
664 ✗ LOG(Warn, "Modelica returned a non-zero exit code (" << result << "). Check the Modelica log");
665 }
666
667 ✗ } catch (const std::exception& e) {
668 ✗ boost::filesystem::current_path(curDirPath);
669 ✗ LOG_AND_THROW(e.what());
670 ✗ }
671 ✗ }
672
673 } // namespace openstudio
674