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
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
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
//! Exact algebraic solution sets.
//!
//! [`AtomCore::solve`] accepts expressions equal to zero. Select the domain
//! with [`SolveBuilder::over`] and the unknowns with [`SolveBuilder::wrt`].
//! The resulting [`SolutionSet`] contains branches with expression assignments,
//! free variables and validity conditions.
//! For numerical roots, see [`AtomCore::nsolve`] and [`AtomCore::nsolve_system`].

use std::{ops::Neg, sync::Arc};

use ahash::{HashMap, HashSet};
use numerica::domains::{
    Field, RealEmbedding, Ring, RingOps,
    float::{Complex, Float, RealLike},
    rational::Rational,
};

use crate::{
    atom::{Atom, AtomCore, AtomView, Indeterminate},
    coefficient::{Coefficient, ConvertToRing},
    domains::{
        InternalOrdering, SelfRing,
        algebraic::AlgebraicContext,
        float::{FloatField, Real, SingleFloat},
        integer::Z,
        rational::Q,
        rational_polynomial::{RationalPolynomial, RationalPolynomialField},
    },
    evaluate::{EvaluationDomain, FunctionMap, OptimizationSettings},
    id::ConditionResult,
    poly::{
        GrevLexOrder, LexOrder, PolyVariable, PositiveExponent, groebner::GroebnerBasis,
        polynomial::MultivariatePolynomial,
    },
    tensors::matrix::{Matrix, MatrixError},
};

#[derive(Clone)]
struct AuxiliaryPower {
    variable: PolyVariable,
    base: Atom,
    exponent: Atom,
    denominator: usize,
}

enum ParametricSolveResult {
    Solved(Vec<SolveBranch>),
    PositiveDimensional(usize),
    Inconsistent,
}

#[derive(Clone)]
pub(crate) struct SolveBranch {
    values: HashMap<PolyVariable, Atom>,
    nonzero_conditions: Vec<Atom>,
}

impl SolveBranch {
    fn unconditional(values: HashMap<PolyVariable, Atom>) -> Self {
        Self {
            values,
            nonzero_conditions: Vec::new(),
        }
    }
}

/// Errors from exact equation solving and numerical root finding.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SolveError {
    /// The equations require a solving method that is unavailable.
    UnsupportedProblem(String),
    /// The requested conclusion depends on unresolved conditions or parameter cases.
    IncompleteCoverage(String),
    /// The equations or requested variables are invalid.
    InvalidInput(String),
    /// The result cannot be extracted as a single unconditional point.
    NotPoint,
    /// The equations are inconsistent.
    Inconsistent,
    /// The system contains complex coefficients, but the solver works over the reals.
    ComplexCoefficients,
    /// The number of equations differs from the number of unknowns.
    NonSquareSystem,
    /// Initial values were not provided for all unknowns.
    IncompleteInitialValues,
    /// Newton's method encountered a zero derivative.
    ZeroDerivative,
    /// Newton's method could not invert the Jacobian.
    SingularJacobian,
    /// The solver did not converge within the iteration limit.
    NoConvergence,
    /// The input system is empty.
    EmptySystem,
    /// The input system is not linear in the requested variables.
    NonLinearSystem,
    /// The system was underdetermined. The partial solution is returned.
    Underdetermined {
        /// Rank of the system.
        rank: u32,
        /// Partial solution found, that may contain free variables.
        partial_solution: Vec<Atom>,
    },
    /// A failure described by a message that does not fit a more specific variant.
    Other(String),
}

/// The values that an exact solve result is allowed to contain.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SolveDomain {
    /// Keep solutions whose requested values are integers.
    Integers,
    /// Keep solutions whose requested values are rational numbers.
    Rationals,
    /// Keep solutions whose requested values are real numbers.
    Reals,
    /// Keep all complex solutions.
    #[default]
    Complexes,
}

pub use SolveDomain::{Complexes, Integers, Rationals, Reals};

mod solution_set;
pub use solution_set::*;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum DomainMembership {
    Yes,
    No,
    Indeterminate,
}

fn algebraic_domain_membership(value: &Atom, domain: SolveDomain) -> DomainMembership {
    let Ok(mut context) = AlgebraicContext::from_atom(value.as_view()) else {
        return DomainMembership::Indeterminate;
    };
    let Ok(element) = context.convert_atom(value.as_view()) else {
        return DomainMembership::Indeterminate;
    };

    match domain {
        Integers => {
            if context
                .field()
                .element_to_atom_simplified(&element)
                .is_integer()
                .is_true()
            {
                DomainMembership::Yes
            } else {
                DomainMembership::No
            }
        }
        Rationals => {
            let simplified = context.field().element_to_atom_simplified(&element);
            if Rational::try_from(simplified.as_view()).is_ok() {
                DomainMembership::Yes
            } else {
                DomainMembership::No
            }
        }
        Reals if context.field().try_sign(&element).is_ok() => DomainMembership::Yes,
        Reals => DomainMembership::No,
        Complexes => DomainMembership::Yes,
    }
}

pub(crate) fn value_in_domain(value: &Atom, domain: SolveDomain) -> DomainMembership {
    let membership = match domain {
        Complexes => ConditionResult::True,
        Integers => value.is_integer(),
        Rationals if Rational::try_from(value.as_view()).is_ok() => ConditionResult::True,
        Rationals => ConditionResult::Inconclusive,
        Reals => value.is_real(),
    };
    match membership {
        ConditionResult::True => DomainMembership::Yes,
        ConditionResult::False => DomainMembership::No,
        ConditionResult::Inconclusive => algebraic_domain_membership(value, domain),
    }
}

pub(crate) fn rational_denominator<E: PositiveExponent + 'static>(
    expression: AtomView<'_>,
) -> Option<Atom> {
    // Preserve poles from the received expression before polynomial gcd
    // cancellation removes them (e.g. (x^2-2*x+1)/(x-1)).
    let mut bases = Vec::new();
    expression.visitor(&mut |atom| {
        if let AtomView::Pow(power) = atom {
            let (base, exponent) = power.get_base_exp();
            if Rational::try_from(exponent).is_ok_and(|e| e < Rational::from(0)) {
                let base = base.to_owned();
                if !bases.contains(&base) {
                    bases.push(base);
                }
            }
        }
        true
    });
    if !bases.is_empty() {
        return Some(bases.into_iter().fold(Atom::num(1), |a, b| a * b));
    }
    let rational: RationalPolynomial<_, E> =
        expression.try_to_rational_polynomial(&Q, &Z, None).ok()?;
    (!rational.denominator.is_one()).then(|| rational.denominator.to_expression())
}

impl std::error::Error for SolveError {}

impl From<String> for SolveError {
    fn from(value: String) -> Self {
        SolveError::Other(value)
    }
}

impl From<&str> for SolveError {
    fn from(value: &str) -> Self {
        SolveError::Other(value.to_owned())
    }
}

impl std::fmt::Display for SolveError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SolveError::UnsupportedProblem(s) => write!(f, "Unsupported problem: {s}"),
            SolveError::IncompleteCoverage(s) => write!(f, "Complete coverage unavailable: {s}"),
            SolveError::InvalidInput(s) => write!(f, "Invalid solve input: {s}"),
            SolveError::NotPoint => f.write_str("Branch is not an unconditional point"),
            SolveError::Inconsistent => f.write_str("Inconsistent system"),
            SolveError::ComplexCoefficients => {
                f.write_str("Complex coefficients are not supported")
            }
            SolveError::NonSquareSystem => {
                f.write_str("System must have same number of equations as there are unknowns")
            }
            SolveError::IncompleteInitialValues => {
                f.write_str("Initial values must be provided for all unknowns")
            }
            SolveError::ZeroDerivative => f.write_str("Derivative is zero"),
            SolveError::SingularJacobian => f.write_str("Could not invert Jacobian"),
            SolveError::NoConvergence => f.write_str("Did not converge"),
            SolveError::EmptySystem => f.write_str("Empty system"),
            SolveError::NonLinearSystem => f.write_str("Not a linear system"),
            SolveError::Underdetermined {
                rank,
                partial_solution,
            } => write!(
                f,
                "Underdetermined system of rank {}/{}. Partial solution: {:?}",
                rank,
                partial_solution.len(),
                partial_solution
            ),
            SolveError::Other(e) => f.write_str(e),
        }
    }
}

