symbolica 3.0.0

A blazing fast computer algebra system
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
//! Python protocols for eager exact solution sets.
use super::*;
use crate::solve::{SolutionSet, SolveCoverage, SolveError};

/// Show assignments and conditions; free variables remain in the metadata.
fn solution_text(solution: &Solution, atom: &impl Fn(&Atom) -> String) -> String {
    let assignments = solution
        .iter()
        .map(|(variable, value)| format!("{} = {}", atom(&variable.to_atom()), atom(value)))
        .collect::<Vec<_>>()
        .join(", ");
    let mut text = format!("{{{assignments}}}");
    if solution.is_conditional() {
        text.push_str(" where ");
        text.push_str(
            &solution
                .conditions()
                .iter()
                .map(|c| condition_text(c, atom))
                .collect::<Vec<_>>()
                .join(" & "),
        );
    }
    text
}

fn formatted_atom_with_color(atom: &Atom, color: ColorMode) -> String {
    atom.format_string(
        &PrintOptions::new()
            .max_line_length(Some(80))
            .multiplication_operator('ยท')
            .num_exp_as_superscript(true)
            .max_terms(Some(100))
            .color_mode(color),
        PrintState::new(),
    )
}

pub(super) fn formatted_atom(atom: &Atom) -> String {
    formatted_atom_with_color(atom, ColorMode::Always)
}

fn pretty_atom(atom: &Atom) -> String {
    formatted_atom_with_color(atom, ColorMode::Never)
}

fn condition_text(condition: &SolutionCondition, atom: &impl Fn(&Atom) -> String) -> String {
    condition.format_with(atom)
}

pub(super) fn inline_html(formatted: &str) -> String {
    let html = crate::printer::AnsiHtmlFormatter::new(formatted).to_string();
    html.strip_prefix("<div style=\"white-space: pre-wrap; margin: 0;\">")
        .and_then(|s| s.strip_suffix("</div>"))
        .unwrap_or(&html)
        .to_owned()
}

fn guard_text(guard: &[Atom], atom: &impl Fn(&Atom) -> String) -> String {
    guard
        .iter()
        .map(|a| format!("{} != 0", atom(a)))
        .collect::<Vec<_>>()
        .join(" & ")
}
fn guard_html(guard: &[Atom]) -> String {
    inline_html(&guard_text(guard, &formatted_atom))
}
fn guard_condition(guard: &[Atom]) -> crate::id::Condition<crate::id::Relation> {
    guard
        .iter()
        .map(|a| {
            crate::id::Condition::Yield(crate::id::Relation::Ne(
                a.clone().into(),
                Atom::num(0).into(),
            ))
        })
        .reduce(|a, b| a & b)
        .unwrap_or(crate::id::Condition::True)
}
fn relation_condition(
    condition: &SolutionCondition,
) -> Option<crate::id::Condition<crate::id::Relation>> {
    use crate::id::{Condition, Relation};
    let right = Atom::num(0).into();
    Some(Condition::Yield(match condition {
        SolutionCondition::Zero(a) => Relation::Eq(a.clone().into(), right),
        SolutionCondition::NonZero(a) => Relation::Ne(a.clone().into(), right),
        SolutionCondition::Positive(a) => Relation::Gt(a.clone().into(), right),
        SolutionCondition::DomainMembership { .. } => return None,
    }))
}

fn condition_html(condition: &SolutionCondition) -> String {
    inline_html(&condition_text(condition, &formatted_atom))
}

/// Keep equations aligned without relying on notebook table styles.
fn solution_html(
    solution: &Solution,
    conditions: &[SolutionCondition],
    index: Option<usize>,
) -> PyResult<String> {
    let assignments = solution.coordinates();
    let mut html = String::from(
        "<div style=\"display: flex; align-items: baseline; gap: 0.75em; line-height: 1.6\">",
    );
    if let Some(index) = index {
        html.push_str(&format!(
            "<span style=\"opacity: 0.65; font-size: 0.85em; flex-shrink: 0\">({index}) </span>"
        ));
    }
    html.push_str(
        "<div style=\"display: grid; grid-template-columns: max-content max-content minmax(0, 1fr); column-gap: 0.4em; align-items: baseline; min-width: 0\">",
    );
    if assignments.is_empty() {
        html.push_str("<div style=\"grid-column: 1 / -1\">{}</div>");
    }
    for coordinate in assignments {
        let variable: PythonExpression = coordinate.0.to_atom().into();
        let value: PythonExpression = coordinate.1.clone().into();
        html.push_str(&format!(
            "{}<span> = </span>{}",
            variable._repr_html_()?,
            value._repr_html_()?,
        ));
    }
    if !conditions.is_empty() {
        html.push_str(&format!(
            "<div style=\"grid-column: 1 / -1; margin-top: 0.25em\"><small>where {}</small></div>",
            conditions
                .iter()
                .map(condition_html)
                .collect::<Vec<_>>()
                .join(" &amp; "),
        ));
    }
    html.push_str("</div></div>");
    Ok(html)
}

