kcl-ezpz 0.2.18

A constraint solver for KCL and Zoo Design Studio
Documentation
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
use std::collections::HashMap;

use indexmap::IndexMap;

use crate::Analysis;
use crate::Config;
use crate::Constraint;
use crate::ConstraintRequest;
use crate::FailureOutcome;
use crate::FreedomAnalysis;
use crate::IdGenerator;
use crate::NoAnalysis;
use crate::SolveOutcome;
use crate::SolveOutcomeAnalysis;
use crate::Warning;
use crate::datatypes;
use crate::datatypes::AngleKind;
use crate::datatypes::inputs::DatumCircularArc;
use crate::datatypes::inputs::DatumDistance;
use crate::datatypes::inputs::DatumLineSegment;
use crate::datatypes::inputs::DatumPoint;
use crate::datatypes::outputs::Arc;
use crate::datatypes::outputs::{Circle, Component, Point};
use crate::error::TextualError;
use crate::textual::Label;
use crate::textual::geometry_variables::DoneState;
use crate::textual::geometry_variables::GeometryVariables;
use crate::textual::geometry_variables::PointsState;
use crate::textual::geometry_variables::VARS_PER_ARC;
use crate::textual::instruction::*;

use super::Instruction;
use super::Problem;

impl Problem {
    /// Build a [`ConstraintSystem`] which models the system in this problem.
    /// Error means this problem was not properly specified, e.g. it could be
    /// missing a variable used in a constraint.
    pub fn to_constraint_system(&self) -> Result<ConstraintSystem<'_>, TextualError> {
        let mut id_generator = IdGenerator::default();
        // First, construct the list of initial guesses,
        // and assign them to solver variables.
        let mut initial_guesses: GeometryVariables<PointsState> = Default::default();
        // Maps labels to points
        let mut guessmap_points = HashMap::new();
        guessmap_points.extend(
            self.point_guesses
                .iter()
                .map(|pg| (pg.point.0.clone(), pg.guess)),
        );
        for point in &self.inner_points {
            let Some(guess) = guessmap_points.remove(&point.0) else {
                return Err(TextualError::MissingGuess {
                    label: point.0.clone(),
                });
            };
            initial_guesses.push_point(&mut id_generator, guess.x, guess.y);
        }
        let mut guessmap_scalars = HashMap::new();
        guessmap_scalars.extend(
            self.scalar_guesses
                .iter()
                .map(|sg| (sg.scalar.0.clone(), sg.guess)),
        );
        let mut initial_guesses = initial_guesses.done();
        for circle in &self.inner_circles {
            // Each circle should have a guess for its center and radius.
            // First, find the guess for its center:
            let center_label = format!("{}.center", circle.0);
            let Some(center_guess) = guessmap_points.remove(&center_label) else {
                return Err(TextualError::MissingGuess {
                    label: center_label,
                });
            };
            // Now, find the guess for its radius.
            let radius_label = format!("{}.radius", circle.0);
            let Some(radius_guess) = guessmap_scalars.remove(&radius_label) else {
                return Err(TextualError::MissingGuess {
                    label: radius_label,
                });
            };
            initial_guesses.push_circle(
                &mut id_generator,
                center_guess.x,
                center_guess.y,
                radius_guess,
            );
        }
        let mut initial_guesses = initial_guesses.done();
        for arc in &self.inner_arcs {
            // Each arc should have a guess for its 3 points (p, q, and center).
            let center_label = format!("{}.center", arc.0);
            let Some(center_guess) = guessmap_points.remove(&center_label) else {
                return Err(TextualError::MissingGuess {
                    label: center_label,
                });
            };
            let a_label = format!("{}.a", arc.0);
            let Some(a_guess) = guessmap_points.remove(&a_label) else {
                return Err(TextualError::MissingGuess { label: a_label });
            };
            let b_label = format!("{}.b", arc.0);
            let Some(b_guess) = guessmap_points.remove(&b_label) else {
                return Err(TextualError::MissingGuess { label: b_label });
            };
            initial_guesses.push_arc(&mut id_generator, a_guess, b_guess, center_guess);
        }
        if !guessmap_points.is_empty() {
            let labels: Vec<String> = guessmap_points.keys().cloned().collect();
            return Err(TextualError::UnusedGuesses { labels });
        }
        if !guessmap_scalars.is_empty() {
            let labels: Vec<String> = guessmap_scalars.keys().cloned().collect();
            return Err(TextualError::UnusedGuesses { labels });
        }