impl AtomView<'_> {
    fn leading_ideal_dimension<E: PositiveExponent>(
        leading_monomials: &[Vec<E>],
        nvars: usize,
    ) -> usize {
        fn subsets_of_size(
            nvars: usize,
            size: usize,
            start: usize,
            current: &mut Vec<usize>,
            subsets: &mut Vec<Vec<usize>>,
        ) {
            if current.len() == size {
                subsets.push(current.clone());
                return;
            }

            let remaining = size - current.len();
            for variable in start..=nvars - remaining {
                current.push(variable);
                subsets_of_size(nvars, size, variable + 1, current, subsets);
                current.pop();
            }
        }

        for size in (0..=nvars).rev() {
            let mut subsets = Vec::new();
            subsets_of_size(nvars, size, 0, &mut Vec::new(), &mut subsets);
            if subsets.into_iter().any(|subset| {
                !leading_monomials.iter().any(|leading| {
                    leading.iter().enumerate().all(|(variable, exponent)| {
                        exponent.is_zero() || subset.contains(&variable)
                    })
                })
            }) {
                return size;
            }
        }

        0
    }

    fn preferred_input_sets(nvars: usize, dimension: usize) -> Vec<Vec<usize>> {
        fn collect(
            nvars: usize,
            dimension: usize,
            start: usize,
            current: &mut Vec<usize>,
            result: &mut Vec<Vec<usize>>,
        ) {
            if current.len() == dimension {
                result.push(current.clone());
                return;
            }

            let remaining = dimension - current.len();
            for variable in start..=nvars - remaining {
                current.push(variable);
                collect(nvars, dimension, variable + 1, current, result);
                current.pop();
            }
        }

        let mut result = Vec::new();
        collect(nvars, dimension, 0, &mut Vec::new(), &mut result);
        result.sort_by(|left, right| right.cmp(left));
        result
    }

    fn solve_parametric_polynomial_system<E: PositiveExponent + 'static, T: AtomCore>(
        system: &[T],
        variables: &[PolyVariable],
        input_variables: &HashSet<PolyVariable>,
        domain: SolveDomain,
    ) -> Result<ParametricSolveResult, SolveError> {
        let rationals = system
            .iter()
            .map(|expression| {
                expression
                    .as_atom_view()
                    .try_to_rational_polynomial(&Q, &Z, None)
                    .map_err(|error| SolveError::Other(error.to_string()))
            })
            .collect::<Result<Vec<RationalPolynomial<_, E>>, SolveError>>()?;

        let has_denominators = rationals
            .iter()
            .any(|rational| !rational.denominator.is_one());
        let mut polynomial_variables = variables
            .iter()
            .filter(|variable| !input_variables.contains(*variable))
            .cloned()
            .collect::<Vec<_>>();
        let saturation_variable = if has_denominators {
            let mut index = 0;
            let variable = loop {
                let candidate = PolyVariable::Temporary(index);
                if !variables.contains(&candidate) {
                    break candidate;
                }
                index += 1;
            };
            polynomial_variables.push(variable.clone());
            Some(variable)
        } else {
            None
        };
        let polynomial_variables = Arc::new(polynomial_variables);

        let mut denominators = Vec::new();
        let mut polynomials = Vec::new();
        for rational in rationals {
            let numerator_one = rational.numerator.one();
            let numerator = RationalPolynomial {
                numerator: rational.numerator,
                denominator: numerator_one,
            }
            .to_polynomial(polynomial_variables.as_ref(), true)
            .map_err(|error| SolveError::Other(error.to_string()))?;
            if !numerator.is_zero() {
                polynomials.push(numerator.reorder::<GrevLexOrder>());
            }

            if !rational.denominator.is_one() {
                let denominator_one = rational.denominator.one();
                let denominator = RationalPolynomial {
                    numerator: rational.denominator,
                    denominator: denominator_one,
                }
                .to_polynomial(polynomial_variables.as_ref(), true)
                .map_err(|error| SolveError::Other(error.to_string()))?;
                denominators.push(denominator);
            }
        }

        if let Some(saturation_variable) = saturation_variable {
            let mut denominator_product = denominators
                .first()
                .expect("A saturation variable requires a denominator")
                .one();
            for denominator in denominators {
                denominator_product = &denominator_product * &denominator;
            }
            let helper = denominator_product
                .variable(&saturation_variable)
                .map_err(SolveError::Other)?;
            let saturation = &helper * &denominator_product - denominator_product.one();
            polynomials.push(saturation.reorder::<GrevLexOrder>());
        }

        if polynomials.is_empty() {
            if polynomial_variables.is_empty() {
                return Ok(ParametricSolveResult::Solved(vec![
                    SolveBranch::unconditional(
                        variables
                            .iter()
                            .map(|variable| (variable.clone(), variable.to_atom()))
                            .collect(),
                    ),
                ]));
            }
            return Ok(ParametricSolveResult::PositiveDimensional(
                polynomial_variables.len(),
            ));
        }

        let basis = GroebnerBasis::new(&polynomials, false);
        if basis
            .system
            .iter()
            .any(|polynomial| !polynomial.is_zero() && polynomial.is_constant())
        {
            return Ok(ParametricSolveResult::Inconsistent);
        }

        let leading_monomials = basis
            .system
            .iter()
            .filter(|polynomial| !polynomial.is_zero())
            .map(|polynomial| polynomial.max_exp().to_vec())
            .collect::<Vec<_>>();
        let dimension =
            Self::leading_ideal_dimension(&leading_monomials, polynomial_variables.len());
        if dimension > 0 {
            return Ok(ParametricSolveResult::PositiveDimensional(dimension));
        }

        let basis = basis
            .change_order::<LexOrder>()
            .map_err(SolveError::Other)?;
        let solutions = basis
            .solve_parametric_in_base_field(matches!(domain, Integers | Rationals))
            .map_err(SolveError::Other)?
            .into_iter()
            .map(|solution| {
                let nonzero_conditions = solution
                    .field()
                    .generic_conditions()
                    .iter()
                    .map(|condition| condition.to_expression())
                    .collect();
                let values = variables
                    .iter()
                    .filter_map(|variable| {
                        if input_variables.contains(variable) {
                            Some((variable.clone(), variable.to_atom()))
                        } else {
                            solution
                                .get(variable)
                                .map(|value| (variable.clone(), value.to_atom()))
                        }
                    })
                    .collect();
                SolveBranch {
                    values,
                    nonzero_conditions,
                }
            })
            .collect();
        Ok(ParametricSolveResult::Solved(solutions))
    }

    fn solve_positive_dimensional_polynomial_system<E: PositiveExponent + 'static, T: AtomCore>(
        system: &[T],
        variables: &[PolyVariable],
        dimension: usize,
        domain: SolveDomain,
    ) -> Result<Vec<SolveBranch>, SolveError> {
        if dimension > variables.len() {
            return Err(SolveError::Other(format!(
                "The polynomial system has dimension {dimension}, but only {} solve variables",
                variables.len()
            )));
        }

        let maximize_base_field_branches = matches!(domain, Integers | Rationals);
        let mut best_solutions = None;
        for indices in Self::preferred_input_sets(variables.len(), dimension) {
            let input_variables = indices
                .into_iter()
                .map(|index| variables[index].clone())
                .collect::<HashSet<_>>();
            match Self::solve_parametric_polynomial_system::<E, _>(
                system,
                variables,
                &input_variables,
                domain,
            )? {
                ParametricSolveResult::Solved(solutions) => {
                    if !maximize_base_field_branches {
                        return Ok(solutions);
                    }
                    if best_solutions
                        .as_ref()
                        .is_none_or(|best: &Vec<_>| solutions.len() > best.len())
                    {
                        best_solutions = Some(solutions);
                    }
                }
                ParametricSolveResult::PositiveDimensional(_)
                | ParametricSolveResult::Inconsistent => {}
            }
        }

        if let Some(solutions) = best_solutions {
            return Ok(solutions);
        }

        Err(SolveError::Other(
            "Could not select input variables for the positive-dimensional polynomial system"
                .to_string(),
        ))
    }

    fn rational_exponent_parts(exponent: AtomView<'_>) -> Option<(i64, usize)> {
        let exponent = Rational::try_from(exponent).ok()?;
        let numerator = exponent.numerator().to_i64()?;
        let denominator = usize::try_from(exponent.denominator().to_i64()?).ok()?;
        Some((numerator, denominator))
    }

    fn collect_auxiliary_powers<T: AtomCore>(system: &[T]) -> Vec<AuxiliaryPower> {
        let mut seen = HashSet::default();
        let mut powers = Vec::new();

        for expression in system {
            expression.visitor(&mut |atom| {
                let AtomView::Pow(power) = atom else {
                    return true;
                };
                let (base, exponent) = power.get_base_exp();
                let Some((_, denominator)) = Self::rational_exponent_parts(exponent) else {
                    return true;
                };
                if denominator <= 1 {
                    return true;
                }

                // Use the primitive principal power base^(1/denominator) as
                // the auxiliary. Other powers, including negative ones, are
                // represented as integer powers of this generator by the
                // rational-polynomial converter.
                let exponent = Atom::num(Rational::from((1, denominator as i64)));
                let power = base.pow(exponent.clone());
                if seen.insert(power.clone()) {
                    powers.push(AuxiliaryPower {
                        variable: PolyVariable::Power(power),
                        base: base.to_owned(),
                        exponent,
                        denominator,
                    });
                }
                true
            });
        }

        powers
    }

    fn substitute_algebraic_solution(
        expression: AtomView<'_>,
        solution: &HashMap<PolyVariable, Atom>,
    ) -> Atom {
        let replacements = solution
            .iter()
            .filter_map(|(variable, value)| {
                (!matches!(variable, PolyVariable::Temporary(_)))
                    .then(|| (variable.to_atom(), value))
            })
            .collect::<Vec<_>>();

        expression.replace_map_bottom_up(
            |atom, _, out| {
                if let Some((_, value)) = replacements
                    .iter()
                    .find(|(variable, _)| variable.as_view() == atom)
                {
                    **out = (*value).clone();
                }
            },
            true,
        )
    }

    fn numerically_zero(expression: &Atom) -> Result<bool, String> {
        let norm = |decimal_precision| -> Result<f64, String> {
            let approximation = expression.to_float(decimal_precision);
            let value = Complex::<Float>::try_from(approximation.as_view())
                .map_err(|error| error.to_string())?;
            Ok(value.norm().re.to_f64().abs())
        };

        let low_precision = norm(48)?;
        let high_precision = norm(96)?;
        if high_precision == 0.0 {
            return Ok(low_precision == 0.0);
        }

        Ok(high_precision < 1e-40 && low_precision > 0.0 && high_precision < low_precision * 1e-12)
    }

    fn algebraically_zero(expression: &Atom) -> Option<bool> {
        let expression = expression.expand();
        if expression.is_zero() {
            return Some(true);
        }

        if let Ok(value) = Rational::try_from(expression.as_view()) {
            return Some(value.is_zero());
        }

        if let Ok(mut context) = AlgebraicContext::from_atom(expression.as_view())
            && let Ok(value) = context.convert_atom(expression.as_view())
        {
            return Some(context.field().is_zero(&value));
        }

        None
    }

    fn auxiliary_branch_matches(
        auxiliary: &AuxiliaryPower,
        solution: &HashMap<PolyVariable, Atom>,
        context: &mut AlgebraicContext,
        require_complete: bool,
    ) -> Result<bool, String> {
        let candidate = solution.get(&auxiliary.variable).ok_or_else(|| {
            format!(
                "The Gröbner solution is missing auxiliary variable {}",
                auxiliary.variable
            )
        })?;

        // The polynomial solver has already put the auxiliary and all solved
        // variables in one algebraic field. For a positive real base, select
        // the principal branch there: it is the unique positive real d-th
        // root. This avoids rebuilding a compositum from the printed root
        // expressions merely to rediscover an element already in the field.
        let auxiliary_atom = auxiliary.variable.to_atom();
        if let (Ok(candidate_value), Ok(base_value)) = (
            context.convert_atom(auxiliary_atom.as_view()),
            context.convert_atom(auxiliary.base.as_view()),
        ) {
            let field = context.field();
            let relation = field.sub(
                &field.pow(&candidate_value, auxiliary.denominator as u64),
                &base_value,
            );
            if !field.is_zero(&relation) {
                return Ok(false);
            }
            if field.is_zero(&base_value) {
                return Ok(field.is_zero(&candidate_value));
            }
            if field.is_positive_real(&base_value).unwrap_or(false) {
                // For d <= 4 the principal positive root is the only d-th
                // root with positive real part. Checking that part directly
                // avoids computing a second minimal polynomial when the
                // primitive generator of the solution field is complex.
                if auxiliary.denominator <= 4 {
                    return field.has_positive_real_part(&candidate_value);
                }
                return field.is_positive_real(&candidate_value);
            }
        }

        let base = Self::substitute_algebraic_solution(auxiliary.base.as_view(), solution);
        let expected = base.pow(auxiliary.exponent.clone());
        let difference = (candidate.clone() - expected.clone()).expand();
        if let Some(is_zero) = Self::algebraically_zero(&difference) {
            return Ok(is_zero);
        }

        if require_complete {
            return Err(
                "Principal algebraic branch selection could not be certified exactly".into(),
            );
        }
        Self::numerically_zero(&difference)
    }

    /// Solve a system exactly for `vars`.
    ///
    /// Linear systems use a dedicated exact fast path. Polynomial nonlinear
    /// systems over `Q` or `Q(parameters)` are first converted to a
    /// grevlex Gröbner basis, changed to lex order with FGLM, and solved by
    /// triangular back-substitution. For a positive-dimensional nonlinear
    /// system, a maximal set of requested variables is treated as input
    /// parameters and mapped to itself. As in the linear solver, viable input
    /// sets containing variables later in `vars` are preferred. Rational powers
    /// such as `sqrt(x+3)` are replaced by auxiliary polynomial variables and
    /// defining equations; solutions on non-principal power branches are
    /// removed afterwards.
    /// Denominators involving solve variables are cleared before constructing
    /// the basis, and solutions on their zero loci are rejected.
    /// Rational-power auxiliaries combined with parameters are not yet
    /// supported because selecting their analytic branch requires assumptions
    /// on the parameters. Parametric results describe the generic parameter
    /// locus. This also applies to automatically selected input variables in a
    /// positive-dimensional result: exceptional input values where
    /// denominators vanish or the Gröbner basis changes must be solved
    /// separately.
    ///
    /// Every expression in `system` is understood to equal zero. Each internal
    /// branch retains its exact values and generic nonvanishing conditions.
    #[cfg(test)]
    pub(crate) fn solve_impl<E: PositiveExponent + 'static, T1: AtomCore, T2: AtomCore>(
        system: &[T1],
        vars: &[T2],
        domain: SolveDomain,
    ) -> Result<Vec<SolveBranch>, SolveError> {
        Self::solve_impl_with_coverage::<E, _, _>(system, vars, domain, false)
    }

    fn solve_impl_with_coverage<E: PositiveExponent + 'static, T1: AtomCore, T2: AtomCore>(
        system: &[T1],
        vars: &[T2],
        domain: SolveDomain,
        require_complete: bool,
    ) -> Result<Vec<SolveBranch>, SolveError> {
        let variables = vars
            .iter()
            .map(|variable| variable.as_atom_view().to_owned().try_into())
            .collect::<Result<Vec<PolyVariable>, String>>()
            .map_err(SolveError::Other)?;

        let auxiliaries = Self::collect_auxiliary_powers(system);
        if auxiliaries.is_empty() {
            match Self::solve_linear_system::<E, _, _>(system, vars) {
                Ok(values) => {
                    return Ok(vec![SolveBranch::unconditional(
                        variables.into_iter().zip(values).collect(),
                    )]);
                }
                Err(SolveError::NonLinearSystem) => {}
                Err(SolveError::Other(error)) if error == "Not a polynomial" => {}
                Err(error) => return Err(error),
            }
        }

        let mut augmented_variables = variables.clone();
        for auxiliary in &auxiliaries {
            if !augmented_variables.contains(&auxiliary.variable) {
                augmented_variables.push(auxiliary.variable.clone());
            }
        }
        let variable_map = Arc::new(augmented_variables);

        let system_views = system
            .iter()
            .map(|expression| expression.as_atom_view())
            .collect::<Vec<_>>();
        let parameters = Self::get_parameters(&system_views, &variables);
        if !parameters.is_empty() {
            if !auxiliaries.is_empty() {
                return Err(SolveError::Other(
                    "Parametric solving with rational-power auxiliary variables is not supported"
                        .to_string(),
                ));
            }

            return match Self::solve_parametric_polynomial_system::<E, _>(
                system,
                &variables,
                &HashSet::default(),
                domain,
            )? {
                ParametricSolveResult::Solved(solutions) => Ok(solutions),
                ParametricSolveResult::PositiveDimensional(dimension) => {
                    Self::solve_positive_dimensional_polynomial_system::<E, _>(
                        system, &variables, dimension, domain,
                    )
                }
                ParametricSolveResult::Inconsistent => Ok(Vec::new()),
            };
        }

        let mut denominators = Vec::new();
        let mut polynomials = system
            .iter()
            .map(|expression| {
                let rational: RationalPolynomial<_, E> = expression
                    .as_atom_view()
                    .try_to_rational_polynomial_preserve_power_variables(
                        &Q,
                        &Z,
                        Some(variable_map.clone()),
                    )
                    .map_err(|error| SolveError::Other(error.to_string()))?;
                let numerator = rational
                    .numerator
                    .map_coeff(|coefficient| coefficient.into(), Q);
                let denominator = rational
                    .denominator
                    .map_coeff(|coefficient| coefficient.into(), Q);
                if !denominator.is_one() {
                    denominators.push(denominator);
                }
                Ok(numerator.reorder::<GrevLexOrder>())
            })
            .collect::<Result<Vec<MultivariatePolynomial<_, E, GrevLexOrder>>, SolveError>>()?
            .into_iter()
            .filter(|polynomial| !polynomial.is_zero())
            .collect::<Vec<_>>();
        if !auxiliaries.is_empty() {
            let prototype = MultivariatePolynomial::<_, E>::new(&Q, None, variable_map.clone());
            for auxiliary in &auxiliaries {
                let helper = prototype
                    .variable(&auxiliary.variable)
                    .map_err(SolveError::Other)?;
                let base: RationalPolynomial<_, E> = auxiliary
                    .base
                    .as_view()
                    .try_to_rational_polynomial_preserve_power_variables(
                        &Q,
                        &Z,
                        Some(variable_map.clone()),
                    )
                    .map_err(|error| SolveError::Other(error.to_string()))?;
                let base_numerator = base
                    .numerator
                    .map_coeff(|coefficient| coefficient.into(), Q);
                let base_denominator = base
                    .denominator
                    .map_coeff(|coefficient| coefficient.into(), Q);
                let relation =
                    helper.pow(auxiliary.denominator) * &base_denominator - base_numerator;
                if !base_denominator.is_one() {
                    denominators.push(base_denominator);
                }
                polynomials.push(relation.reorder::<GrevLexOrder>());
            }
        }
        let basis = GroebnerBasis::new(&polynomials, false);
        let basis =
            match basis.change_order::<LexOrder>() {
                Ok(basis) => basis,
                Err(_) if require_complete => return Err(SolveError::IncompleteCoverage(
                    "Nonlinear positive-dimensional coverage requires a complete family backend"
                        .into(),
                )),
                Err(_) if auxiliaries.is_empty() => {
                    return match Self::solve_parametric_polynomial_system::<E, _>(
                        system,
                        &variables,
                        &HashSet::default(),
                        domain,
                    )? {
                        ParametricSolveResult::Solved(solutions) => Ok(solutions),
                        ParametricSolveResult::PositiveDimensional(dimension) => {
                            Self::solve_positive_dimensional_polynomial_system::<E, _>(
                                system, &variables, dimension, domain,
                            )
                        }
                        ParametricSolveResult::Inconsistent => Ok(Vec::new()),
                    };
                }
                Err(error) => return Err(SolveError::Other(error)),
            };
        let polynomial_solutions = basis
            .solve_in_base_field(auxiliaries.is_empty() && matches!(domain, Integers | Rationals))
            .map_err(SolveError::Other)?;

        if auxiliaries.is_empty() && denominators.is_empty() {
            return polynomial_solutions
                .iter()
                .map(|solution| {
                    solution
                        .to_atom_map()
                        .map(SolveBranch::unconditional)
                        .map_err(SolveError::Other)
                })
                .collect();
        }

        let mut filtered = Vec::new();
        'solutions: for polynomial_solution in polynomial_solutions {
            let solution = polynomial_solution
                .to_atom_map()
                .map_err(SolveError::Other)?;
            let mut context = AlgebraicContext::new(polynomial_solution.field().clone());
            for (variable, value) in polynomial_solution.values() {
                context.insert_image(variable.to_atom(), value.clone());
                if let Some(atom) = solution.get(variable) {
                    context.insert_image(atom.clone(), value.clone());
                }
            }

            for denominator in &denominators {
                let denominator = denominator.to_expression();
                let is_zero = context
                    .convert_atom(denominator.as_view())
                    .ok()
                    .map(|value| context.field().is_zero(&value))
                    .or_else(|| {
                        let denominator =
                            Self::substitute_algebraic_solution(denominator.as_view(), &solution);
                        Self::algebraically_zero(&denominator)
                    });
                match is_zero {
                    Some(true) => continue 'solutions,
                    Some(false) => {}
                    None => {
                        return Err(SolveError::Other(format!(
                            "Could not determine whether denominator {denominator} is zero"
                        )));
                    }
                }
            }

            for auxiliary in &auxiliaries {
                if !Self::auxiliary_branch_matches(
                    auxiliary,
                    &solution,
                    &mut context,
                    require_complete,
                )
                .map_err(|e| {
                    if require_complete {
                        SolveError::IncompleteCoverage(e)
                    } else {
                        SolveError::Other(e)
                    }
                })? {
                    continue 'solutions;
                }
            }

            filtered.push(SolveBranch::unconditional(
                variables
                    .iter()
                    .filter_map(|variable| {
                        solution
                            .get(variable)
                            .cloned()
                            .map(|value| (variable.clone(), value))
                    })
                    .collect(),
            ));
        }

        Ok(filtered)
    }

    /// Find the root of a function in `x` numerically over the reals using Newton's method.
    pub(crate) fn nsolve<N: SingleFloat + Real + EvaluationDomain + PartialOrd>(
        &self,
        x: &Indeterminate,
        init: N,
        prec: N,
        max_iterations: usize,
    ) -> Result<N, SolveError> {
        if self.has_complex_coefficients() {
            return Err(SolveError::ComplexCoefficients);
        }

        let v: Atom = x.clone().into();
        let f = self
            .evaluator(std::slice::from_ref(&v))
            .build()
            .map_err(|e| SolveError::Other(e.to_string()))?;
        let df = self
            .derivative(x)
            .evaluator(std::slice::from_ref(&v))
            .build()
            .map_err(|e| SolveError::Other(e.to_string()))?;

        let mut f_e = f.map_coeff(&|x| init.from_rational(x.to_real().unwrap()));
        let mut df_e = df.map_coeff(&|x| init.from_rational(x.to_real().unwrap()));

        let mut cur = init.clone();

        for _ in 0..max_iterations {
            let df_val = df_e.evaluate_single(std::slice::from_ref(&cur));
            let f_val = f_e.evaluate_single(std::slice::from_ref(&cur));

            if !df_val.is_finite() || df_val.is_zero() {
                return Err(SolveError::ZeroDerivative);
            }

            cur -= f_val.clone() / df_val;
            if f_val.norm() < prec {
                return Ok(cur);
            }
        }

        Err(SolveError::NoConvergence)
    }

    /// Solve a non-linear system numerically over the reals using Newton's method.
    pub(crate) fn nsolve_system<
        N: SingleFloat
            + Real
            + EvaluationDomain
            + PartialOrd
            + InternalOrdering
            + Eq
            + std::hash::Hash,
        T: AtomCore,
    >(
        system: &[T],
        vars: &[Indeterminate],
        init: &[N],
        prec: N,
        max_iterations: usize,
    ) -> Result<Vec<N>, SolveError> {
        let system = system.iter().map(|v| v.as_atom_view()).collect::<Vec<_>>();
        AtomView::nsolve_system_impl(&system, vars, init, prec, max_iterations)
    }

    fn nsolve_system_impl<
        N: SingleFloat
            + Real
            + EvaluationDomain
            + PartialOrd
            + InternalOrdering
            + Eq
            + std::hash::Hash,
    >(
        system: &[AtomView],
        vars: &[Indeterminate],
        init: &[N],
        prec: N,
        max_iterations: usize,
    ) -> Result<Vec<N>, SolveError> {
        if system.len() != vars.len() {
            Err(SolveError::NonSquareSystem)?;
        }

        if vars.len() != init.len() {
            Err(SolveError::IncompleteInitialValues)?;
        }

        if system.is_empty() {
            return Ok(vec![]);
        }

        if system.iter().any(|a| a.has_complex_coefficients()) {
            return Err(SolveError::ComplexCoefficients);
        }

        if system.len() == 1 {
            return Ok(vec![system[0].nsolve(
                &vars[0],
                init[0].clone(),
                prec,
                max_iterations,
            )?]);
        }

        let avars = vars.iter().map(|v| v.clone().into()).collect::<Vec<_>>();

        let mut fs = system
            .iter()
            .map(|a| {
                Ok(a.to_evaluation_tree(&FunctionMap::new(), &avars)
                    .map_err(|e| SolveError::Other(e.to_string()))?
                    .optimize(&OptimizationSettings {
                        horner_iterations: 1,
                        n_cores: 0,
                        cpe_iterations: None,
                        hot_start: None,
                        abort_check: None,
                        verbose: false,
                        ..Default::default()
                    })
                    .map_coeff(&|x| init[0].from_rational(x.to_real().unwrap())))
            })
            .collect::<Result<Vec<_>, SolveError>>()?;

        let mut jacobian = Vec::with_capacity(vars.len() * system.len());
        for a in system {
            let mut row = Vec::with_capacity(vars.len());
            for v in vars {
                let deriv = a.derivative(v);

                let a = deriv
                    .evaluator(&avars)
                    .build()
                    .map_err(|e| SolveError::Other(e.to_string()))?
                    .map_coeff(&|x| init[0].from_rational(x.to_real().unwrap()));

                row.push(a);
            }
            jacobian.extend_from_slice(&row);
        }

        let field = FloatField::from_rep(init[0].clone());
        let mut cur = init.to_vec();

        for _ in 0..max_iterations {
            let f = fs
                .iter_mut()
                .map(|a| a.evaluate_single(&cur))
                .collect::<Vec<_>>();
            let f = Matrix::new_vec(f, field.clone());

            let df = jacobian
                .iter_mut()
                .map(|a| a.evaluate_single(&cur))
                .collect::<Vec<_>>();

            let df = Matrix::from_linear(df, system.len() as u32, vars.len() as u32, field.clone())
                .unwrap();

            let Ok(i) = df.inv() else {
                return Err(SolveError::SingularJacobian);
            };

            let mut ci = Matrix::new_vec(cur.to_vec(), field.clone());

            ci -= &(&i * &f);

            cur = ci.into_vec();

            if f.into_iter().all(|x| x.norm() < prec) {
                return Ok(cur);
            }
        }

        Err(SolveError::NoConvergence)
    }

    /// Solve a system that is linear in `vars`, if possible.
    /// Each expression in `system` is understood to yield 0.
    fn solve_linear_system<E: PositiveExponent, T1: AtomCore, T2: AtomCore>(
        system: &[T1],
        vars: &[T2],
    ) -> Result<Vec<Atom>, SolveError> {
        let system: Vec<_> = system.iter().map(|v| v.as_atom_view()).collect();

        let vars: Vec<_> = vars
            .iter()
            .map(|v| v.as_atom_view().to_owned().try_into())
            .collect::<Result<Vec<_>, _>>()
            .map_err(SolveError::Other)?;

        AtomView::solve_linear_system_impl::<E>(&system, &vars)
    }

    /// Convert a system of linear equations to a matrix representation, returning the matrix
    /// and the right-hand side.
    pub(crate) fn system_to_matrix<E: PositiveExponent, T1: AtomCore, T2: AtomCore>(
        system: &[T1],
        vars: &[T2],
    ) -> Result<
        (
            Matrix<RationalPolynomialField<Z, E>>,
            Matrix<RationalPolynomialField<Z, E>>,
        ),
        SolveError,
    > {
        let system: Vec<_> = system.iter().map(|v| v.as_atom_view()).collect();

        let vars: Vec<_> = vars
            .iter()
            .map(|v| v.as_atom_view().to_owned().try_into())
            .collect::<Result<Vec<_>, _>>()?;
        let params = Self::get_parameters(&system, &vars);

        AtomView::system_to_matrix_impl::<E>(&system, &vars, params)
    }

    fn system_to_matrix_impl<E: PositiveExponent>(
        system: &[AtomView],
        vars: &[PolyVariable],
        params: HashSet<AtomView>,
    ) -> Result<
        (
            Matrix<RationalPolynomialField<Z, E>>,
            Matrix<RationalPolynomialField<Z, E>>,
        ),
        SolveError,
    > {
        let mut mat = Vec::with_capacity(system.len() * vars.len());
        let mut row = vec![RationalPolynomial::<_, E>::new(&Z, Arc::new(vec![])); vars.len()];
        let mut rhs = vec![RationalPolynomial::<_, E>::new(&Z, Arc::new(vec![])); system.len()];

        let params = Arc::new(
            params
                .iter()
                .map(|x| x.to_owned().try_into())
                .collect::<Result<Vec<_>, String>>()
                .map_err(SolveError::Other)?,
        );

        for (si, a) in system.iter().enumerate() {
            let rat: RationalPolynomial<Z, E> = a
                .try_to_rational_polynomial(&Q, &Z, None)
                .map_err(|e| SolveError::Other(e.to_string()))?;

            let poly = rat
                .to_polynomial(vars, true)
                .map_err(|e| SolveError::Other(e.to_owned()))?;

            for e in &mut row {
                *e = RationalPolynomial::<_, E>::new(&Z, params.clone());
            }

            // get linear coefficients
            'next_monomial: for e in poly.into_iter() {
                if e.exponents.iter().cloned().sum::<E>() > E::one() {
                    Err(SolveError::NonLinearSystem)?;
                }

                for (rv, p) in row.iter_mut().zip(e.exponents) {
                    if !p.is_zero() {
                        *rv = e.coefficient.clone();
                        continue 'next_monomial;
                    }
                }

                // constant term
                rhs[si] = e.coefficient.clone().neg();
            }

            mat.extend_from_slice(&row);
        }

        let Some((first, rest)) = mat.split_first_mut() else {
            return Err(SolveError::EmptySystem);
        };

        for _ in 0..2 {
            for x in &mut *rest {
                first.unify_variables(x);
            }
            for x in &mut rhs {
                first.unify_variables(x);
            }
        }

        let field = RationalPolynomialField::new(Z);

        let m = Matrix::from_linear(mat, system.len() as u32, vars.len() as u32, field.clone())
            .unwrap();
        let b = Matrix::new_vec(rhs, field);

        Ok((m, b))
    }

    /// Get all parameters in the system that are not free variables.
    fn get_parameters<'a>(system: &[AtomView<'a>], vars: &[PolyVariable]) -> HashSet<AtomView<'a>> {
        let mut all_params = HashSet::default();
        for s in system {
            all_params.extend(s.get_all_indeterminates(false));
        }

        let v: Vec<_> = vars.iter().map(|x| x.to_atom()).collect();
        let mut all_vars = HashSet::default();
        for x in &v {
            all_vars.insert(x.as_view());
        }

        all_params
            .into_iter()
            .filter(|x| !all_vars.contains(x))
            .collect()
    }

    fn solve_linear_system_without_parameters<T: Field + ConvertToRing>(
        system: &[AtomView],
        vars: &[PolyVariable],
        field: T,
    ) -> Result<Vec<Atom>, SolveError>
    where
        T::Element: Into<Coefficient>,
    {
        let mut mat = vec![field.zero(); system.len() * vars.len()];
        let mut rhs = vec![field.zero(); system.len()];

        let vars = Arc::new(vars.to_vec());
        for (row, s) in system.iter().enumerate() {
            let poly = s
                .try_to_polynomial::<_, u8>(&field, Some(vars.clone()))
                .map_err(|e| SolveError::Other(e.to_string()))?;

            // Conversion may introduce indeterminates for nonpolynomial terms
            // such as 1/x. They cannot be ignored when constructing the linear
            // matrix: doing so turns 1/x-2=0 into the contradiction -2=0.
            if poly.variables().as_ref() != vars.as_ref() {
                return Err(SolveError::NonLinearSystem);
            }

            for e in &poly {
                if e.exponents.iter().copied().sum::<u8>() > 1 {
                    return Err(SolveError::NonLinearSystem);
                }

                let mut found = false;
                for j in 0..vars.len() {
                    if e.exponents[j] != 0 {
                        if found {
                            return Err(SolveError::Other("Not a linear system".to_owned()));
                        }
                        mat[row * vars.len() + j] = e.coefficient.clone();
                        found = true;
                    }
                }

                if !found {
                    rhs[row] = field.neg(e.coefficient);
                }
            }
        }

        let m = Matrix::from_linear(mat, system.len() as u32, vars.len() as u32, field.clone())
            .map_err(SolveError::Other)?;
        let rhs = Matrix::new_vec(rhs, field.clone());

        match m.solve(&rhs) {
            Ok(sol) => Ok(sol.into_vec().into_iter().map(Atom::num).collect()),
            Err(MatrixError::Underdetermined {
                rank,
                row_reduced_augmented_matrix,
            }) => {
                let mut sols = Vec::with_capacity(vars.len());

                let mut var_index = 0;
                for r in row_reduced_augmented_matrix.row_iter() {
                    while var_index < vars.len() as u32 && field.is_zero(&r[var_index as usize]) {
                        sols.push(vars[var_index as usize].to_atom());
                        var_index += 1;
                    }

                    if var_index >= vars.len() as u32 {
                        break;
                    }

                    if field.is_one(&r[var_index as usize]) {
                        let mut sol = Atom::num(r.last().unwrap().clone());

                        for (var, coeff) in vars.iter().zip(r).skip((var_index + 1) as usize) {
                            if !field.is_zero(coeff) {
                                sol -= Atom::num(coeff.clone()) * var.to_atom();
                            }
                        }

                        sols.push(sol);
                        var_index += 1;
                    }
                }

                for i in var_index as usize..vars.len() {
                    sols.push(vars[i].to_atom());
                }

                Err(SolveError::Underdetermined {
                    rank,
                    partial_solution: sols,
                })
            }
            Err(MatrixError::Inconsistent) => Err(SolveError::Inconsistent),
            Err(e) => Err(SolveError::Other(format!("Could not solve {e:?}"))),
        }
    }

    fn solve_linear_system_impl<E: PositiveExponent>(
        system: &[AtomView],
        vars: &[PolyVariable],
    ) -> Result<Vec<Atom>, SolveError> {
        let params = Self::get_parameters(system, vars);
        if params.is_empty() {
            if system.iter().any(|a| a.has_complex_coefficients()) {
                let f: FloatField<Complex<Rational>> = FloatField::from_rep(Complex::new_zero());
                return Self::solve_linear_system_without_parameters(system, vars, f);
            } else {
                return Self::solve_linear_system_without_parameters::<Q>(system, vars, Q);
            }
        }

        let (m, b) = Self::system_to_matrix_impl::<E>(system, vars, params)?;

        match m.solve(&b) {
            Ok(sol) => Ok(sol
                .into_vec()
                .into_iter()
                .map(|s| s.to_expression())
                .collect()),
            Err(MatrixError::Underdetermined {
                rank,
                row_reduced_augmented_matrix,
            }) => {
                let mut sols = Vec::with_capacity(vars.len());

                let mut var_index = 0;
                for r in row_reduced_augmented_matrix.row_iter() {
                    while var_index < vars.len() as u32 && r[var_index as usize].is_zero() {
                        sols.push(vars[var_index as usize].to_atom());
                        var_index += 1;
                    }

                    if var_index >= vars.len() as u32 {
                        break;
                    }

                    if r[var_index as usize].is_one() {
                        let mut sol = r.last().unwrap().to_expression();

                        for (var, coeff) in vars.iter().zip(r).skip((var_index + 1) as usize) {
                            if !coeff.is_zero() {
                                sol -= coeff.to_expression() * var.to_atom();
                            }
                        }

                        sols.push(sol);
                        var_index += 1;
                    }
                }

                for i in var_index as usize..vars.len() {
                    sols.push(vars[i].to_atom());
                }

                Err(SolveError::Underdetermined {
                    rank,
                    partial_solution: sols,
                })
            }
            Err(MatrixError::Inconsistent) => Err(SolveError::Inconsistent),
            Err(e) => Err(SolveError::Other(format!("Could not solve {e:?}"))),
        }
    }
}

