1
//! conjure_oxide solve sub-command
2
#![allow(clippy::unwrap_used)]
3
use std::collections::{BTreeMap, BTreeSet};
4
use std::time::Instant;
5
use std::{
6
    fs::File,
7
    path::{Path, PathBuf},
8
};
9

            
10
use clap::ValueHint;
11
use conjure_cp::Model;
12
use conjure_cp::ast::SatEncodingDecision;
13
use conjure_cp::instantiate::{instantiate_model, validate_instantiation_conditions};
14
use conjure_cp::pipeline::Pipeline;
15
use conjure_cp::solutions::SolutionOptions;
16
use conjure_cp_cli::stats::{
17
    RecordedRunConfig, RecordedRunStats, StatsFormat, replace_config_run_stats,
18
};
19
use conjure_cp_cli::utils::conjure::{solutions_to_essence, solutions_to_json};
20
use conjure_cp_cli::utils::rule_trace::RuleApplicationCounter;
21
use 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

            
26
use crate::cli::{GlobalArgs, LOGGING_HELP_HEADING};
27

            
28
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, clap::ValueEnum)]
29
pub enum OutputFormat {
30
    /// Conjure-compatible Essence multi-solution / per-solution files
31
    #[default]
32
    Essence,
33
    /// Conjure `--output-format=json` simplified JSON
34
    Json,
35
}
36

            
37
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38
pub enum NumberOfSolutions {
39
    All,
40
    Limit(i32),
41
}
42

            
43
impl NumberOfSolutions {
44
108
    fn as_solver_limit(self) -> i32 {
45
108
        match self {
46
46
            NumberOfSolutions::All => 0,
47
62
            NumberOfSolutions::Limit(limit) => limit,
48
        }
49
108
    }
50
}
51

            
52
201
fn parse_number_of_solutions(input: &str) -> Result<NumberOfSolutions, String> {
53
201
    if input.eq_ignore_ascii_case("all") {
54
46
        return Ok(NumberOfSolutions::All);
55
155
    }
56

            
57
155
    let limit = input
58
155
        .parse::<i32>()
59
        .map_err(|_| "expected a positive integer or 'all'".to_string())?;
60

            
61
155
    if limit <= 0 {
62
        return Err("expected a positive integer or 'all'".to_string());
63
155
    }
64

            
65
155
    Ok(NumberOfSolutions::Limit(limit))
66
201
}
67

            
68
#[derive(Clone, Debug, clap::Args)]
69
pub struct Args {
70
    /// The input Essence problem file
71
    #[arg(value_name = "INPUT_ESSENCE", value_hint = ValueHint::FilePath)]
72
    pub essence_file: PathBuf,
73

            
74
    /// The input Essence parameter file
75
    #[arg(value_name = "PARAM_ESSENCE", value_hint = ValueHint::FilePath)]
76
    pub param_file: Option<PathBuf>,
77

            
78
    /// Write execution statistics; the .toml or .json extension selects the format.
79
    #[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
    /// Do not run the solver.
84
    ///
85
    /// The rewritten model is printed to stdout in an Essence-style syntax
86
    /// (but is not necessarily valid Essence).
87
    #[arg(long, default_value_t = false)]
88
    pub no_run_solver: bool,
89

            
90
    /// Number of solutions to return. Use a positive integer, or `all`.
91
    #[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
    /// Format for printed / saved solutions
101
    #[arg(long, value_enum, default_value_t = OutputFormat::Essence, help_heading=LOGGING_HELP_HEADING)]
102
    pub output_format: OutputFormat,
103

            
104
    /// Write all solutions into a single file (default: true).
105
    ///
106
    /// Pass `--solutions-in-one-file=false` to emit one file (or stdout record) per solution.
107
    #[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
    /// Save solutions to the given path (Essence `.solutions` / JSON `.solutions.json`, or a
117
    /// filename stem when `--solutions-in-one-file=false`)
118
    #[arg(long, short = 'o', value_hint = ValueHint::FilePath,help_heading=LOGGING_HELP_HEADING)]
119
    pub output: Option<PathBuf>,
120

            
121
    /// When optimising, retain every improving solution Minion reports instead of only the last
122
    /// one.
123
    #[arg(long, default_value_t = false)]
124
    pub keep_intermediate_solutions: bool,
125
}
126

            
127
fn 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

            
133
186
pub fn run_solve_command(
134
186
    global_args: GlobalArgs,
135
186
    solve_args: Args,
136
186
    rule_application_counts: &RuleApplicationCounter,
137
186
) -> anyhow::Result<()> {
138
186
    let pipeline = Pipeline::new(global_args.library_config())?;
139
186
    pipeline
140
186
        .with_settings(|| run_solve(&pipeline, global_args, solve_args, rule_application_counts))
141
186
}
142

            
143
186
fn run_solve(
144
186
    pipeline: &Pipeline,
145
186
    global_args: GlobalArgs,
146
186
    solve_args: Args,
147
186
    rule_application_counts: &RuleApplicationCounter,
148
186
) -> anyhow::Result<()> {
149
186
    let essence_file = solve_args.essence_file.clone();
150
186
    let param_file = solve_args.param_file.clone();
151

            
152
186
    let context = pipeline.context();
153
    {
154
186
        let mut context = context.write().unwrap();
155
186
        context.essence_file_name = Some(essence_file.to_string_lossy().into_owned());
156
186
        context.param_file_name = param_file
157
186
            .as_ref()
158
34
            .map(|path| path.to_string_lossy().into_owned());
159
    }
160

            
161
186
    let translation_started_at = Instant::now();
162
186
    let unified_model = pipeline.with_settings(|| -> anyhow::Result<Model> {
163
186
        let problem_model = pipeline.parse_file(&essence_file)?;
164
158
        match param_file {
165
            Some(param_file) => {
166
34
                let param_model = parse_param(pipeline, &param_file, &problem_model)?;
167
34
                Ok(instantiate_model(problem_model, param_model)?)
168
            }
169
            None => {
170
124
                let mut problem_model = problem_model;
171
124
                validate_instantiation_conditions(&mut problem_model)?;
172
124
                Ok(problem_model)
173
            }
174
        }
175
186
    })?;
176
152
    let rewritten_model = pipeline.rewrite(unified_model)?;
177

            
178
    // Capture representations and SAT encoding choices
179
152
    let mut model_choices = RecordedRunStats::default();
180

            
181
152
    record_model_choices(&rewritten_model, &mut model_choices);
182

            
183
152
    let translation_time = translation_started_at.elapsed().as_secs_f64();
184

            
185
152
    let solver_started_at = Instant::now();
186

            
187
152
    let measured = if solve_args.no_run_solver {
188
44
        println!("{}", rewritten_model);
189

            
190
44
        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
44
        }
198

            
199
44
        None
200
    } else {
201
108
        Some(run_solver(
202
108
            pipeline,
203
108
            &global_args,
204
108
            &solve_args,
205
108
            rewritten_model,
206
108
        )?)
207
    };
