-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
403 lines (372 loc) · 16.4 KB
/
main.cpp
File metadata and controls
403 lines (372 loc) · 16.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
#include "coolsolve/parser.h"
#include "coolsolve/ir.h"
#include "coolsolve/runner.h"
#include "coolsolve/structural_analysis.h"
#include "coolsolve/evaluator.h" // For profiling stats
#ifdef COOLSOLVE_GUI
#include "coolsolve/server.h"
#endif
#include <iostream>
#include <fstream>
#include <string>
#include <filesystem>
#include <iomanip>
namespace fs = std::filesystem;
void printUsage(const char* programName) {
std::cerr << "Usage: " << programName << " [options] <input.eescode>\n\n";
std::cerr << "Options:\n";
std::cerr << " -o, --output <file> Output file (default: stdout)\n";
std::cerr << " -f, --format <format> Output format: json, residuals, latex (default: json)\n";
std::cerr << " -c, --compare <file> Compare with EES .residuals file\n";
std::cerr << " -d, --debug [dir] Debug mode: create output folder with all analysis files\n";
std::cerr << " If dir not specified, creates <input_dir>/<input_name>_coolsolve/\n";
std::cerr << " --no-sol Disable generation of .sol file\n";
std::cerr << " -g, --guess Update .initials file with solution on success\n";
std::cerr << " --no-superancillary Disable CoolProp superancillary functions (faster VLE solving)\n";
#ifdef COOLSOLVE_GUI
std::cerr << " --gui [port] Start the GUI web server (default port: 8550)\n";
std::cerr << " --no-browser Don't open browser automatically (with --gui)\n";
#endif
std::cerr << " -h, --help Show this help message\n";
}
// Helper to read file content
std::optional<std::string> readFileContent(const std::string& path) {
std::ifstream file(path);
if (!file.is_open()) return std::nullopt;
std::stringstream buffer;
buffer << file.rdbuf();
return buffer.str();
}
int main(int argc, char* argv[]) {
std::string inputFile;
std::string outputFile;
std::string compareFile;
std::string debugDir;
std::string format = "json";
bool debugMode = false;
bool writeSolFile = true;
bool enableSuperancillary = true;
bool updateGuessFile = false;
#ifdef COOLSOLVE_GUI
bool guiMode = false;
int guiPort = 8550;
bool guiOpenBrowser = true;
#endif
// Parse command line arguments
for (int i = 1; i < argc; ++i) {
std::string arg = argv[i];
if (arg == "-h" || arg == "--help") {
printUsage(argv[0]);
return 0;
} else if (arg == "--no-sol") {
writeSolFile = false;
} else if (arg == "--no-superancillary") {
enableSuperancillary = false;
} else if (arg == "-g" || arg == "--guess") {
updateGuessFile = true;
#ifdef COOLSOLVE_GUI
} else if (arg == "--gui") {
guiMode = true;
// Check if next arg is a port number
if (i + 1 < argc) {
try {
int port = std::stoi(argv[i + 1]);
if (port > 0 && port < 65536) {
guiPort = port;
++i;
}
} catch (...) {}
}
} else if (arg == "--no-browser") {
guiOpenBrowser = false;
#endif
} else if (arg == "-d" || arg == "--debug") {
debugMode = true;
// Check if next arg is a directory (not starting with - and not ending with .eescode)
if (i + 1 < argc && argv[i + 1][0] != '-') {
std::string nextArg = argv[i + 1];
// If it looks like an input file (.eescode), don't consume it as debug dir
if (nextArg.size() < 8 || nextArg.substr(nextArg.size() - 8) != ".eescode") {
debugDir = argv[++i];
}
}
} else if (arg == "-o" || arg == "--output") {
if (i + 1 < argc) {
outputFile = argv[++i];
} else {
std::cerr << "Error: -o requires an argument\n";
return 1;
}
} else if (arg == "-f" || arg == "--format") {
if (i + 1 < argc) {
format = argv[++i];
} else {
std::cerr << "Error: -f requires an argument\n";
return 1;
}
} else if (arg == "-c" || arg == "--compare") {
if (i + 1 < argc) {
compareFile = argv[++i];
} else {
std::cerr << "Error: -c requires an argument\n";
return 1;
}
} else if (arg[0] != '-') {
inputFile = arg;
} else {
std::cerr << "Unknown option: " << arg << "\n";
return 1;
}
}
if (inputFile.empty()) {
#ifdef COOLSOLVE_GUI
if (guiMode) {
coolsolve::ServerOptions serverOpts;
serverOpts.port = guiPort;
serverOpts.openBrowser = guiOpenBrowser;
return coolsolve::startServer(serverOpts);
}
#endif
std::cerr << "Error: No input file specified\n";
printUsage(argv[0]);
return 1;
}
#ifdef COOLSOLVE_GUI
// GUI mode with input file: open it in the GUI
if (guiMode) {
coolsolve::ServerOptions serverOpts;
serverOpts.port = guiPort;
serverOpts.openBrowser = guiOpenBrowser;
// The server will be able to load this file via the /api/v1/files/open endpoint
// For now, pass via environment or we'll handle in the server startup
return coolsolve::startServer(serverOpts);
}
#endif
// Configure solver options (defaults from solver.h)
coolsolve::SolverOptions options;
options.verbose = false; // Disable stdout/stderr verbosity
options.coolpropConfig.enableSuperancillaries = enableSuperancillary;
// Override from coolsolve.conf in the same folder as the input file (not subfolders)
fs::path configPath = fs::path(inputFile).parent_path() / "coolsolve.conf";
if (fs::exists(configPath)) {
coolsolve::loadSolverOptionsFromFile(configPath.string(), options);
}
// Apply CoolProp configuration before any CoolProp calls
coolsolve::applyCoolPropConfig(options.coolpropConfig);
// Use CoolSolveRunner to handle the execution pipeline
coolsolve::CoolSolveRunner runner(inputFile);
// Determine the debug output path early so we can pass it to the solver options
fs::path debugPath;
if (debugMode) {
if (debugDir.empty()) {
fs::path inputPath(inputFile);
debugPath = inputPath.parent_path() / (inputPath.stem().string() + "_coolsolve");
} else {
debugPath = debugDir;
}
}
// Clean up previous solve outputs before starting a new solve
{
fs::path inputPath(inputFile);
// Delete existing .sol file
fs::path solPath = inputPath.parent_path() / (inputPath.stem().string() + ".sol");
if (fs::exists(solPath)) {
fs::remove(solPath);
}
// Delete existing debug directory
if (!debugPath.empty() && fs::exists(debugPath)) {
std::error_code ec;
fs::remove_all(debugPath, ec);
}
}
// If debug mode and symbolic reduction enabled, write the reduction debug report
// into the debug directory (the directory is created by runner.generateDebugOutput later,
// but writeDebugReductionReport will create it on its own if needed)
if (debugMode && options.enableSymbolicReduction) {
std::error_code ec;
fs::create_directories(debugPath, ec);
options.debugReductionPath = (debugPath / "symbolic_reduction.md").string();
}
// Run the pipeline (Parse -> IR -> Infer -> Analyze -> Solve)
// Note: runner.run() automatically loads .initials if present
// Pass debugMode as enableTracing
bool runSuccess = runner.run(options, debugMode);
if (!runner.isParseSuccess()) {
std::cerr << "Parse failed:\n";
for (const auto& err : runner.getParseResult().errors) {
std::cerr << " Line " << err.line << ": " << err.message << "\n";
}
return 1;
}
// Retrieve results from runner
const auto& ir = runner.getIR();
const auto& analysisResult = runner.getAnalysisResult();
const auto& solveResult = runner.getSolveResult();
// Print statistics
std::cout << "=== Model Statistics ===\n";
std::cout << "Equations: " << ir.getEquationCount() << "\n";
std::cout << "Variables: " << ir.getNonConstantVariableCount() << "\n";
std::cout << "System square: " << (ir.isSquare() ? "Yes" : "No") << "\n";
if (!ir.isSquare()) {
auto unmatchedVars = ir.getUnmatchedVariables();
auto unmatchedEqs = ir.getUnmatchedEquations();
if (!unmatchedVars.empty()) {
std::cout << "Unmatched variables (" << unmatchedVars.size() << "): ";
for (size_t i = 0; i < std::min(unmatchedVars.size(), size_t(10)); ++i) std::cout << unmatchedVars[i] << " ";
if (unmatchedVars.size() > 10) std::cout << "...";
std::cout << "\n";
}
if (!unmatchedEqs.empty()) {
std::cout << "Unmatched equations (" << unmatchedEqs.size() << "): ";
for (size_t i = 0; i < std::min(unmatchedEqs.size(), size_t(10)); ++i) std::cout << unmatchedEqs[i] << " ";
if (unmatchedEqs.size() > 10) std::cout << "...";
std::cout << "\n";
}
}
// Handle Debug Output generation
if (debugMode) {
std::cout << "Debug output: " << fs::weakly_canonical(debugPath) << "\n";
// Read source code for inclusion in debug output
auto sourceCode = readFileContent(inputFile);
runner.generateDebugOutput(debugPath.string(), sourceCode.value_or(""));
}
// Check for structural analysis errors (e.g., non-square system)
if (!analysisResult.success) {
std::cerr << "\n=== Structural Analysis Error ===\n";
std::cerr << analysisResult.errorMessage << "\n";
return 1;
}
// Print structural analysis results
std::cout << "Total blocks: " << analysisResult.totalBlocks << "\n";
std::cout << "Largest block: " << analysisResult.largestBlockSize << "\n";
if (options.enableSymbolicReduction && !solveResult.blockResults.empty()) {
int maxReducedSize = 0;
int totalBlocksReduced = 0;
int totalVarsReduced = 0;
for (const auto& br : solveResult.blockResults) {
if (br.symbolicReductionApplied) {
++totalBlocksReduced;
totalVarsReduced += (br.originalSize - br.reducedSize);
maxReducedSize = std::max(maxReducedSize, br.reducedSize);
} else {
maxReducedSize = std::max(maxReducedSize, br.originalSize);
}
}
if (totalBlocksReduced > 0) {
std::cout << "Largest block after reduction: " << maxReducedSize
<< " (" << totalBlocksReduced << " block(s) reduced, "
<< totalVarsReduced << " variable(s) eliminated)\n";
}
}
// Report Solver Result
if (!solveResult.success && solveResult.status != coolsolve::SolverStatus::InvalidInput) {
std::cout << "\n=== Solver Error ===\n";
std::cout << "Status: " << coolsolve::statusToString(solveResult.status) << "\n";
std::cout << "Message: " << solveResult.errorMessage << "\n";
} else if (solveResult.success) {
std::cout << "\nSolver: SUCCESS (" << solveResult.totalIterations << " iterations)\n";
}
// Write .sol file if successful
if (solveResult.success && writeSolFile) {
fs::path inputPath(inputFile);
fs::path solPath = inputPath.parent_path() / (inputPath.stem().string() + ".sol");
std::ofstream solFile(solPath);
if (solFile.is_open()) {
solFile << std::scientific << std::setprecision(12);
for (const auto& [name, val] : solveResult.variables) {
solFile << name << " = " << val;
// Add units if available
const auto* info = ir.getVariable(name);
if (info && !info->units.empty()) {
solFile << " \"" << info->units << "\"";
}
solFile << "\n";
}
for (const auto& [name, val] : solveResult.stringVariables) {
solFile << name << " = '" << val << "'\n";
}
} else {
std::cerr << "Warning: Could not write solution file: " << solPath << "\n";
}
}
// Write .initials file if successful and requested
if (solveResult.success && updateGuessFile) {
fs::path inputPath(inputFile);
fs::path initialsPath = inputPath.parent_path() / (inputPath.stem().string() + ".initials");
std::ofstream initialsFile(initialsPath);
if (initialsFile.is_open()) {
initialsFile << std::scientific << std::setprecision(12);
for (const auto& [name, val] : solveResult.variables) {
initialsFile << name << " = " << val;
const auto* info = ir.getVariable(name);
if (info && !info->units.empty()) {
initialsFile << " \"" << info->units << "\"";
}
initialsFile << "\n";
}
for (const auto& [name, val] : solveResult.stringVariables) {
initialsFile << name << " = '" << val << "'\n";
}
} else {
std::cerr << "Warning: Could not write initials file: " << initialsPath << "\n";
}
}
// Compare with EES reference if requested
if (!compareFile.empty()) {
auto comparison = coolsolve::StructuralAnalyzer::compareWithEES(analysisResult, compareFile);
// Maybe print to stdout if requested, but we don't have verbose mode anymore for stdout.
// Let's print it always if -c is provided? Or only if fails?
// User asked to remove verbose output.
// Assuming comparison result is important if requested.
std::cout << "EES comparison: " << (comparison.matches ? "PASS" : "FAIL") << "\n";
if (!comparison.matches) {
for (const auto& diff : comparison.differences) {
std::cout << " - " << diff << "\n";
}
}
}
// Generate output based on format
std::string output;
if (format == "json") {
output = coolsolve::generateAnalysisJSON(ir, analysisResult);
} else if (format == "residuals") {
output = coolsolve::generateResidualsReport(ir, analysisResult);
} else if (format == "latex") {
output = ir.toLatex();
} else {
std::cerr << "Unknown format: " << format << "\n";
return 1;
}
// Write standard output
if (!outputFile.empty()) {
std::ofstream file(outputFile);
if (!file.is_open()) {
std::cerr << "Error: Could not open output file: " << outputFile << "\n";
return 1;
}
file << output;
}
// If no output file specified, do we print to stdout?
// User complaint was "too much output to stdout".
// Usually stdout is used for piping. If -o is not specified, piping JSON is standard behavior.
// But previous code only printed if verbose was on OR output file was empty.
// "Only print full output to stdout if verbose is on and no output file specified" -> NO, logic was:
// } else if (verbose) { std::cout << output; }
// So if NOT verbose and NO output file, it didn't print the huge output?
// Wait, let's check original code.
// Line 266: } else if (verbose) { ... print output ... }
// So previously, by default (no -v, no -o), it printed NOTHING of the JSON/residuals?
// That seems odd for a CLI tool.
// But lines 141-161 print Model Statistics to cout.
// And 187-197 print solver result.
// So by default it just prints summary.
// I will preserve this behavior. No verbose -> no huge dump to stdout unless specifically asked via -o (to file) or maybe we should support dumping to stdout if user wants?
// Usually CLI tools print to stdout if no file.
// But "options.verbose" controlled it.
// The user said "-v option has too much output to stdout".
// So removing -v means we shouldn't have that output.
// If they want the output, they use -o.
// Or maybe I should allow dumping if format is specified?
// Let's stick to: only print summary to stdout. If they want the full JSON/Report, use -o or -d (which creates files).
return solveResult.success ? 0 : 1;
}