#[cfg(test)]
mod test {
    use std::sync::Arc;

    use crate::{
        atom::{Atom, AtomCore, AtomView, representation::InlineVar},
        domains::{
            Ring,
            algebraic::AlgebraicContext,
            float::{Complex, F64, Real},
            integer::Z,
            rational::Q,
            rational_polynomial::{RationalPolynomial, RationalPolynomialField},
        },
        parse,
        poly::PolyVariable,
        solve::{Complexes, Integers, Rationals, Reals, SolveError},
        symbol,
        tensors::matrix::Matrix,
        transcendental::root,
    };

    // Generic engine regression tests do not imply completeness of its output.
    fn generic_backend(
        system: &[Atom],
        variables: &[Atom],
        domain: super::SolveDomain,
    ) -> Vec<ahash::HashMap<PolyVariable, Atom>> {
        AtomView::solve_impl::<u16, _, _>(system, variables, domain)
            .unwrap()
            .into_iter()
            .map(|b| b.values)
            .collect()
    }

    fn assert_algebraic_zero(expression: Atom) {
        if expression.is_zero() {
            return;
        }

        let mut context = AlgebraicContext::from_atom(expression.as_view()).unwrap();
        assert!(
            !context.is_trivial(),
            "expression should contain an algebraic number"
        );
        let value = context.convert_atom(expression.as_view()).unwrap();
        assert!(
            context.field().is_zero(&value),
            "expected {expression} to be zero"
        );
    }