/// Python exceptions raised by the equation solver.
pub mod errors {
    use pyo3::create_exception;
    create_exception!(
        symbolica,
        SolveError,
        pyo3::exceptions::PyValueError,
        "Base exception for invalid solve requests or failures to obtain the requested result."
    );
    create_exception!(
        symbolica,
        UnsupportedProblem,
        SolveError,
        "The equations require a solving method that is not supported."
    );
    create_exception!(
        symbolica,
        IncompleteCoverage,
        SolveError,
        "The requested conclusion cannot be established for all relevant cases."
    );
}
pub(super) fn solve_error(error: SolveError) -> PyErr {
    let message = error.to_string();
    match error {
        SolveError::UnsupportedProblem(_) => errors::UnsupportedProblem::new_err(message),
        SolveError::IncompleteCoverage(_) => errors::IncompleteCoverage::new_err(message),
        _ => errors::SolveError::new_err(message),
    }
}

/// A formula or domain restriction under which a solution branch is valid.
#[cfg_attr(feature = "python_stubgen", gen_stub_pyclass)]
#[pyclass(
    frozen,
    skip_from_py_object,
    name = "SolutionCondition",
    module = "symbolica.core"
)]
#[derive(Clone)]
pub struct PythonSolutionCondition {
    condition: SolutionCondition,
}
#[cfg_attr(feature = "python_stubgen", gen_stub_pymethods)]
#[pymethods]
impl PythonSolutionCondition {
    /// The restriction type: ``"formula"`` or ``"domain_membership"``.
    #[getter]
    fn kind(&self) -> &'static str {
        match self.condition {
            SolutionCondition::DomainMembership { .. } => "domain_membership",
            _ => "formula",
        }
    }
    /// The symbolic condition, or None for a domain-membership restriction.
    #[getter]
    fn formula(&self) -> Option<PythonCondition> {
        relation_condition(&self.condition).map(Into::into)
    }
    /// The variable restricted by a domain-membership condition, otherwise None.
    #[getter]
    fn variable(&self) -> Option<PythonExpression> {
        match &self.condition {
            SolutionCondition::DomainMembership { variable, .. } => Some(variable.to_atom().into()),
            _ => None,
        }
    }
    /// The expression restricted by a domain-membership condition, otherwise None.
    #[getter]
    fn value(&self) -> Option<PythonExpression> {
        match &self.condition {
            SolutionCondition::DomainMembership { value, .. } => Some(value.clone().into()),
            _ => None,
        }
    }
    /// The required domain for a domain-membership condition, otherwise None.
    #[getter]
    fn domain(&self) -> Option<PythonSolveDomain> {
        match &self.condition {
            SolutionCondition::DomainMembership { domain, .. } => Some((*domain).into()),
            _ => None,
        }
    }
    fn __repr__(&self) -> String {
        self.condition.to_string()
    }
    fn _repr_html_(&self) -> String {
        condition_html(&self.condition)
    }
}
/// One equality-solution branch: Expression assignments and validity conditions.
///
/// Index or iterate over the mapping to read assigned variables and their values.
/// Use ``free_variables()`` for the family's free coordinates and ``variables``
/// for all requested unknowns. All assignments hold simultaneously, subject to
/// ``conditions()``, which includes the parent set's coverage guard.
///
/// Examples
/// --------
/// >>> from symbolica import Expression, S
/// >>> x, y = S("x", "y")
/// >>> branch = Expression.solve(x + y - 1, [x, y])[0]
/// >>> branch[x] == 1 - y
/// True
/// >>> dict(branch) == {x: 1-y}
/// True
/// >>> branch.free_variables() == [y]
/// True
/// >>> y in branch
/// False
#[cfg_attr(feature = "python_stubgen", gen_stub_pyclass)]
#[pyclass(
    frozen,
    skip_from_py_object,
    name = "Solution",
    module = "symbolica.core"
)]
#[derive(Clone)]
pub struct PythonSolution {
    solution: Solution,
    coverage_guard: Vec<Atom>,
}
impl From<Solution> for PythonSolution {
    fn from(solution: Solution) -> Self {
        Self {
            solution,
            coverage_guard: Vec::new(),
        }
    }
}
impl PythonSolution {
    fn text_with(&self, atom: &impl Fn(&Atom) -> String) -> String {
        let mut text = solution_text(&self.solution, atom);
        let mut conditional = self.solution.is_conditional();
        for condition in self
            .coverage_guard
            .iter()
            .map(|a| SolutionCondition::NonZero(a.clone()))
        {
            if !self.solution.conditions().contains(&condition) {
                text.push_str(if conditional { " & " } else { " where " });
                text.push_str(&condition_text(&condition, atom));
                conditional = true;
            }
        }
        text
    }
    fn from_set(solution: Solution, set: &SolutionSet) -> Self {
        Self {
            solution,
            coverage_guard: set.coverage_guard().to_vec(),
        }
    }
}
#[cfg_attr(feature = "python_stubgen", gen_stub_pymethods)]
#[cfg_attr(not(feature = "python_stubgen"), remove_gen_stub)]
#[pymethods]
impl PythonSolution {
    /// Return assigned variables mapped directly to Expressions.
    ///
    /// Use ``free_variables()`` for free coordinates and ``conditions()`` for the
    /// restrictions under which these assignments are valid.
    #[gen_stub(override_return_type(type_repr = "dict[Expression, Expression]"))]
    fn as_dict<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
        let dict = PyDict::new(py);
        for (k, v) in self.items() {
            dict.set_item(k, v)?;
        }
        Ok(dict)
    }
    /// All requested unknowns in coordinate order, including free variables.
    #[getter]
    fn variables(&self) -> Vec<PythonExpression> {
        self.solution
            .coordinate_order()
            .map(|v| v.to_atom().into())
            .collect()
    }
    /// Return the unknowns that remain free within this branch.
    fn free_variables(&self) -> Vec<PythonExpression> {
        self.solution
            .free_variables()
            .iter()
            .map(|v| v.to_atom().into())
            .collect()
    }
    /// Return additional conditions that must hold for this branch to be valid.
    fn conditions(&self) -> Vec<PythonSolutionCondition> {
        let mut conditions = self.solution.conditions().to_vec();
        for guard in self
            .coverage_guard
            .iter()
            .map(|a| SolutionCondition::NonZero(a.clone()))
        {
            if !conditions.contains(&guard) {
                conditions.push(guard);
            }
        }
        conditions
            .into_iter()
            .map(|condition| PythonSolutionCondition { condition })
            .collect()
    }
    /// The allowed domain of this branch's unknowns.
    #[getter]
    fn domain(&self) -> PythonSolveDomain {
        self.solution.domain().into()
    }
    /// Return whether this branch has additional validity conditions.
    fn is_conditional(&self) -> bool {
        self.solution.is_conditional() || !self.coverage_guard.is_empty()
    }
    /// Return whether all unknowns have assigned expressions, possibly subject to conditions.
    fn is_point(&self) -> bool {
        self.solution.free_variables().is_empty()
    }
    /// Return the number of independent coordinates in this branch, or None if unknown.
    fn dimension(&self) -> Option<usize> {
        self.solution.dimension()
    }
    /// Return the number of unknowns minus the dimension, or None if unknown.
    fn codimension(&self) -> Option<usize> {
        self.solution.codimension()
    }
    /// Return the assigned variables in coordinate order; free variables are omitted.
    fn keys(&self) -> Vec<PythonExpression> {
        self.solution
            .iter()
            .map(|(v, _)| v.to_atom().into())
            .collect()
    }
    /// Return the assigned Expressions in the same order as ``keys()``.
    fn values(&self) -> Vec<PythonExpression> {
        self.items().into_iter().map(|(_, v)| v).collect()
    }
    /// Return (variable, Expression) pairs, omitting free variables.
    fn items(&self) -> Vec<(PythonExpression, PythonExpression)> {
        self.solution
            .iter()
            .map(|(v, a)| (v.to_atom().into(), a.clone().into()))
            .collect()
    }
    /// Return an assigned Expression, or None for a free or absent variable.
    ///
    /// Parameters
    /// ----------
    /// variable: Expression
    ///     Variable whose assignment to retrieve. ``branch[variable]`` raises
    ///     KeyError when the variable is free or absent.
    fn get(&self, variable: &PythonExpression) -> PyResult<Option<PythonExpression>> {
        let variable = PolyVariable::try_from(variable.expr.clone())
            .map_err(exceptions::PyTypeError::new_err)?;
        Ok(self.solution.get(&variable).cloned().map(Into::into))
    }
    /// Retrieve an assigned Expression; raise KeyError for a free or absent variable.
    ///
    /// Parameters
    /// ----------
    /// variable: Expression
    ///     Variable whose assignment to retrieve.
    fn __getitem__(&self, variable: &PythonExpression) -> PyResult<PythonExpression> {
        self.get(variable)?
            .ok_or_else(|| exceptions::PyKeyError::new_err(variable.expr.to_string()))
    }
    /// Check whether a variable has an assignment in this branch.
    ///
    /// Parameters
    /// ----------
    /// variable: Expression
    ///     Variable to look up; free variables are not mapping keys.
    fn __contains__(&self, variable: &PythonExpression) -> PyResult<bool> {
        Ok(self.get(variable)?.is_some())
    }
    /// Count assignments, excluding free variables.
    fn __len__(&self) -> usize {
        self.solution.len()
    }
    #[gen_stub(override_return_type(type_repr = "typing.Iterator[Expression]"))]
    fn __iter__<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyIterator>> {
        self.keys().into_pyobject(py)?.try_iter()
    }
    fn __repr__(&self) -> String {
        format!("Solution({})", self.__str__())
    }
    fn __str__(&self) -> String {
        self.text_with(&ToString::to_string)
    }
    fn _repr_html_(&self) -> PyResult<String> {
        let conditions = self
            .conditions()
            .into_iter()
            .map(|c| c.condition)
            .collect::<Vec<_>>();
        solution_html(&self.solution, &conditions, None)
    }
    /// Display the assignments in IPython.
    ///
    /// Parameters
    /// ----------
    /// pretty: object
    ///     IPython's pretty printer.
    /// cycle: bool
    ///     Whether this object is already being displayed.
    fn _repr_pretty_(&self, pretty: &Bound<'_, PyAny>, cycle: bool) -> PyResult<()> {
        pretty.call_method1(
            "text",
            (if cycle {
                "Solution(...)".into()
            } else {
                self.text_with(&pretty_atom)
            },),
        )?;
        Ok(())
    }
}
/// Exact solutions returned by ``Expression.solve``.
///
/// Iterate or index this set to get Solution branches. Each branch describes
/// an alternative: a point, or a family of points with free variables.
/// ``len(result)`` counts branches, so a set of length one can still contain
/// infinitely many points. Branch order is not guaranteed.
///
/// For a generic result, the assignments apply where ``coverage_guard`` is true.
/// Solve again after substituting parameter values outside that guard.
/// Use ``dict(result[i])`` or ``result[i].as_dict()`` to extract assignments.
/// Use ``branch.free_variables()`` and ``branch.conditions()`` to inspect a
/// family's free coordinates and validity restrictions.
///
/// Printing a set shows each branch's assignments and restrictions; notebooks
/// display them as aligned equations. A branch with an empty mapping describes
/// a family in which all requested variables are free.
///
/// Examples
/// --------
/// >>> from symbolica import Expression, S, Reals
/// >>> x = S("x")
/// >>> result = Expression.solve(x.eq(2), [x], domain=Reals)
/// >>> print(result)
/// [0] {x = 2}
/// >>> dict(result[0]) == {x: 2}
/// True
/// >>> bool(Expression.solve(x**2 + 1, [x], domain=Reals))
/// False
#[cfg_attr(feature = "python_stubgen", gen_stub_pyclass)]
#[pyclass(
    frozen,
    skip_from_py_object,
    name = "SolutionSet",
    module = "symbolica.core"
)]
#[derive(Clone)]
pub struct PythonSolutionSet {
    pub(super) set: SolutionSet,
}
impl PythonSolutionSet {
    fn text_with(&self, atom: &impl Fn(&Atom) -> String) -> String {
        let mut lines = Vec::new();
        if self.set.len() == 0 {
            lines.push(if self.set.coverage() == SolveCoverage::Complete {
                "No solutions.".into()
            } else {
                "No branches represented; emptiness is not established.".into()
            });
        } else {
            lines.extend(
                self.set.iter().enumerate().map(|(index, solution)| {
                    format!("[{}] {}", index, solution_text(solution, atom))
                }),
            );
        }
        lines.extend(self.display_context(&|guard| guard_text(guard, atom)));
        lines.join("\n")
    }
    fn display_context(&self, format_formula: &impl Fn(&[Atom]) -> String) -> Vec<String> {
        let mut context = Vec::new();
        if !self.set.coverage_guard().is_empty() {
            context.push(format!(
                "For {}; other parameter values are not covered.",
                format_formula(self.set.coverage_guard())
            ));
        }
        context
    }
}
#[cfg_attr(feature = "python_stubgen", gen_stub_pymethods)]
#[cfg_attr(not(feature = "python_stubgen"), remove_gen_stub)]
#[pymethods]
impl PythonSolutionSet {
    /// The unknowns requested in the solve, in the original input order.
    #[getter]
    fn variables(&self) -> Vec<PythonExpression> {
        self.set
            .variables()
            .iter()
            .map(|v| v.to_atom().into())
            .collect()
    }
    /// Symbols treated as fixed parameters during the solve.
    #[getter]
    fn parameters(&self) -> Vec<PythonExpression> {
        self.set
            .parameters()
            .iter()
            .map(|v| v.to_atom().into())
            .collect()
    }
    /// The solve domain, also used as the default domain of external parameters.
    #[getter]
    fn domain(&self) -> PythonSolveDomain {
        self.set.domain().into()
    }
    /// Whether the represented solutions are complete or generic.
    #[getter]
    fn coverage(&self) -> &'static str {
        match self.set.coverage() {
            SolveCoverage::Complete => "complete",
            SolveCoverage::Generic => "generic",
        }
    }
    /// The condition under which the coverage claim applies.
    #[getter]
    fn coverage_guard(&self) -> PythonCondition {
        guard_condition(self.set.coverage_guard()).into()
    }
    /// Return the largest branch dimension for fixed external parameter values.
    ///
    /// A finite nonempty collection of points has dimension zero; a free line
    /// has dimension one. Returns -1 for a complete empty set, or None if unknown.
    fn dimension(&self) -> Option<isize> {
        self.set.dimension()
    }
    /// Return whether there are no solutions.
    ///
    /// Raises IncompleteCoverage if completeness is not established or emptiness
    /// depends on unresolved branch conditions. ``bool(result)`` is the opposite
    /// of this check; use ``len(result)`` to count represented branches.
    fn is_empty(&self) -> PyResult<bool> {
        self.set.is_empty().map_err(solve_error)
    }
    fn __len__(&self) -> usize {
        self.set.len()
    }
    fn __bool__(&self) -> PyResult<bool> {
        self.is_empty().map(|v| !v)
    }
    fn __getitem__(&self, index: isize) -> PyResult<PythonSolution> {
        let index = if index < 0 {
            self.set.len() as isize + index
        } else {
            index
        };
        usize::try_from(index)
            .ok()
            .and_then(|i| self.set.get(i))
            .cloned()
            .map(|solution| PythonSolution::from_set(solution, &self.set))
            .ok_or_else(|| PyIndexError::new_err("Solution branch index out of range"))
    }
    #[gen_stub(override_return_type(type_repr = "typing.Iterator[Solution]"))]
    fn __iter__<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyIterator>> {
        self.set
            .iter()
            .cloned()
            .map(|solution| PythonSolution::from_set(solution, &self.set))
            .collect::<Vec<_>>()
            .into_pyobject(py)?
            .try_iter()
    }
    fn __repr__(&self) -> String {
        self.__str__()
    }
    fn __str__(&self) -> String {
        self.text_with(&ToString::to_string)
    }
    /// Display all solution branches as aligned equations.
    fn _repr_html_(&self) -> PyResult<String> {
        let mut html = String::from("<div>");
        if self.set.len() == 0 {
            html.push_str(if self.set.coverage() == SolveCoverage::Complete {
                "<div>No solutions.</div>"
            } else {
                "<div>No branches represented; emptiness is not established.</div>"
            });
        } else {
            html.push_str("<div style=\"display: flex; flex-direction: column; gap: 0.65em; margin: 0.25em 0\">");
            for (index, solution) in self.set.iter().enumerate() {
                html.push_str(&solution_html(
                    solution,
                    solution.conditions(),
                    Some(index),
                )?);
            }
            html.push_str("</div>");
        }
        for context in self.display_context(&guard_html) {
            html.push_str(&format!("<div><small>{}</small></div>", context));
        }
        html.push_str("</div>");
        Ok(html)
    }
    /// Display all solution branches in IPython.
    ///
    /// Parameters
    /// ----------
    /// pretty: object
    ///     IPython's pretty printer.
    /// cycle: bool
    ///     Whether this object is already being displayed.
    fn _repr_pretty_(&self, pretty: &Bound<'_, PyAny>, cycle: bool) -> PyResult<()> {
        pretty.call_method1(
            "text",
            (if cycle {
                "SolutionSet(...)".into()
            } else {
                self.text_with(&pretty_atom)
            },),
        )?;
        Ok(())
    }
}