Loading...
Searching...
No Matches
CommandLine.cpp
Go to the documentation of this file.
1/*
2** This file is part of eOn.
3**
4** SPDX-License-Identifier: BSD-3-Clause
5**
6** Copyright (c) 2010--present, eOn Development Team
7** All rights reserved.
8**
9** Repo:
10** https://github.com/TheochemUI/eOn
11*/
12#include "eon/CommandLine.h"
13#include "eon/EonLogger.h"
14#include "eon/Matter.h"
15#include "eon/Parameters.h"
16#include "eon/Potential.h"
17#include "version.h"
18
19#ifdef WITH_SERVE_MODE
20#include "eon/ServeMode.h"
21#endif
22
23#include <argum.h>
24
25#include <cstdlib>
26#include <fstream>
27#include <iomanip>
28#include <iostream>
29#include <memory>
30#include <optional>
31#include <sstream>
32#include <string>
33
34namespace {
35constexpr auto colorScheme = Argum::basicDefaultColorScheme<char>;
36Argum::BasicColorizer<char> colorizer(colorScheme);
37} // namespace
38
39void singlePoint(std::unique_ptr<eonc::Matter> matter) {
40 std::cout << "Energy: " << std::fixed << std::setprecision(15)
41 << matter->getPotentialEnergy() << '\n';
42 std::cout << "(free) Forces: \n" << matter->getForcesFree() << "\n";
43 std::cout << "Max atom force: " << std::scientific << matter->maxForce()
44 << '\n';
45}
46
47void minimize(std::unique_ptr<eonc::Matter> matter,
48 const std::string &confileout) {
49 matter->relax(false, false);
50 if (confileout.empty()) {
51 std::cout << "No output file specified, not saving" << '\n';
52 return;
53 }
54 std::cout << "Saving relaxed structure to " << confileout << '\n';
55 if (!eonc::io::io_ok(matter->matter2con(confileout))) {
56 std::cerr << "Failed to write " << confileout << '\n';
57 }
58}
59
61 std::cout << colorizer.heading("Compile-time features:") << '\n';
62 // Parse FEATURES_STRING and colorize enabled/disabled
63 std::istringstream stream(FEATURES_STRING);
64 std::string line;
65 while (std::getline(stream, line)) {
66 if (line.find(": enabled") != std::string::npos) {
67 // Extract feature name and colorize "enabled" with warning (yellow)
68 size_t colonPos = line.find(": ");
69 if (colonPos != std::string::npos) {
70 std::string featureName = line.substr(0, colonPos + 2);
71 std::string status = line.substr(colonPos + 2);
72 std::cout << featureName << colorizer.warning(status) << '\n';
73 } else {
74 std::cout << line << '\n';
75 }
76 } else if (line.find(": disabled") != std::string::npos) {
77 // Extract feature name and colorize "disabled" with error (red)
78 size_t colonPos = line.find(": ");
79 if (colonPos != std::string::npos) {
80 std::string featureName = line.substr(0, colonPos + 2);
81 std::string status = line.substr(colonPos + 2);
82 std::cout << featureName << colorizer.error(status) << '\n';
83 } else {
84 std::cout << line << '\n';
85 }
86 } else {
87 std::cout << line << '\n';
88 }
89 }
90}
91
92namespace eonc {
93
94void commandLine(int argc, char **argv) {
95 bool sflag = false, mflag = false, pflag = false, cflag = false;
96 double optConvergedForce = 0.001;
97 std::string potential;
98 std::string confile;
99 std::string confileout;
100 std::string optimizer("cg");
101
102#ifdef WITH_SERVE_MODE
103 std::optional<std::string> config_path;
104 std::optional<std::string> serve_spec;
105 // Empty until the matching flag is passed. A value here makes has_value()
106 // true, so -p alone takes the serve path and never reads a structure file.
107 std::optional<std::string> serve_host;
108 std::optional<uint16_t> serve_port;
109 std::optional<size_t> replicas;
110 std::optional<bool> gateway;
111#endif
112
113 auto params = Parameters{};
114
115 const char *progname = (argc ? argv[0] : "eonclient");
116
117 Argum::Parser parser;
118
119 parser.add(Argum::Option("--help", "-h")
120 .help("show this help message and exit")
121 .handler([&]() {
122 // Format help with color
123 auto helpText = parser.formatHelp(progname);
124 std::cout << colorizer.heading("eOn Client - Help")
125 << "\n\n";
126 std::cout << helpText;
127 std::exit(EXIT_SUCCESS);
128 }));
129
130 parser.add(Argum::Option("--version", "-v")
131 .help("Print version information")
132 .handler([&]() {
133 std::cout << VERSION_STRING << '\n';
134 std::exit(EXIT_SUCCESS);
135 }));
136
137 parser.add(Argum::Option("--features")
138 .help("Print compile-time features")
139 .handler([&]() {
141 std::exit(EXIT_SUCCESS);
142 }));
143
144 parser.add(Argum::Option("--minimize", "-m")
145 .help("Minimization of inputConfile saves to outputConfile")
146 .handler([&]() { mflag = true; }));
147
148 parser.add(Argum::Option("--single", "-s")
149 .help("Single point energy of inputConfile")
150 .handler([&]() { sflag = true; }));
151
152 parser.add(Argum::Option("--compare", "-c")
153 .help("Compare structures of inputConfile to outputConfile")
154 .handler([&]() { cflag = true; }));
155
156 parser.add(
157 Argum::Option("--optimizer", "-o")
158 .argName("METHOD")
159 .help("Optimization method")
160 .handler([&](const std::string_view &value) { optimizer = value; }));
161
162 parser.add(Argum::Option("--force", "-f")
163 .argName("VALUE")
164 .help("Convergence force")
165 .handler([&](const std::string_view &value) {
166 optConvergedForce = Argum::parseFloatingPoint<double>(value);
167 }));
168
169 parser.add(
170 Argum::Option("--tolerance", "-t")
171 .argName("VALUE")
172 .help("Distance tolerance")
173 .handler([&](const std::string_view &value) {
175 .distance_difference = Argum::parseFloatingPoint<double>(value);
176 }));
177
178 parser.add(Argum::Option("--potential", "-p")
179 .argName("POTENTIAL")
180 .help("The potential (e.g. qsc, lj, eam_al)")
181 .handler([&](const std::string_view &value) {
182 pflag = true;
183 potential = value;
184 }));
185
186#ifdef WITH_SERVE_MODE
187 parser.add(
188 Argum::Option("--serve")
189 .argName("SPEC")
190 .help("Serve potential(s) over rgpot Cap'n Proto RPC. "
191 "Spec: 'potential:port' or 'pot1:port1,pot2:port2'")
192 .handler([&](const std::string_view &value) { serve_spec = value; }));
193
194 parser.add(
195 Argum::Option("--serve-host")
196 .argName("HOST")
197 .help("Host to bind RPC server(s) to")
198 .handler([&](const std::string_view &value) { serve_host = value; }));
199
200 parser.add(Argum::Option("--serve-port")
201 .argName("PORT")
202 .help("Port for single-potential serve mode (used with -p)")
203 .handler([&](const std::string_view &value) {
204 serve_port = Argum::parseIntegral<uint16_t>(value);
205 }));
206
207 parser.add(Argum::Option("--replicas")
208 .argName("N")
209 .help("Number of replicated server instances (used with -p)")
210 .handler([&](const std::string_view &value) {
211 replicas = Argum::parseIntegral<size_t>(value);
212 }));
213
214 parser.add(Argum::Option("--gateway")
215 .help("Run a single gateway port backed by N pool instances "
216 "(use with -p and --replicas)")
217 .handler([&]() { gateway = true; }));
218
219 parser.add(Argum::Option("--config")
220 .argName("FILE")
221 .help("Config file for potential parameters (INI format, "
222 "e.g. [Metatomic] model_path=model.pt)")
223 .handler([&](const std::string_view &value) {
224 config_path = value;
225 }));
226#endif
227
228 // One value each: the partitioner hands a greedy zeroOrMoreTimes positional
229 // every remaining argument, which leaves confileout empty and overwrites
230 // confile with the last one.
231 parser.add(
232 Argum::Positional("confile")
233 .help("Input structure file")
234 .occurs(Argum::zeroOrOneTime)
235 .handler([&](const std::string_view &value) { confile = value; }));
236
237 parser.add(
238 Argum::Positional("confileout")
239 .help("Output structure file (optional)")
240 .occurs(Argum::zeroOrOneTime)
241 .handler([&](const std::string_view &value) { confileout = value; }));
242
243 try {
244 parser.parse(argc, argv);
245 } catch (const Argum::ParsingException &ex) {
246 std::cerr << colorizer.error(ex.message()) << '\n';
247 std::cerr << colorizer.warning(parser.formatUsage(progname)) << '\n';
248 std::exit(EXIT_FAILURE);
249 }
250
251 // Help, version, and features exit inside parse. Logger setup waits until
252 // a flag set commits to a potential, a compare, or a config load.
254
255 if (sflag && mflag) {
256 std::cerr << colorizer.error(
257 "Cannot specify both minimization and single point\n");
258 std::exit(EXIT_FAILURE);
259 }
260
261 if (!pflag && (sflag || mflag)) {
262 std::cerr << colorizer.error("Must specify a potential\n");
263 std::exit(EXIT_FAILURE);
264 }
265
266 if (cflag && confileout.empty()) {
267 std::cerr << colorizer.error(
268 "Comparison needs two structure files: the input con file and the "
269 "one to compare it against\n");
270 std::cerr << colorizer.warning(parser.formatUsage(progname)) << '\n';
271 std::exit(EXIT_FAILURE);
272 }
273
274#ifdef WITH_SERVE_MODE
275 // Load config file if provided (for potential-specific parameters
276 // like model_path, device, length_unit, etc.)
277 if (config_path.has_value()) {
278 std::ifstream config_file(config_path.value());
279 if (!config_file.is_open()) {
280 std::cerr << colorizer.error("Cannot open config file: ")
281 << config_path.value() << '\n';
282 std::exit(EXIT_FAILURE);
283 }
284 params.load(config_path.value());
285 }
286
287 // Handle --serve mode (does not require a con file)
288 if (serve_spec.has_value()) {
289 auto endpoints = parseServeSpec(serve_spec.value());
290 if (endpoints.empty()) {
291 std::cerr << colorizer.error("No valid serve endpoints in spec: ")
292 << serve_spec.value() << '\n';
293 std::exit(EXIT_FAILURE);
294 }
295 serveMultiple(endpoints, params);
296 std::exit(EXIT_SUCCESS);
297 }
298
299 // Handle -p with serve flags (single potential serve mode).
300 // Defaults are applied below with value_or; has_value() is the flag.
301 if (pflag && !sflag && !mflag && !cflag &&
302 (serve_host.has_value() || serve_port.has_value() ||
303 replicas.has_value() || gateway.has_value())) {
304 for (auto &ch : potential) {
305 ch = std::tolower(static_cast<unsigned char>(ch));
306 }
308 magic_enum::enum_cast<PotType>(potential, magic_enum::case_insensitive)
309 .value_or(PotType::UNKNOWN);
310 auto host = serve_host.value_or("localhost");
311 auto port = serve_port.value_or(12345);
312 auto reps = replicas.value_or(1);
313 bool gw = gateway.value_or(false);
314
315 if (gw) {
316 serveGateway(params, host, port, reps);
317 } else if (reps > 1) {
318 serveReplicated(params, host, port, reps);
319 } else {
320 serveMode(params, host, port);
321 }
322 std::exit(EXIT_SUCCESS);
323 }
324
325 // Config-driven serve (no -p or --serve, just --config with [Serve])
326 if (!pflag && !sflag && !mflag && !cflag && config_path.has_value() &&
327 !serve_spec.has_value() &&
328 (!eonc::ParametersLoadAccess::serve_options(params).endpoints.empty() ||
329 eonc::ParametersLoadAccess::serve_options(params).gateway_port > 0 ||
330 eonc::ParametersLoadAccess::serve_options(params).replicas > 1)) {
331 serveFromConfig(params);
332 std::exit(EXIT_SUCCESS);
333 }
334#endif
335
336 // Serve modes take no structure file and have already exited above.
337 if (confile.empty()) {
338 std::cerr << colorizer.error(
339 "At least one non-option argument is required: the con file\n");
340 std::cerr << colorizer.warning(parser.formatUsage(progname)) << '\n';
341 std::exit(EXIT_FAILURE);
342 }
343
344 if (!cflag) {
345 for (auto &ch : potential) {
346 ch = std::tolower(static_cast<unsigned char>(ch));
347 }
348 }
349
350 if (!cflag) {
352 magic_enum::enum_cast<PotType>(potential, magic_enum::case_insensitive)
353 .value_or(PotType::UNKNOWN);
354 }
355
356 if (!sflag) {
358 magic_enum::enum_cast<OptType>(optimizer, magic_enum::case_insensitive)
359 .value_or(OptType::CG);
361 optConvergedForce;
362 }
363
364 if (cflag) {
365 // Matter copies structure_comparison_options into its own structComp in
366 // the constructor, so the flag has to be set before the two below.
368 .check_rotation = true;
369 }
370
371 auto pot =
373 auto matter = std::make_unique<Matter>(pot, params);
374 auto matter2 = std::make_unique<Matter>(pot, params);
375 if (!eonc::io::io_ok(matter->con2matter(confile))) {
376 std::cerr << "Failed to load " << confile << '\n';
377 std::exit(EXIT_FAILURE);
378 }
379
380 if (sflag) {
381 singlePoint(std::move(matter));
382 } else if (mflag) {
383 minimize(std::move(matter), confileout);
384 } else if (cflag) {
385 if (!eonc::io::io_ok(matter2->con2matter(confileout))) {
386 std::cerr << "Failed to load " << confileout << '\n';
387 std::exit(EXIT_FAILURE);
388 }
389 Matter probe(*matter);
390 if (probe.compare(*matter2, true)) {
391 std::cout << "Structures match\n";
392 } else {
393 std::cout << colorizer.error("Structures do not match\n");
394 }
395 }
396}
397
398} // namespace eonc
void printFeatures()
void minimize(std::unique_ptr< eonc::Matter > matter, const std::string &confileout)
void singlePoint(std::unique_ptr< eonc::Matter > matter)
bool compare(const Matter &matter, bool indistinguishable=false)
Definition Matter.cpp:254
std::unique_ptr< Potential > makePotential(const Parameters &params)
Exclusive ownership.
std::shared_ptr< Potential > sharePotential(std::unique_ptr< Potential > pot)
Multi-owner boundary: one instance observed by several Matters, images, or a binding.
Definition Potential.h:292
constexpr bool io_ok(IoStatus s) noexcept
Definition ConFileIO.h:38
quill::Logger * init_client() noexcept
Start the client backend and the combi / traceback loggers once.
Definition EonLogger.h:43
RAII resource manager for the ARTn C library with global synchronization.
std::vector< ServeEndpoint > parseServeSpec(const std::string &spec)
Parse a serve configuration string into endpoints.
void serveGateway(const Parameters &params, const std::string &host, uint16_t port, size_t pool_size)
Start a gateway server backed by a pool of potential instances.
void serveMode(const Parameters &params, const std::string &host, uint16_t port)
Start a single rgpot-compatible Cap'n Proto RPC server.
Definition ServeMode.cpp:58
void serveFromConfig(const Parameters &params)
Start serve mode from config-file parameters.
void commandLine(int argc, char **argv)
void serveMultiple(const std::vector< ServeEndpoint > &endpoints, const Parameters &base_params)
Serve multiple potentials concurrently on different ports.
Definition ServeMode.cpp:82
void serveReplicated(const Parameters &params, const std::string &host, uint16_t base_port, size_t replicas)
Serve N replicas of the same potential across sequential ports.
static structure_comparison_options_t & structure_comparison_options(Parameters &p)
static optimizer_options_t & optimizer_options(Parameters &p)
static serve_options_t & serve_options(Parameters &p)
static potential_options_t & potential_options(Parameters &p)