    #[test]
    fn exact_solve_dispatches_linear_systems() {
        let x = symbol!("x");
        let y = symbol!("y");
        let system = [parse!("x+y-3"), parse!("x-y-1")];
        let variables = [Atom::var(x), Atom::var(y)];

        let solutions = Atom::solve(&system).wrt(&variables).unwrap();

        assert_eq!(solutions.len(), 1);
        assert_eq!(
            solutions[0].get(&PolyVariable::from(x)),
            Some(&Atom::num(2))
        );
        assert_eq!(
            solutions[0].get(&PolyVariable::from(y)),
            Some(&Atom::num(1))
        );
        assert!(solutions[0].is_point());
        assert_eq!(solutions[0].codimension(), Some(2));
        assert_eq!(solutions[0].dimension(), Some(0));
    }

    #[test]
    fn equality_constraints_keep_requested_variable_order() {
        let x = symbol!("x");
        let y = symbol!("y");
        let system = [parse!("x-1"), parse!("y-2")];
        let variables = [Atom::var(y), Atom::var(x)];

        let solutions = Atom::solve(&system).wrt(&variables).unwrap();
        let variable_solutions = solutions[0].coordinates();
        assert_eq!(variable_solutions.len(), 2);
        assert_eq!(&variable_solutions[0].0, &PolyVariable::from(y));
        assert_eq!(&variable_solutions[0].1, &Atom::num(2));
        assert_eq!(&variable_solutions[1].0, &PolyVariable::from(x));
        assert_eq!(&variable_solutions[1].1, &Atom::num(1));
    }