        // Good. Now we can define all the constraints, referencing the solver variables that
        // were defined in the previous step.
        let mut constraints = Vec::new();
        let datum_point_for_label = |label: &Label| -> Result<DatumPoint, TextualError> {
            // Is the point a single geometric point?
            if let Some(point_id) = self.inner_points.iter().position(|p| p == &label.0) {
                let ids = initial_guesses.point_ids(point_id);
                return Ok(DatumPoint {
                    x_id: ids.x,
                    y_id: ids.y,
                });
            }
            // Maybe it's a point in a circle?
            if let Some(circle_id) = self
                .inner_circles
                .iter()
                .position(|circ| format!("{}.center", circ.0) == label.0.as_str())
            {
                let center = initial_guesses.circle_ids(circle_id).center;
                return Ok(DatumPoint {
                    x_id: center.x,
                    y_id: center.y,
                });
            }
            // Maybe it's a point in an arc?
            // Is it an arc's center?
            if let Some(arc_id) = self
                .inner_arcs
                .iter()
                .position(|arc| format!("{}.center", arc.0) == label.0.as_str())
            {
                let center = initial_guesses.arc_ids(arc_id).center;
                return Ok(center.into());
            }
            // Is it an arc's start point (labeled as `.a` in textual format)?
            if let Some(arc_id) = self
                .inner_arcs
                .iter()
                .position(|arc| format!("{}.a", arc.0) == label.0.as_str())
            {
                let start = initial_guesses.arc_ids(arc_id).start;
                return Ok(start.into());
            }
            // Is it an arc's end point (labeled as `.b` in textual format)?
            if let Some(arc_id) = self
                .inner_arcs
                .iter()
                .position(|arc| format!("{}.b", arc.0) == label.0.as_str())
            {
                let end = initial_guesses.arc_ids(arc_id).end;
                return Ok(end.into());
            }
            // Well, it wasn't any of the geometries we recognize.
            Err(TextualError::UndefinedPoint {
                label: label.0.clone(),
            })
        };
        let datum_distance_for_label = |label: &Label| -> Result<DatumDistance, TextualError> {
            if let Some(circle_id) = self
                .inner_circles
                .iter()
                .position(|circ| format!("{}.radius", circ.0) == label.0.as_str())
            {
                let ids = initial_guesses.circle_ids(circle_id);
                return Ok(DatumDistance { id: ids.radius });
            }
            Err(TextualError::UndefinedPoint {
                label: label.0.clone(),
            })
        };