208

            
209
152
    let solve_time = measured
210
152
        .as_ref()
211
108
        .map(|_| solver_started_at.elapsed().as_secs_f64());
212

            
213
152
    let backend_time = measured.as_ref().map(|t| t.0);
214
152
    let search_time = measured.as_ref().map(|t| t.1);
215
152
    let solution_processing_time = measured.as_ref().map(|t| t.2);
216

            
217
    // Still write translation statistics when the solver was not run.
218
152
    if let Some(ref path) = solve_args.stats {
219
        let config = RecordedRunConfig {
220
            parser: global_args.parser.to_string(),
221
            rewriter: global_args.rewriter.to_string(),
222
            comprehension_expander: global_args.comprehension_expander.to_string(),
223
            heuristic: global_args.heuristic.to_string(),
224
            channelling: global_args.channelling.to_string(),
225
            seed: global_args.seed,
226
            solver_seed: global_args.solver_seed,
227
            solver: global_args.solver.as_str(),
228
        };
229

            
230
        let case_name = solve_args
231
            .essence_file
232
            .file_stem()
233
            .map(|s| s.to_string_lossy().into_owned())
234
            .unwrap_or_else(|| "input".to_owned());
235

            
236
        let mut row = RecordedRunStats {
237
            parser: config.parser.clone(),
238
            rewriter: config.rewriter.clone(),
239
            comprehension_expander: config.comprehension_expander.clone(),
240
            heuristic: config.heuristic.clone(),
241
            channelling: config.channelling.clone(),
242
            seed: config.seed,
243
            solver_seed: config.solver_seed,
244
            solver: config.solver.clone(),
245
            minion_discrete_threshold: global_args.minion_discrete_threshold,
246

            
247
            case_name,
248
            model_index: 0,
249
            status: "ok".to_owned(),
250

            
251
            solution_limit: (!solve_args.no_run_solver)
252
                .then(|| solve_args.number_of_solutions.as_solver_limit()),
253

            
254
            translation_time: Some(translation_time),
255
            solve_time,
256
            backend_time,
257
            search_time,
258
            solution_processing_time,
259

            
260
            ..Default::default()
261
        };
262

            
263
        row.representations = model_choices.representations;
264

            
265
        row.sat_encoding_amo = model_choices.sat_encoding_amo;
266
        row.sat_encoding_cardinality = model_choices.sat_encoding_cardinality;
267
        row.sat_encoding_pb = model_choices.sat_encoding_pb;
268
        row.sat_encoding_table = model_choices.sat_encoding_table;
269
        row.sat_encoding_element = model_choices.sat_encoding_element;
270
        row.sat_encoding_alldifferent = model_choices.sat_encoding_alldifferent;
271

            
272
        // Read the same rewrite-attempt counters used by exhaustive testing.
273
        let context_json = serde_json::to_value(context.read().unwrap().clone())?;
274

            
275
        let attempt_counts: Vec<u64> = context_json
276
            .get("stats")
277
            .and_then(|stats| stats.get("rewriterRuns"))
278
            .and_then(serde_json::Value::as_array)
279
            .into_iter()
280
            .flatten()
281
            .filter_map(|run| {
282
                run.get("rewriterRuleApplicationAttempts")
283
                    .and_then(serde_json::Value::as_u64)
284
            })
285
            .collect();
286

            
287
        if !attempt_counts.is_empty() {
288
            row.rule_trace.total_rule_attempts = Some(attempt_counts.iter().sum());
289
        }
290

            
291
        let counts = rule_application_counts.snapshot();
292
        row.rule_trace.total_rule_applications = Some(counts.values().copied().sum());
293
        row.rule_trace.rules = counts;
294

            
295
        // Write the completed statistics record only after all fields are populated.
296
        replace_config_run_stats(path, &config, vec![row])?;
297
152
    }