    #[test]
    fn exact_solve_dispatches_nonlinear_polynomial_systems() {
        let x = symbol!("x");
        let y = symbol!("y");
        let system = [parse!("x+y"), parse!("y^2-2")];
        let variables = [Atom::var(x), Atom::var(y)];

        assert_eq!(
            AtomView::solve_linear_system::<u16, _, Atom>(&system, &variables),
            Err(SolveError::NonLinearSystem)
        );

        let solutions = Atom::solve(&system).wrt(&variables).unwrap();
        assert_eq!(solutions.len(), 2);
        for solution in solutions {
            let x_value = solution.get(&PolyVariable::from(x)).unwrap();
            let y_value = solution.get(&PolyVariable::from(y)).unwrap();
            assert_eq!(x_value, &-y_value.clone());
            assert_eq!(
                (y_value.clone().pow(Atom::num(2)) - Atom::num(2)).expand(),
                Atom::Zero
            );
        }
    }

    #[test]
    fn solve_builder_filters_by_domain() {
        let x = symbol!("x");
        let variable = Atom::var(x);

        let real_solutions = Atom::solve(&[parse!("x^2-2")])
            .over(Reals)
            .wrt(std::slice::from_ref(&variable))
            .unwrap();
        assert_eq!(real_solutions.len(), 2);
        assert!(real_solutions.iter().all(|solution| solution.is_point()));

        let integer_solutions = Atom::solve(&[parse!("x^2-2")])
            .over(Integers)
            .wrt(std::slice::from_ref(&variable))
            .unwrap();
        assert!(integer_solutions.is_empty().unwrap());

        let rational_solutions = Atom::solve(&[parse!("(x-1/2)*(x^2-2)")])
            .over(Rationals)
            .wrt(std::slice::from_ref(&variable))
            .unwrap();
        assert_eq!(rational_solutions.len(), 1);
        assert_eq!(
            rational_solutions[0].get(&PolyVariable::from(x)),
            Some(&parse!("1/2"))
        );

        let integer_solutions = Atom::solve(&[parse!("(x-1/2)*(x^2-2)")])
            .over(Integers)
            .wrt(std::slice::from_ref(&variable))
            .unwrap();
        assert!(integer_solutions.is_empty().unwrap());

        let rational_radical_solution = Atom::solve(&[parse!("sqrt(x)-sqrt(2)")])
            .over(Rationals)
            .wrt(std::slice::from_ref(&variable))
            .unwrap();
        assert_eq!(rational_radical_solution.len(), 1);
        assert_eq!(
            rational_radical_solution[0].get(&PolyVariable::from(x)),
            Some(&Atom::num(2))
        );

        let nonreal_solutions = Atom::solve(&[parse!("x^2+1")])
            .over(Reals)
            .wrt(std::slice::from_ref(&variable))
            .unwrap();
        assert!(nonreal_solutions.is_empty().unwrap());

        let complex_solutions = Atom::solve(&[parse!("x^2+1")])
            .over(Complexes)
            .wrt(std::slice::from_ref(&variable))
            .unwrap();
        assert_eq!(complex_solutions.len(), 2);
    }