        for instr in &self.instructions {
            match instr {
                Instruction::DeclarePoint(_) => {}
                Instruction::DeclareCircle(_) => {}
                Instruction::DeclareArc(_) => {}
                Instruction::Line(_) => {}
                Instruction::CircleRadius(CircleRadius { circle, radius }) => {
                    let circ = &circle.0;
                    let center_id = datum_point_for_label(&Label(format!("{circ}.center")))?;
                    let radius_id = datum_distance_for_label(&Label(format!("{circ}.radius")))?;
                    constraints.push(Constraint::CircleRadius(
                        datatypes::inputs::DatumCircle {
                            center: center_id,
                            radius: radius_id,
                        },
                        *radius,
                    ));
                }
                Instruction::ArcRadius(ArcRadius { arc_label, radius }) => {
                    let arc_label = &arc_label.0;
                    let circular_arc = DatumCircularArc {
                        center: datum_point_for_label(&Label(format!("{arc_label}.center")))?,
                        start: datum_point_for_label(&Label(format!("{arc_label}.a")))?,
                        end: datum_point_for_label(&Label(format!("{arc_label}.b")))?,
                    };
                    constraints.push(Constraint::ArcRadius(circular_arc, *radius));
                }
                Instruction::IsArc(IsArc { arc_label }) => {
                    let arc_label = &arc_label.0;
                    let circular_arc = DatumCircularArc {
                        center: datum_point_for_label(&Label(format!("{arc_label}.center")))?,
                        start: datum_point_for_label(&Label(format!("{arc_label}.a")))?,
                        end: datum_point_for_label(&Label(format!("{arc_label}.b")))?,
                    };
                    constraints.push(Constraint::Arc(circular_arc));
                }
                Instruction::PointLineDistance(PointLineDistance {
                    point,
                    line_p0,
                    line_p1,
                    distance,
                }) => {
                    let line = DatumLineSegment {
                        p0: datum_point_for_label(line_p0)?,
                        p1: datum_point_for_label(line_p1)?,
                    };
                    let p = datum_point_for_label(point)?;
                    constraints.push(Constraint::PointLineDistance(p, line, *distance));
                }
                Instruction::Tangent(Tangent {
                    circle,
                    line_p0,
                    line_p1,
                }) => {
                    let circ = &circle.0;
                    let center_id = datum_point_for_label(&Label(format!("{circ}.center")))?;
                    let radius_id = datum_distance_for_label(&Label(format!("{circ}.radius")))?;
                    let line = DatumLineSegment {
                        p0: datum_point_for_label(line_p0)?,
                        p1: datum_point_for_label(line_p1)?,
                    };
                    constraints.push(Constraint::LineTangentToCircle(
                        line,
                        datatypes::inputs::DatumCircle {
                            center: center_id,
                            radius: radius_id,
                        },
                    ));
                }
                Instruction::FixPointComponent(FixPointComponent {
                    point,
                    component,
                    value,
                }) => {
                    if let Some(point_id) =
                        self.inner_points.iter().position(|label| label == point)
                    {
                        let ids = initial_guesses.point_ids(point_id);
                        let id = match component {
                            Component::X => ids.x,
                            Component::Y => ids.y,
                        };
                        constraints.push(Constraint::Fixed(id, *value));
                    } else if let Some(circle_label) = point.0.strip_suffix(".center") {
                        if let Some(circle_id) =
                            self.inner_circles.iter().position(|p| p.0 == circle_label)
                        {
                            let center = initial_guesses.circle_ids(circle_id).center;
                            let id = match component {
                                Component::X => center.x,
                                Component::Y => center.y,
                            };
                            constraints.push(Constraint::Fixed(id, *value));
                        }
                    } else {
                        return Err(TextualError::UndefinedPoint {
                            label: point.0.clone(),
                        });
                    }
                }
                Instruction::FixCenterPointComponent(FixCenterPointComponent {
                    object,
                    center_component,
                    value,
                }) => {
                    // Is this center talking about a circle object?
                    if let Some(circle_id) =
                        self.inner_circles.iter().position(|label| label == object)
                    {
                        let center = initial_guesses.circle_ids(circle_id).center;
                        let id = match center_component {
                            Component::X => center.x,
                            Component::Y => center.y,
                        };
                        constraints.push(Constraint::Fixed(id, *value));
                    // Is this center talking about an arc object?
                    } else if let Some(arc_id) =
                        self.inner_arcs.iter().position(|label| label == object)
                    {
                        let center = initial_guesses.arc_ids(arc_id).center;
                        let id = match center_component {
                            Component::X => center.x,
                            Component::Y => center.y,
                        };
                        constraints.push(Constraint::Fixed(id, *value));
                    } else {
                        return Err(TextualError::UndefinedPoint {
                            label: object.0.clone(),
                        });
                    }
                }
                Instruction::Vertical(Vertical { label }) => {
                    let p0 = datum_point_for_label(&label.0)?;
                    let p1 = datum_point_for_label(&label.1)?;
                    constraints.push(Constraint::Vertical(DatumLineSegment { p0, p1 }));
                }
                Instruction::PointsCoincident(PointsCoincident { point0, point1 }) => {
                    let p0 = datum_point_for_label(point0)?;
                    let p1 = datum_point_for_label(point1)?;
                    constraints.push(Constraint::PointsCoincident(p0, p1));
                }
                Instruction::PointArcCoincident(PointArcCoincident { point, arc }) => {
                    let p = datum_point_for_label(point)?;
                    let arc_label = &arc.0;
                    let datum_arc = DatumCircularArc {
                        center: datum_point_for_label(&Label(format!("{arc_label}.center")))?,
                        start: datum_point_for_label(&Label(format!("{arc_label}.a")))?,
                        end: datum_point_for_label(&Label(format!("{arc_label}.b")))?,
                    };
                    constraints.push(Constraint::PointArcCoincident(datum_arc, p));
                }
                Instruction::Midpoint(Midpoint { point0, point1, mp }) => {
                    let p0 = datum_point_for_label(point0)?;
                    let p1 = datum_point_for_label(point1)?;
                    let mp = datum_point_for_label(mp)?;
                    constraints.push(Constraint::Midpoint(DatumLineSegment { p0, p1 }, mp));
                }
                Instruction::Symmetric(Symmetric { p0, p1, line }) => {
                    let p0 = datum_point_for_label(p0)?;
                    let p1 = datum_point_for_label(p1)?;
                    let line = (
                        datum_point_for_label(&line.0)?,
                        datum_point_for_label(&line.1)?,
                    );
                    let line = DatumLineSegment {
                        p0: line.0,
                        p1: line.1,
                    };
                    constraints.push(Constraint::Symmetric(line, p0, p1));
                }
                Instruction::Horizontal(Horizontal { label }) => {
                    let p0 = datum_point_for_label(&label.0)?;
                    let p1 = datum_point_for_label(&label.1)?;
                    constraints.push(Constraint::Horizontal(DatumLineSegment { p0, p1 }));
                }
                Instruction::Distance(Distance { label, distance }) => {
                    let p0 = datum_point_for_label(&label.0)?;
                    let p1 = datum_point_for_label(&label.1)?;
                    constraints.push(Constraint::Distance(p0, p1, *distance));
                }
                Instruction::Parallel(Parallel { line0, line1 }) => {
                    let p0 = datum_point_for_label(&line0.0)?;
                    let p1 = datum_point_for_label(&line0.1)?;
                    let p2 = datum_point_for_label(&line1.0)?;
                    let p3 = datum_point_for_label(&line1.1)?;
                    constraints.push(Constraint::lines_parallel([
                        DatumLineSegment { p0, p1 },
                        DatumLineSegment { p0: p2, p1: p3 },
                    ]));
                }
                Instruction::LinesEqualLength(LinesEqualLength { line0, line1 }) => {
                    let p0 = datum_point_for_label(&line0.0)?;
                    let p1 = datum_point_for_label(&line0.1)?;
                    let p2 = datum_point_for_label(&line1.0)?;
                    let p3 = datum_point_for_label(&line1.1)?;
                    constraints.push(Constraint::LinesEqualLength(
                        DatumLineSegment { p0, p1 },
                        DatumLineSegment { p0: p2, p1: p3 },
                    ));
                }
                Instruction::Perpendicular(Perpendicular { line0, line1 }) => {
                    let p0 = datum_point_for_label(&line0.0)?;
                    let p1 = datum_point_for_label(&line0.1)?;
                    let p2 = datum_point_for_label(&line1.0)?;
                    let p3 = datum_point_for_label(&line1.1)?;
                    constraints.push(Constraint::lines_perpendicular([
                        DatumLineSegment { p0, p1 },
                        DatumLineSegment { p0: p2, p1: p3 },
                    ]));
                }
                Instruction::AngleLine(AngleLine {
                    line0,
                    line1,
                    angle,
                }) => {
                    let p0 = datum_point_for_label(&line0.0)?;
                    let p1 = datum_point_for_label(&line0.1)?;
                    let p2 = datum_point_for_label(&line1.0)?;
                    let p3 = datum_point_for_label(&line1.1)?;
                    constraints.push(Constraint::LinesAtAngle(
                        DatumLineSegment { p0, p1 },
                        DatumLineSegment { p0: p2, p1: p3 },
                        AngleKind::Other(*angle),
                    ));
                }
                Instruction::ArcLength(arc_length) => {
                    let arc_label = &arc_length.arc.0;
                    let length = arc_length.distance;
                    let circular_arc = DatumCircularArc {
                        center: datum_point_for_label(&Label(format!("{arc_label}.center")))?,
                        start: datum_point_for_label(&Label(format!("{arc_label}.a")))?,
                        end: datum_point_for_label(&Label(format!("{arc_label}.b")))?,
                    };
                    constraints.push(Constraint::ArcLength(circular_arc, length));
                }
            }
        }
        let initial_guesses = initial_guesses.done();