298
152
    Ok(())
299
186
}
300
152
fn record_model_choices(model: &Model, row: &mut RecordedRunStats) {
301
152
    row.representations = model
302
152
        .symbols()
303
152
        .iter_local()
304
29774
        .flat_map(|(_, decl)| {
305
29774
            decl.reprs()
306
29774
                .iter()
307
318
                .map(|(name, _)| name.to_owned())
308
                .collect::<Vec<_>>()
309
29774
        })
310
        .collect::<BTreeSet<_>>()
311
        .into_iter()
312
        .collect();
313
152
    let mut families: BTreeMap<&str, BTreeSet<String>> = BTreeMap::new();
314
    macro_rules! record {
315
        ($family:expr, $selection:expr) => {{
316
522
            $selection.iter().for_each(|selection| {
317
522
                families
318
522
                    .entry($family)
319
522
                    .or_default()
320
522
                    .insert(selection.algorithm.to_string());
321
522
            });
322
        }};
323
    }
324
152
    for decision in model.sat_decisions() {
325
2618
        match decision {
326
            SatEncodingDecision::AtMostOne { encoding, .. } => {
327
                record!("amo", encoding);
328
            }
329
            SatEncodingDecision::Cardinality { encoding, .. } => {
330
                record!("cardinality", encoding);
331
            }
332
            SatEncodingDecision::CountRelation {
333
                encoding,
334
                amo_encoding,
335
                ..
336
            } => {
337
                record!("cardinality", encoding);
338
                record!("amo", amo_encoding);
339
            }
340
            SatEncodingDecision::PseudoBoolean { encoding, .. }
341
            | SatEncodingDecision::IntegerRelation { encoding, .. }
342
522
            | SatEncodingDecision::Objective { encoding, .. } => record!("pb", encoding),
343
            SatEncodingDecision::AllDifferent {
344
                encoding,
345
                amo_encoding,
346
                pb_encoding,
347
                ..
348
            } => {
349
                record!("alldifferent", encoding);
350
                record!("amo", amo_encoding);
351
                record!("pb", pb_encoding);
352
            }
353
            SatEncodingDecision::Table {
354
                encoding,
355
                pb_encoding,
356
                ..
357
            } => {
358
                record!("table", encoding);
359
                record!("pb", pb_encoding);
360
            }
361
            SatEncodingDecision::Element {
362
                encoding,
363
                pb_encoding,
364
                ..
365
            } => {
366
                record!("element", encoding);
367
                record!("pb", pb_encoding);
368
            }
369
2096
            _ => {}
370
        }
371
    }
372
152
    row.sat_encoding_amo = families
373
152
        .remove("amo")
374
152
        .unwrap_or_default()
375
152
        .into_iter()
376
152
        .collect();
377
152
    row.sat_encoding_cardinality = families
378
152
        .remove("cardinality")
379
152
        .unwrap_or_default()
380
152
        .into_iter()
381
152
        .collect();
382
152
    row.sat_encoding_pb = families
383
152
        .remove("pb")
384
152
        .unwrap_or_default()
385
152
        .into_iter()
386
152
        .collect();
387
152
    row.sat_encoding_table = families
388
152
        .remove("table")
389
152
        .unwrap_or_default()
390
152
        .into_iter()
391
152
        .collect();
392
152
    row.sat_encoding_element = families
393
152
        .remove("element")
394
152
        .unwrap_or_default()
395
152
        .into_iter()
396
152
        .collect();
397
152
    row.sat_encoding_alldifferent = families
398
152
        .remove("alldifferent")
399
152
        .unwrap_or_default()
400
152
        .into_iter()
401
152
        .collect();
402
152
}
403
/// Parse an Essence or simplified-JSON parameter file.
404
38
pub(crate) fn parse_param(
405
38
    pipeline: &Pipeline,
406
38
    file_path: &Path,
407
38
    problem_model: &Model,
408
38
) -> anyhow::Result<Model> {
409
38
    if file_path
410
38
        .extension()
411
38
        .is_some_and(|extension| extension == "json")
412
    {
413
        tracing::info!(target: "conjure::stage", path = %file_path.display(), "parsing parameter file");
414
        let text = std::fs::read_to_string(file_path)?;
415
        let given_domains = domains_from_model(problem_model);
416
        let params = params_from_simplified_json_str(&text, &given_domains)?;
417
        return Ok(param_model_from_assignments(
418
            params,
419
            &given_domains,
420
            pipeline.context(),
421
        ));
422
38
    }
423
38
    pipeline.parse_file(file_path)
424
38
}
425

            
426
108
fn run_solver(
427
108
    pipeline: &Pipeline,
428
108
    global_args: &GlobalArgs,
429
108
    cmd_args: &Args,
430
108
    model: Model,
431
108
) -> anyhow::Result<(f64, f64, f64)> {
432
108
    let (solutions, measured) = pipeline.solve_with_timings(
433
108
        model,
434
108
        &SolutionOptions {
435
108
            number_of_solutions: cmd_args.number_of_solutions.as_solver_limit(),
436
108
            keep_intermediate_solutions: cmd_args.keep_intermediate_solutions,
437
108
            solver_input_file: global_args.save_solver_input_file.clone(),
438
108
            rule_trace_cdp: global_args.rule_trace_cdp,
439
108
        },
440
108
    )?;
441

            
442
108
    let output_started_at = Instant::now();
443

            
444
    tracing::debug!(
445
108
        solutions = %solutions_to_json(&solutions),
446
108
        "solver solutions"
447
    );
448

            
449
108
    write_solutions(&solutions, cmd_args)?;
450

            
451
108
    Ok((
452
108
        measured.backend_time_s,
453
108
        measured.search_time_s,
454
108
        measured.solution_processing_time_s + output_started_at.elapsed().as_secs_f64(),
455
108
    ))
456
108
}
457

            
458
108
fn write_solutions(
459
108
    solutions: &[std::collections::BTreeMap<conjure_cp::ast::Name, conjure_cp::ast::Literal>],
460
108
    cmd_args: &Args,
461
108
) -> anyhow::Result<()> {
462
108
    if cmd_args.solutions_in_one_file {
463
108
        let body = match cmd_args.output_format {
464
104
            OutputFormat::Essence => solutions_to_essence(solutions),
465
4
            OutputFormat::Json => solutions_to_simplified_json_string(solutions)?,
466
        };
467
108
        match &cmd_args.output {
468
108
            None => print!("{body}"),
469
            Some(path) => {
470
                std::fs::write(path, body.as_bytes())?;
471
                println!("Solutions saved to {:?}", path.canonicalize()?);
472
            }
473
        }
474
108
        return Ok(());
475
    }
476

            
477
    // One file / record per solution.
478
    for (index, solution) in solutions.iter().enumerate() {
479
        let body = match cmd_args.output_format {
480
            OutputFormat::Essence => solutions_to_essence(std::slice::from_ref(solution)),
481
            OutputFormat::Json => {
482
                let value = solution_to_simplified_json(solution)?;
483
                format!("{}\n", serde_json::to_string_pretty(&value)?)
484
            }
485
        };
486
        match &cmd_args.output {
487
            None => print!("{body}"),
488
            Some(path) => {
489
                let file_path = per_solution_output_path(path, index + 1, cmd_args.output_format);
490
                std::fs::write(&file_path, body.as_bytes())?;
491
                println!("Solution saved to {:?}", file_path.canonicalize()?);
492
            }
493
        }
494
    }
495
    Ok(())
496
108
}
497

            
498
fn per_solution_output_path(base: &Path, index: usize, format: OutputFormat) -> PathBuf {
499
    let stem = base
500
        .file_stem()
501
        .and_then(|s| s.to_str())
502
        .unwrap_or("solution");
503
    let parent = base.parent().unwrap_or_else(|| std::path::Path::new("."));
504
    let extension = match format {
505
        OutputFormat::Essence => "solution",
506
        OutputFormat::Json => "solution.json",
507
    };
508
    parent.join(format!("{stem}-{index:06}.{extension}"))
509
}