    #[test]
    fn solution_reports_exact_free_family() {
        let x = symbol!("x");
        let y = symbol!("y");
        let variables = [Atom::var(x), Atom::var(y)];

        let solutions = Atom::solve(&[parse!("x+y-1")])
            .over(Complexes)
            .wrt(&variables)
            .unwrap();

        assert_eq!(solutions.len(), 1);
        assert!(!solutions[0].is_point());
        assert_eq!(solutions[0].codimension(), Some(1));
        assert_eq!(solutions[0].dimension(), Some(1));
        assert_eq!(solutions[0].free_variables().len(), 1);
        assert!(solutions[0].conditions().is_empty());
        assert_eq!(solutions[0].domain(), Complexes);
    }

    #[test]
    fn rational_positive_dimensional_system_keeps_all_variables_mapped() {
        let x = symbol!("x");
        let y = symbol!("y");
        let z = symbol!("z");
        let variables = [Atom::var(x), Atom::var(y), Atom::var(z)];

        let solutions = generic_backend(
            &[parse!("(x-z)*(x^2-3*x+y)"), parse!("z+y-3")],
            &variables,
            Rationals,
        );

        assert_eq!(solutions.len(), 2);
        assert!(solutions.iter().all(|solution| solution.len() == 3));
        assert!(
            solutions
                .iter()
                .all(|solution| { solution.get(&PolyVariable::from(x)) == Some(&Atom::var(x)) })
        );
        assert!(solutions.iter().any(|solution| {
            solution.get(&PolyVariable::from(y)) == Some(&parse!("3-x"))
                && solution.get(&PolyVariable::from(z)) == Some(&Atom::var(x))
        }));
        assert!(solutions.iter().any(|solution| {
            solution.get(&PolyVariable::from(y)) == Some(&parse!("-x^2+3*x"))
                && solution.get(&PolyVariable::from(z)) == Some(&parse!("x^2-3*x+3"))
        }));
    }