        // At some point, the textual format should support setting priority.
        // For now, set it to max priority.
        let priority = 0;
        let constraints = constraints
            .into_iter()
            .map(|c| ConstraintRequest::new(c, priority))
            .collect();

        Ok(ConstraintSystem {
            constraints,
            initial_guesses,
            inner_points: &self.inner_points,
            inner_circles: &self.inner_circles,
            inner_arcs: &self.inner_arcs,
            inner_lines: &self.inner_lines,
        })
    }
}

/// A constraint system that ezpz could solve,
/// built from the ezpz text format.
#[derive(Clone)]
pub struct ConstraintSystem<'a> {
    /// Constraints from the text input.
    pub constraints: Vec<ConstraintRequest>,
    initial_guesses: GeometryVariables<DoneState>,
    inner_points: &'a [Label],
    inner_circles: &'a [Label],
    inner_arcs: &'a [Label],
    inner_lines: &'a [(Label, Label)],
}

impl ConstraintSystem<'_> {
    /// Solve, without carrying through metadata about the solve.
    pub fn solve_no_metadata(&self, config: Config) -> Result<SolveOutcome, FailureOutcome> {
        crate::solve(&self.constraints, self.initial_guesses.variables(), config)
    }

    fn solve_no_metadata_inner<A: Analysis>(
        &self,
        config: Config,
    ) -> Result<SolveOutcomeAnalysis<A>, FailureOutcome> {
        crate::solve_with_priority_inner(
            &self.constraints,
            self.initial_guesses.variables(),
            config,
        )
    }

    /// Solve, with metadata about the solve.
    pub fn solve(&self) -> Result<Outcome, FailureOutcome> {
        self.solve_with_config(Default::default())
    }

    /// Solve, and analyze the degrees of freedom.
    pub fn solve_with_config_analysis(
        &self,
        config: Config,
    ) -> Result<OutcomeAnalysis, FailureOutcome> {
        let (analysis, outcome) = self.solve_with_config_inner::<FreedomAnalysis>(config)?;
        Ok(OutcomeAnalysis { analysis, outcome })
    }

    /// Solve, but give a non-default config.
    pub fn solve_with_config(&self, config: Config) -> Result<Outcome, FailureOutcome> {
        let (NoAnalysis, outcome) = self.solve_with_config_inner::<NoAnalysis>(config)?;
        Ok(outcome)
    }

    fn solve_with_config_inner<A: Analysis>(
        &self,
        config: Config,
    ) -> Result<(A, Outcome), FailureOutcome> {
        let num_vars = self.initial_guesses.len();
        let num_eqs = self
            .constraints
            .iter()
            .map(|c| c.constraint().residual_dim())
            .sum();
        // Pass into the solver.
        let SolveOutcomeAnalysis {
            analysis,
            outcome:
                SolveOutcome {
                    iterations,
                    warnings,
                    final_values,
                    unsatisfied,
                    priority_solved,
                },
        } = self.solve_no_metadata_inner::<A>(config)?;
        let num_points = self.inner_points.len();
        let num_circles = self.inner_circles.len();
        let num_arcs = self.inner_arcs.len();

        let mut final_points = IndexMap::with_capacity(num_points);
        for (i, point) in self.inner_points.iter().enumerate() {
            let x_id = 2 * i;
            let y_id = 2 * i + 1;
            let p = Point {
                x: final_values[x_id],
                y: final_values[y_id],
            };
            final_points.insert(point.0.clone(), p);
        }
        let start_of_circles = 2 * self.inner_points.len();
        let mut final_circles = IndexMap::with_capacity(num_circles);
        for (i, circle_label) in self.inner_circles.iter().enumerate() {
            let cx = final_values[start_of_circles + 3 * i]; // center x
            let cy = final_values[start_of_circles + 3 * i + 1]; // center y
            let rd = final_values[start_of_circles + 3 * i + 2]; // radius
            final_circles.insert(
                circle_label.0.clone(),
                Circle {
                    radius: rd,
                    center: Point { x: cx, y: cy },
                },
            );
        }
        let start_of_arcs = start_of_circles + 3 * self.inner_circles.len();
        let mut final_arcs = IndexMap::with_capacity(num_arcs);
        for (i, arc_label) in self.inner_arcs.iter().enumerate() {
            let ax = final_values[start_of_arcs + VARS_PER_ARC * i];
            let ay = final_values[start_of_arcs + VARS_PER_ARC * i + 1];
            let bx = final_values[start_of_arcs + VARS_PER_ARC * i + 2];
            let by = final_values[start_of_arcs + VARS_PER_ARC * i + 3];
            let cx = final_values[start_of_arcs + VARS_PER_ARC * i + 4];
            let cy = final_values[start_of_arcs + VARS_PER_ARC * i + 5];
            final_arcs.insert(
                arc_label.0.clone(),
                Arc {
                    center: Point { x: cx, y: cy },
                    a: Point { x: ax, y: ay },
                    b: Point { x: bx, y: by },
                },
            );
        }
        Ok((
            analysis,
            Outcome {
                priority_solved,
                unsatisfied,
                iterations,
                warnings,
                points: final_points,
                circles: final_circles,
                arcs: final_arcs,
                num_vars,
                lines: self.inner_lines.to_vec(),
                num_eqs,
            },
        ))
    }
}

