1#![allow(clippy::unwrap_used)]
3use std::collections::{BTreeMap, BTreeSet};
4use std::time::Instant;
5use std::{
6 fs::File,
7 path::{Path, PathBuf},
8};
9
10use clap::ValueHint;
11use conjure_cp::Model;
12use conjure_cp::ast::SatEncodingDecision;
13use conjure_cp::instantiate::{instantiate_model, validate_instantiation_conditions};
14use conjure_cp::pipeline::Pipeline;
15use conjure_cp::solutions::SolutionOptions;
16use conjure_cp_cli::stats::{
17 RecordedRunConfig, RecordedRunStats, StatsFormat, replace_config_run_stats,
18};
19use conjure_cp_cli::utils::conjure::{solutions_to_essence, solutions_to_json};
20use conjure_cp_cli::utils::rule_trace::RuleApplicationCounter;
21use conjure_cp_cli::utils::simplified_json::{
22 domains_from_model, param_model_from_assignments, params_from_simplified_json_str,
23 solution_to_simplified_json, solutions_to_simplified_json_string,
24};
25
26use crate::cli::{GlobalArgs, LOGGING_HELP_HEADING};
27
28#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, clap::ValueEnum)]
29pub enum OutputFormat {
30 #[default]
32 Essence,
33 Json,
35}
36
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub enum NumberOfSolutions {
39 All,
40 Limit(i32),
41}
42
43impl NumberOfSolutions {
44 fn as_solver_limit(self) -> i32 {
45 match self {
46 NumberOfSolutions::All => 0,
47 NumberOfSolutions::Limit(limit) => limit,
48 }
49 }
50}
51
52fn parse_number_of_solutions(input: &str) -> Result<NumberOfSolutions, String> {
53 if input.eq_ignore_ascii_case("all") {
54 return Ok(NumberOfSolutions::All);
55 }
56
57 let limit = input
58 .parse::<i32>()
59 .map_err(|_| "expected a positive integer or 'all'".to_string())?;
60
61 if limit <= 0 {
62 return Err("expected a positive integer or 'all'".to_string());
63 }
64
65 Ok(NumberOfSolutions::Limit(limit))
66}
67
68#[derive(Clone, Debug, clap::Args)]
69pub struct Args {
70 #[arg(value_name = "INPUT_ESSENCE", value_hint = ValueHint::FilePath)]
72 pub essence_file: PathBuf,
73
74 #[arg(value_name = "PARAM_ESSENCE", value_hint = ValueHint::FilePath)]
76 pub param_file: Option<PathBuf>,
77
78 #[arg(long, value_name = "PATH", value_hint = ValueHint::FilePath,
80 value_parser = parse_stats_path, help_heading = LOGGING_HELP_HEADING)]
81 pub stats: Option<PathBuf>,
82
83 #[arg(long, default_value_t = false)]
88 pub no_run_solver: bool,
89
90 #[arg(
92 long,
93 short = 'n',
94 default_value = "1",
95 value_name = "N|all",
96 value_parser = parse_number_of_solutions
97 )]
98 pub number_of_solutions: NumberOfSolutions,
99
100 #[arg(long, value_enum, default_value_t = OutputFormat::Essence, help_heading=LOGGING_HELP_HEADING)]
102 pub output_format: OutputFormat,
103
104 #[arg(
108 long,
109 default_value_t = true,
110 action = clap::ArgAction::Set,
111 value_name = "BOOL",
112 help_heading = LOGGING_HELP_HEADING
113 )]
114 pub solutions_in_one_file: bool,
115
116 #[arg(long, short = 'o', value_hint = ValueHint::FilePath,help_heading=LOGGING_HELP_HEADING)]
119 pub output: Option<PathBuf>,
120
121 #[arg(long, default_value_t = false)]
124 pub keep_intermediate_solutions: bool,
125}
126
127fn parse_stats_path(input: &str) -> Result<PathBuf, String> {
128 let path = PathBuf::from(input);
129 StatsFormat::from_path(&path).map_err(|err| err.to_string())?;
130 Ok(path)
131}
132
133pub fn run_solve_command(
134 global_args: GlobalArgs,
135 solve_args: Args,
136 rule_application_counts: &RuleApplicationCounter,
137) -> anyhow::Result<()> {
138 let pipeline = Pipeline::new(global_args.library_config())?;
139 pipeline
140 .with_settings(|| run_solve(&pipeline, global_args, solve_args, rule_application_counts))
141}
142
143fn run_solve(
144 pipeline: &Pipeline,
145 global_args: GlobalArgs,
146 solve_args: Args,
147 rule_application_counts: &RuleApplicationCounter,
148) -> anyhow::Result<()> {
149 let essence_file = solve_args.essence_file.clone();
150 let param_file = solve_args.param_file.clone();
151
152 let context = pipeline.context();
153 {
154 let mut context = context.write().unwrap();
155 context.essence_file_name = Some(essence_file.to_string_lossy().into_owned());
156 context.param_file_name = param_file
157 .as_ref()
158 .map(|path| path.to_string_lossy().into_owned());
159 }
160
161 let translation_started_at = Instant::now();
162 let unified_model = pipeline.with_settings(|| -> anyhow::Result<Model> {
163 let problem_model = pipeline.parse_file(&essence_file)?;
164 match param_file {
165 Some(param_file) => {
166 let param_model = parse_param(pipeline, ¶m_file, &problem_model)?;
167 Ok(instantiate_model(problem_model, param_model)?)
168 }
169 None => {
170 let mut problem_model = problem_model;
171 validate_instantiation_conditions(&mut problem_model)?;
172 Ok(problem_model)
173 }
174 }
175 })?;
176 let rewritten_model = pipeline.rewrite(unified_model)?;
177
178 let mut model_choices = RecordedRunStats::default();
180
181 record_model_choices(&rewritten_model, &mut model_choices);
182
183 let translation_time = translation_started_at.elapsed().as_secs_f64();
184
185 let solver_started_at = Instant::now();
186
187 let measured = if solve_args.no_run_solver {
188 println!("{}", rewritten_model);
189
190 if let Some(ref path) = global_args.save_solver_input_file {
191 pipeline.with_settings(|| -> anyhow::Result<()> {
192 let solver = pipeline.solver()?.load_model(rewritten_model)?;
193 let mut file: Box<dyn std::io::Write> = Box::new(File::create(path)?);
194 solver.write_solver_input_file(&mut file)?;
195 Ok(())
196 })?;
197 }
198
199 None
200 } else {
201 Some(run_solver(
202 pipeline,
203 &global_args,
204 &solve_args,
205 rewritten_model,
206 )?)
207 };
208
209 let solve_time = measured
210 .as_ref()
211 .map(|_| solver_started_at.elapsed().as_secs_f64());
212
213 let backend_time = measured.as_ref().map(|t| t.0);
214 let search_time = measured.as_ref().map(|t| t.1);
215 let solution_processing_time = measured.as_ref().map(|t| t.2);
216
217 if let Some(ref path) = solve_args.stats {
219 let config = RecordedRunConfig {
220 rewriter: global_args.rewriter.to_string(),
221 comprehension_expander: global_args.comprehension_expander.to_string(),
222 heuristic: global_args.heuristic.to_string(),
223 channelling: global_args.channelling.to_string(),
224 seed: global_args.seed,
225 solver_seed: global_args.solver_seed,
226 solver: global_args.solver.as_str(),
227 };
228
229 let case_name = solve_args
230 .essence_file
231 .file_stem()
232 .map(|s| s.to_string_lossy().into_owned())
233 .unwrap_or_else(|| "input".to_owned());
234
235 let mut row = RecordedRunStats {
236 rewriter: config.rewriter.clone(),
237 comprehension_expander: config.comprehension_expander.clone(),
238 heuristic: config.heuristic.clone(),
239 channelling: config.channelling.clone(),
240 seed: config.seed,
241 solver_seed: config.solver_seed,
242 solver: config.solver.clone(),
243 minion_discrete_threshold: global_args.minion_discrete_threshold,
244
245 case_name,
246 model_index: 0,
247 status: "ok".to_owned(),
248
249 solution_limit: (!solve_args.no_run_solver)
250 .then(|| solve_args.number_of_solutions.as_solver_limit()),
251
252 translation_time: Some(translation_time),
253 solve_time,
254 backend_time,
255 search_time,
256 solution_processing_time,
257
258 ..Default::default()
259 };
260
261 row.representations = model_choices.representations;
262
263 row.sat_encoding_amo = model_choices.sat_encoding_amo;
264 row.sat_encoding_cardinality = model_choices.sat_encoding_cardinality;
265 row.sat_encoding_pb = model_choices.sat_encoding_pb;
266 row.sat_encoding_table = model_choices.sat_encoding_table;
267 row.sat_encoding_element = model_choices.sat_encoding_element;
268 row.sat_encoding_alldifferent = model_choices.sat_encoding_alldifferent;
269
270 let context_json = serde_json::to_value(context.read().unwrap().clone())?;
272
273 let attempt_counts: Vec<u64> = context_json
274 .get("stats")
275 .and_then(|stats| stats.get("rewriterRuns"))
276 .and_then(serde_json::Value::as_array)
277 .into_iter()
278 .flatten()
279 .filter_map(|run| {
280 run.get("rewriterRuleApplicationAttempts")
281 .and_then(serde_json::Value::as_u64)
282 })
283 .collect();
284
285 if !attempt_counts.is_empty() {
286 row.rule_trace.total_rule_attempts = Some(attempt_counts.iter().sum());
287 }
288
289 let counts = rule_application_counts.snapshot();
290 row.rule_trace.total_rule_applications = Some(counts.values().copied().sum());
291 row.rule_trace.rules = counts;
292
293 replace_config_run_stats(path, &config, vec![row])?;
295 }
296 Ok(())
297}
298fn record_model_choices(model: &Model, row: &mut RecordedRunStats) {
299 row.representations = model
300 .symbols()
301 .iter_local()
302 .flat_map(|(_, decl)| {
303 decl.reprs()
304 .iter()
305 .map(|(name, _)| name.to_owned())
306 .collect::<Vec<_>>()
307 })
308 .collect::<BTreeSet<_>>()
309 .into_iter()
310 .collect();
311 let mut families: BTreeMap<&str, BTreeSet<String>> = BTreeMap::new();
312 macro_rules! record {
313 ($family:expr, $selection:expr) => {{
314 $selection.iter().for_each(|selection| {
315 families
316 .entry($family)
317 .or_default()
318 .insert(selection.algorithm.to_string());
319 });
320 }};
321 }
322 for decision in model.sat_decisions() {
323 match decision {
324 SatEncodingDecision::AtMostOne { encoding, .. } => {
325 record!("amo", encoding);
326 }
327 SatEncodingDecision::Cardinality { encoding, .. } => {
328 record!("cardinality", encoding);
329 }
330 SatEncodingDecision::CountRelation {
331 encoding,
332 amo_encoding,
333 ..
334 } => {
335 record!("cardinality", encoding);
336 record!("amo", amo_encoding);
337 }
338 SatEncodingDecision::PseudoBoolean { encoding, .. }
339 | SatEncodingDecision::IntegerRelation { encoding, .. }
340 | SatEncodingDecision::Objective { encoding, .. } => record!("pb", encoding),
341 SatEncodingDecision::AllDifferent {
342 encoding,
343 amo_encoding,
344 pb_encoding,
345 ..
346 } => {
347 record!("alldifferent", encoding);
348 record!("amo", amo_encoding);
349 record!("pb", pb_encoding);
350 }
351 SatEncodingDecision::Table {
352 encoding,
353 pb_encoding,
354 ..
355 } => {
356 record!("table", encoding);
357 record!("pb", pb_encoding);
358 }
359 SatEncodingDecision::Element {
360 encoding,
361 pb_encoding,
362 ..
363 } => {
364 record!("element", encoding);
365 record!("pb", pb_encoding);
366 }
367 _ => {}
368 }
369 }
370 row.sat_encoding_amo = families
371 .remove("amo")
372 .unwrap_or_default()
373 .into_iter()
374 .collect();
375 row.sat_encoding_cardinality = families
376 .remove("cardinality")
377 .unwrap_or_default()
378 .into_iter()
379 .collect();
380 row.sat_encoding_pb = families
381 .remove("pb")
382 .unwrap_or_default()
383 .into_iter()
384 .collect();
385 row.sat_encoding_table = families
386 .remove("table")
387 .unwrap_or_default()
388 .into_iter()
389 .collect();
390 row.sat_encoding_element = families
391 .remove("element")
392 .unwrap_or_default()
393 .into_iter()
394 .collect();
395 row.sat_encoding_alldifferent = families
396 .remove("alldifferent")
397 .unwrap_or_default()
398 .into_iter()
399 .collect();
400}
401pub(crate) fn parse_param(
403 pipeline: &Pipeline,
404 file_path: &Path,
405 problem_model: &Model,
406) -> anyhow::Result<Model> {
407 if file_path
408 .extension()
409 .is_some_and(|extension| extension == "json")
410 {
411 tracing::info!(target: "conjure::stage", path = %file_path.display(), "parsing parameter file");
412 let text = std::fs::read_to_string(file_path)?;
413 let given_domains = domains_from_model(problem_model);
414 let params = params_from_simplified_json_str(&text, &given_domains)?;
415 return Ok(param_model_from_assignments(
416 params,
417 &given_domains,
418 pipeline.context(),
419 ));
420 }
421 pipeline.parse_file(file_path)
422}
423
424fn run_solver(
425 pipeline: &Pipeline,
426 global_args: &GlobalArgs,
427 cmd_args: &Args,
428 model: Model,
429) -> anyhow::Result<(f64, f64, f64)> {
430 let (solutions, measured) = pipeline.solve_with_timings(
431 model,
432 &SolutionOptions {
433 number_of_solutions: cmd_args.number_of_solutions.as_solver_limit(),
434 keep_intermediate_solutions: cmd_args.keep_intermediate_solutions,
435 solver_input_file: global_args.save_solver_input_file.clone(),
436 rule_trace_cdp: global_args.rule_trace_cdp,
437 },
438 )?;
439
440 let output_started_at = Instant::now();
441
442 tracing::debug!(
443 solutions = %solutions_to_json(&solutions),
444 "solver solutions"
445 );
446
447 write_solutions(&solutions, cmd_args)?;
448
449 Ok((
450 measured.backend_time_s,
451 measured.search_time_s,
452 measured.solution_processing_time_s + output_started_at.elapsed().as_secs_f64(),
453 ))
454}
455
456fn write_solutions(
457 solutions: &[std::collections::BTreeMap<conjure_cp::ast::Name, conjure_cp::ast::Literal>],
458 cmd_args: &Args,
459) -> anyhow::Result<()> {
460 if cmd_args.solutions_in_one_file {
461 let body = match cmd_args.output_format {
462 OutputFormat::Essence => solutions_to_essence(solutions),
463 OutputFormat::Json => solutions_to_simplified_json_string(solutions)?,
464 };
465 match &cmd_args.output {
466 None => print!("{body}"),
467 Some(path) => {
468 std::fs::write(path, body.as_bytes())?;
469 println!("Solutions saved to {:?}", path.canonicalize()?);
470 }
471 }
472 return Ok(());
473 }
474
475 for (index, solution) in solutions.iter().enumerate() {
477 let body = match cmd_args.output_format {
478 OutputFormat::Essence => solutions_to_essence(std::slice::from_ref(solution)),
479 OutputFormat::Json => {
480 let value = solution_to_simplified_json(solution)?;
481 format!("{}\n", serde_json::to_string_pretty(&value)?)
482 }
483 };
484 match &cmd_args.output {
485 None => print!("{body}"),
486 Some(path) => {
487 let file_path = per_solution_output_path(path, index + 1, cmd_args.output_format);
488 std::fs::write(&file_path, body.as_bytes())?;
489 println!("Solution saved to {:?}", file_path.canonicalize()?);
490 }
491 }
492 }
493 Ok(())
494}
495
496fn per_solution_output_path(base: &Path, index: usize, format: OutputFormat) -> PathBuf {
497 let stem = base
498 .file_stem()
499 .and_then(|s| s.to_str())
500 .unwrap_or("solution");
501 let parent = base.parent().unwrap_or_else(|| std::path::Path::new("."));
502 let extension = match format {
503 OutputFormat::Essence => "solution",
504 OutputFormat::Json => "solution.json",
505 };
506 parent.join(format!("{stem}-{index:06}.{extension}"))
507}