    #[test]
    fn exact_solve_returns_a_parametrization_for_positive_dimensional_systems() {
        let x = symbol!("x");
        let y = symbol!("y");
        let z = symbol!("z");
        let system = [parse!("x+y^2"), parse!("z-y")];
        let variables = [Atom::var(x), Atom::var(y), Atom::var(z)];

        let solutions = generic_backend(&system, &variables, Complexes);

        assert_eq!(solutions.len(), 1);
        let solution = &solutions[0];
        assert_eq!(solution.get(&PolyVariable::from(x)), Some(&parse!("-z^2")));
        assert_eq!(solution.get(&PolyVariable::from(y)), Some(&Atom::var(z)));
        assert_eq!(solution.get(&PolyVariable::from(z)), Some(&Atom::var(z)));
    }

    #[test]
    fn exact_solve_does_not_choose_a_constrained_variable_as_input() {
        let x = symbol!("x");
        let y = symbol!("y");
        let system = [parse!("y^2-1")];
        let variables = [Atom::var(x), Atom::var(y)];

        let solutions = generic_backend(&system, &variables, Complexes);

        assert_eq!(solutions.len(), 2);
        for solution in solutions {
            assert_eq!(solution.get(&PolyVariable::from(x)), Some(&Atom::var(x)));
            let y_value = solution.get(&PolyVariable::from(y)).unwrap();
            assert_eq!(
                (y_value.clone().pow(Atom::num(2)) - Atom::num(1)).expand(),
                Atom::Zero
            );
        }
    }

    #[test]
    fn exact_solve_branches_over_nonlinear_input_parameters() {
        let x = symbol!("x");
        let y = symbol!("y");
        let system = [parse!("x^2+y^2-1")];
        let variables = [Atom::var(x), Atom::var(y)];

        let solutions = generic_backend(&system, &variables, Complexes);

        assert_eq!(solutions.len(), 2);
        for solution in solutions {
            assert_eq!(solution.get(&PolyVariable::from(y)), Some(&Atom::var(y)));
            let x_value = solution
                .get(&PolyVariable::from(x))
                .unwrap()
                .replace(y)
                .with(Atom::num(0));
            assert_algebraic_zero(x_value.pow(Atom::num(2)) - Atom::num(1));
        }
    }

    #[test]
    fn exact_solve_combines_explicit_and_selected_parameters() {
        let a = symbol!("a");
        let x = symbol!("x");
        let y = symbol!("y");
        let system = [parse!("x+y^2-a")];
        let variables = [Atom::var(x), Atom::var(y)];

        let solutions = generic_backend(&system, &variables, Complexes);

        assert_eq!(solutions.len(), 1);
        let solution = &solutions[0];
        assert_eq!(solution.get(&PolyVariable::from(x)), Some(&parse!("a-y^2")));
        assert_eq!(solution.get(&PolyVariable::from(y)), Some(&Atom::var(y)));
        assert!(!solution.contains_key(&PolyVariable::from(a)));
    }

    #[test]
    fn exact_solve_cubic_over_quadratic_extension() {
        let x = symbol!("x");
        let y = symbol!("y");
        let system = [parse!("x^3+y+2"), parse!("y^2-3")];
        let variables = [Atom::var(x), Atom::var(y)];

        let solutions = Atom::solve(&system).wrt(&variables).unwrap();
        assert_eq!(solutions.len(), 6);

        for solution in solutions {
            let x_value = solution.get(&PolyVariable::from(x)).unwrap();
            let y_value = solution.get(&PolyVariable::from(y)).unwrap();
            assert_algebraic_zero(
                x_value.clone().pow(Atom::num(3)) + y_value.clone() + Atom::num(2),
            );
            assert_algebraic_zero(y_value.clone().pow(Atom::num(2)) - Atom::num(3));
        }
    }

    #[test]
    fn exact_solve_cubic_with_algebraic_constant() {
        let x = symbol!("x");
        let y = symbol!("y");
        let system = [parse!("x^3+y+sqrt(2)"), parse!("y^2-3")];
        let variables = [Atom::var(x), Atom::var(y)];

        let solutions = Atom::solve(&system).wrt(&variables).unwrap();
        assert_eq!(solutions.len(), 6);
        for solution in solutions {
            assert_eq!(solution.len(), 2);
            let x_value = solution.get(&PolyVariable::from(x)).unwrap();
            let y_value = solution.get(&PolyVariable::from(y)).unwrap();
            let first_residual = Complex::<f64>::try_from(
                (x_value.clone().pow(Atom::num(3)) + y_value.clone() + parse!("sqrt(2)"))
                    .to_float(16),
            )
            .unwrap();
            let second_residual = Complex::<f64>::try_from(
                (y_value.clone().pow(Atom::num(2)) - Atom::num(3)).to_float(16),
            )
            .unwrap();
            assert!(first_residual.re.hypot(first_residual.im) < 1e-12);
            assert!(second_residual.re.hypot(second_residual.im) < 1e-12);
        }
    }

    #[test]
    fn exact_solve_supports_polynomial_parameters() {
        let x = symbol!("x");
        let y = symbol!("y");
        let a = symbol!("a");
        let system = [parse!("x+y"), parse!("y^2-a")];
        let variables = [Atom::var(x), Atom::var(y)];

        let solutions = generic_backend(&system, &variables, Complexes);
        assert_eq!(solutions.len(), 2);

        for solution in solutions {
            let x_value = solution.get(&PolyVariable::from(x)).unwrap();
            let y_value = solution.get(&PolyVariable::from(y)).unwrap();
            assert_eq!((x_value.clone() + y_value).expand(), Atom::Zero);
            let specialized = y_value.replace(a).with(Atom::num(2));
            assert_algebraic_zero(specialized.pow(Atom::num(2)) - Atom::num(2));
        }
    }

    #[test]
    fn exact_solve_expands_parametric_binomial_cubic_roots() {
        let x = symbol!("x");
        let y = symbol!("y");
        let a = symbol!("a");
        let system = [parse!("x^3+y+1"), parse!("y^2-a")];
        let variables = [Atom::var(x), Atom::var(y)];

        let solutions = generic_backend(&system, &variables, Complexes);
        assert_eq!(solutions.len(), 6);

        for solution in solutions {
            let x_value = solution.get(&PolyVariable::from(x)).unwrap();
            let y_value = solution.get(&PolyVariable::from(y)).unwrap();
            assert!(!x_value.contains_symbol(root()));
            assert!(!y_value.contains_symbol(root()));

            let x_value = x_value.replace(a).with(Atom::num(2));
            let y_value = y_value.replace(a).with(Atom::num(2));
            assert_algebraic_zero(
                (x_value.pow(Atom::num(3)) + y_value.clone() + Atom::num(1)).expand(),
            );
            assert_algebraic_zero(y_value.pow(Atom::num(2)) - Atom::num(2));
        }
    }

    #[test]
    fn exact_solve_factors_over_rational_function_parameters() {
        let x = symbol!("x");
        let system = [parse!("x^2-a^2")];
        let variables = [Atom::var(x)];

        let solutions = generic_backend(&system, &variables, Complexes);
        assert_eq!(solutions.len(), 2);

        let values = solutions
            .iter()
            .map(|solution| solution.get(&PolyVariable::from(x)).unwrap())
            .collect::<Vec<_>>();
        assert!(values.contains(&&parse!("a")));
        assert!(values.contains(&&parse!("-a")));
    }