/// Outcome of successfully solving a constraint system.
#[derive(Debug)]
pub struct Outcome {
    /// All constraint IDs which couldn't be satisfied.
    pub unsatisfied: Vec<usize>,
    /// How many iterations of the core Newton-Gauss loop this system required.
    pub iterations: usize,
    /// Anything bad that users should know about.
    pub warnings: Vec<Warning>,
    /// Points the user defined, with their final solved values.
    pub points: IndexMap<String, Point>,
    /// Circles the user defined, with their final solved values.
    pub circles: IndexMap<String, Circle>,
    /// Arcs the user defined, with their final solved values.
    pub arcs: IndexMap<String, Arc>,
    /// Lines the user defined, with labels for their two points.
    pub lines: Vec<(Label, Label)>,
    /// Size of the constraint system. Number of variables being solved for.
    pub num_vars: usize,
    /// Size of the constraint system. Number of residual equations.
    pub num_eqs: usize,
    /// The lowest priority solved before the constraint solver stopped.
    /// The constraint solver stops when it cannot solve any more constraints, i.e.
    /// got an error.
    pub priority_solved: u32,
}

/// Outcome of solving an ezpz system, and degrees-of-freedom analysis.
#[derive(Debug)]
pub struct OutcomeAnalysis {
    /// Degrees of freedom analysis
    pub analysis: FreedomAnalysis,
    /// Outcome of solving the constraint system.
    pub outcome: Outcome,
}