    #[test]
    fn exact_solve_supports_rational_function_parameters() {
        let x = symbol!("x");
        let a = symbol!("a");
        let b = symbol!("b");
        let system = [parse!("x^2-a/b")];
        let variables = [Atom::var(x)];

        let solutions = generic_backend(&system, &variables, Complexes);
        assert_eq!(solutions.len(), 2);
        for solution in solutions {
            let value = solution
                .get(&PolyVariable::from(x))
                .unwrap()
                .replace(a)
                .with(Atom::num(2))
                .replace(b)
                .with(Atom::num(1));
            assert_algebraic_zero(value.pow(Atom::num(2)) - Atom::num(2));
        }
    }

    #[test]
    fn exact_solve_clears_parametric_denominators_in_solve_variables() {
        let x = symbol!("x");
        let system = [parse!("x/(x-a)")];
        let variables = [Atom::var(x)];

        let solutions = generic_backend(&system, &variables, Complexes);

        assert_eq!(solutions.len(), 1);
        assert_eq!(
            solutions[0].get(&PolyVariable::from(x)),
            Some(&Atom::num(0))
        );
        assert_eq!(solutions[0].len(), 1);
    }

    #[test]
    fn exact_solve_polynomializes_radicals_and_filters_the_sign_branch() {
        let x = symbol!("x");
        let system = [parse!("sqrt(x+3)+x")];
        let variables = [Atom::var(x)];

        let solutions = Atom::solve(&system).wrt(&variables).unwrap();

        assert_eq!(solutions.len(), 1);
        assert_eq!(solutions[0].len(), 1);
        let x_value = solutions[0].get(&PolyVariable::from(x)).unwrap();
        assert_algebraic_zero(x_value.clone().pow(Atom::num(2)) - x_value.clone() - Atom::num(3));
        assert_algebraic_zero((x_value.clone() + Atom::num(3)).sqrt() + x_value.clone());
    }

    #[test]
    fn exact_solve_rejects_a_nonprincipal_square_root_branch() {
        let x = symbol!("x");
        let system = [parse!("sqrt(x)+1")];
        let variables = [Atom::var(x)];

        let solutions = Atom::solve(&system).wrt(&variables).unwrap();
        assert!(solutions.is_empty().unwrap());
    }

    #[test]
    fn exact_solve_supports_rational_radical_equations() {
        let x = symbol!("x");
        let system = [parse!("1/x+1/sqrt(x)-1")];
        let variables = [Atom::var(x)];

        let solutions = Atom::solve(&system).wrt(&variables).unwrap();

        assert_eq!(solutions.len(), 1);
        let x_value = solutions[0].get(&PolyVariable::from(x)).unwrap();
        assert_algebraic_zero(x_value.clone() - parse!("(3+sqrt(5))/2"));
        assert_algebraic_zero(
            x_value.clone().pow(Atom::num(-1)) + x_value.clone().pow(parse!("-1/2")) - Atom::num(1),
        );
    }

    #[test]
    fn exact_solve_rejects_a_zero_of_a_cleared_denominator() {
        let x = symbol!("x");
        let system = [parse!("(sqrt(x)-1)/(x-1)")];
        let variables = [Atom::var(x)];

        let solutions = Atom::solve(&system).wrt(&variables).unwrap();

        assert!(solutions.is_empty().unwrap());
    }

    #[test]
    fn exact_solve_polynomializes_nested_radicals() {
        let x = symbol!("x");
        let system = [parse!("sqrt(sqrt(x)+1)-2")];
        let variables = [Atom::var(x)];

        let solutions = Atom::solve(&system).wrt(&variables).unwrap();

        assert_eq!(solutions.len(), 1);
        assert_eq!(
            solutions[0].get(&PolyVariable::from(x)),
            Some(&Atom::num(9))
        );
    }

    #[test]
    fn underdetermined() {
        let v0 = symbol!("v0").into();
        let v1 = symbol!("v1").into();
        let v2 = symbol!("v2").into();
        let v3 = symbol!("v3").into();
        let v4 = symbol!("v4").into();
        let eqs = ["v1 + v2 - 3", "2*v1 + 2*v2 - 6", "v1 + v3 - 5"];

        let system: Vec<_> = eqs.iter().map(|e| parse!(e)).collect();
        let vars = [v0, v1, v2, v3, v4];

        let sol = AtomView::solve_linear_system::<u8, _, InlineVar>(&system, &vars);

        assert_eq!(
            sol,
            Err(SolveError::Underdetermined {
                rank: 2,
                partial_solution: vec![
                    parse!("v0"),
                    parse!("-v3+5"),
                    parse!("v3-2"),
                    parse!("v3"),
                    parse!("v4"),
                ],
            })
        );
    }

    #[test]
    fn solve() {
        let x = symbol!("v1").into();
        let y = symbol!("v2").into();
        let z = symbol!("v3").into();
        let eqs = [
            "v4*v1 + f1(v4)*v2 + v3 - 1",
            "v1 + v4*v2 + v3/v4 - 2",
            "(v4-1)v1 + v4*v3",
        ];

        let system: Vec<_> = eqs.iter().map(|e| parse!(e)).collect();

        let sol = AtomView::solve_linear_system::<u8, _, InlineVar>(&system, &[x, y, z]).unwrap();

        let res = [
            "(v4^3-2*v4^2*f1(v4))*(v4^2-f1(v4)-v4^3+v4^4+v4*f1(v4)-v4^2*f1(v4))^-1",
            "(-1+2*v4)*(v4^2-f1(v4))^-1",
            "(v4^2-v4^3-2*v4*f1(v4)+2*v4^2*f1(v4))*(v4^2-f1(v4)-v4^3+v4^4+v4*f1(v4)-v4^2*f1(v4))^-1",
        ];
        let res = res.iter().map(|x| parse!(x)).collect::<Vec<_>>();

        assert_eq!(sol, res);
    }

    #[test]
    fn solve_from_matrix() {
        let system = [
            ["v4", "v4+1", "v4^2+5"],
            ["1", "v4", "v4+1"],
            ["v4-1", "-1", "v4"],
        ];
        let rhs = ["1", "2", "-1"];

        let var_map = Arc::new(vec![PolyVariable::Symbol(symbol!("v4"))]);

        let system_rat: Vec<RationalPolynomial<_, u8>> = system
            .iter()
            .flatten()
            .map(|s| parse!(s).to_rational_polynomial(&Q, &Z, Some(var_map.clone())))
            .collect();

        let rhs_rat: Vec<RationalPolynomial<_, u8>> = rhs
            .iter()
            .map(|s| parse!(s).to_rational_polynomial(&Q, &Z, Some(var_map.clone())))
            .collect();

        let field = RationalPolynomialField::from_poly(&rhs_rat[0].numerator);
        let m = Matrix::from_linear(
            system_rat,
            system.len() as u32,
            system.len() as u32,
            field.clone(),
        )
        .unwrap();
        let b = Matrix::new_vec(rhs_rat, field);

        let sol = m.solve(&b).unwrap();

        let res = [
            "(10-2*v4+4*v4^2-v4^3)/(6-4*v4+5*v4^2-3*v4^3+v4^4)",
            "(-4+10*v4-5*v4^2+2*v4^3)/(6-4*v4+5*v4^2-3*v4^3+v4^4)",
            "(2-4*v4)/(6-4*v4+5*v4^2-3*v4^3+v4^4)",
        ];

        let res = res
            .iter()
            .map(|x| parse!(x).to_rational_polynomial(&Z, &Z, m[(0, 0)].get_variables().clone()))
            .collect::<Vec<_>>();

        assert_eq!(sol.into_vec(), res);
    }

    #[test]
    fn find_root() {
        let x = symbol!("x");
        let a = parse!("x^2 - 2");
        let a = a.as_view();

        let root = a.nsolve(&x.into(), 1.0, 1e-10, 1000).unwrap();
        assert!((root - 2f64.sqrt()).abs() < 1e-10);
    }

    #[test]
    fn solve_system_newton() {
        let a = parse!("5x^2+x*y^2+sin(2y)^2 - 2");
        let b = parse!("exp(2x-y)+4y - 3");

        let r = AtomView::nsolve_system(
            &[a.as_view(), b.as_view()],
            &[symbol!("x").into(), symbol!("y").into()],
            &[F64::from(1.), F64::from(1.)],
            F64::from(1e-10),
            100,
        )
        .unwrap();

        assert!((r[0] - F64::from(5.672_973_499_396_123e-1)).norm() < 1e-10.into());
        assert!((r[1] - F64::from(-3.0944227920271083e-1)).norm() < 1e-10.into());
    }
}