impl Outcome {
    /// Look up a point by its label.
    pub fn get_point(&self, label: &str) -> Option<Point> {
        self.points.get(label).copied()
    }

    /// Look up a circle by its label.
    pub fn get_circle(&self, label: &str) -> Option<Circle> {
        self.circles.get(label).copied()
    }

    /// Look up an arc by its label.
    pub fn get_arc(&self, label: &str) -> Option<Arc> {
        self.arcs.get(label).copied()
    }
}

impl OutcomeAnalysis {
    /// Look up a point by its label.
    #[cfg(test)]
    pub fn get_point(&self, label: &str) -> Option<Point> {
        self.outcome.get_point(label)
    }

    /// Look up a circle by its label.
    #[cfg(test)]
    pub fn get_circle(&self, label: &str) -> Option<Circle> {
        self.outcome.get_circle(label)
    }

    /// Look up an arc by its label.
    #[cfg(test)]
    pub fn get_arc(&self, label: &str) -> Option<Arc> {
        self.outcome.get_arc(label)
    }

    /// Are all constraints satisfied?
    #[cfg(test)]
    pub fn is_satisfied(&self) -> bool {
        !self.is_unsatisfied()
    }

    /// Are any constraints not satisfied?
    #[cfg(test)]
    pub fn is_unsatisfied(&self) -> bool {
        !self.outcome.unsatisfied.is_empty()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::textual::{PointGuess, instruction::FixPointComponent};

    fn empty_problem() -> Problem {
        Problem {
            instructions: Vec::new(),
            inner_points: Vec::new(),
            inner_circles: Vec::new(),
            inner_arcs: Vec::new(),
            inner_lines: Vec::new(),
            point_guesses: Vec::new(),
            scalar_guesses: Vec::new(),
        }
    }

    #[test]
    fn missing_guess_is_reported() {
        let mut problem = empty_problem();
        problem.inner_points.push(Label::from("p"));
        let err = problem
            .to_constraint_system()
            .err()
            .expect("expected missing guess");
        assert!(matches!(err, TextualError::MissingGuess { label } if label == "p"));
    }

    #[test]
    fn unused_guesses_are_detected() {
        let mut problem = empty_problem();
        problem.point_guesses.push(PointGuess {
            point: Label::from("ghost"),
            guess: Point { x: 0.0, y: 0.0 },
        });

        let err = problem
            .to_constraint_system()
            .err()
            .expect("expected unused guess error");
        match err {
            TextualError::UnusedGuesses { labels } => {
                assert_eq!(labels.len(), 1);
                assert_eq!(labels[0], "ghost");
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn undefined_point_in_instruction_errors() {
        let mut problem = empty_problem();
        problem.inner_points.push(Label::from("p"));
        problem.point_guesses.push(PointGuess {
            point: Label::from("p"),
            guess: Point { x: 0.0, y: 0.0 },
        });
        problem
            .instructions
            .push(Instruction::FixPointComponent(FixPointComponent {
                point: Label::from("missing"),
                component: Component::X,
                value: 2.5,
            }));

        let err = problem
            .to_constraint_system()
            .err()
            .expect("expected undefined point error");
        assert!(matches!(err, TextualError::UndefinedPoint { label } if label == "missing"));
    }
}