Skip to content

moreau_ptr_solver

JAX-native conic backend for the PTR convex subproblem.

Assembles each SCP subproblem as a sparse conic program (SOCP-capable) and dispatches it to moreau.jax.Solver, a JAX-native interior-point conic solver. This backend sits alongside :class:openscvx.solvers.qpax_ptr_solver.QPAXPTRSolver (QP-only) and :class:openscvx.solvers.cvxpy_ptr_solver.CVXPyPTRSolver (DCP via CVXPy).

Compared to QPAX, Moreau accepts second-order cone (SOC) constraints natively. QPAX slack-reformulates the PTR penalties — |nu| (L1 virtual control) and pos(nu_vb) (positive-part virtual buffer) — with extra slack variables and doubled inequality rows. Here |nu_i| <= t_i is a 2-D SOC on [t_i, nu_i] with linear cost lam_vc * t_i, and pos(nu_vb) uses a nonnegative epigraph instead of two inequality rows, yielding a smaller problem for the same PTR math.

moreau.jax.Solver differentiates through the solve via implicit differentiation on the KKT conditions. Once the surrounding SCP pipeline stays in jit, jax.grad / jax.vmap can reach through a full SCvx solve (future work).

Scope
  • No user .convex() constraints — rejected upstream by :meth:ConvexSolver.lower_convex_constraints.
  • No cross-node constraints — raises :class:NotImplementedError at :meth:MoreauPTRSolver.initialize.
  • Impulsive controls (parameterization="impulsive") are supported. D_d is absorbed numerically into A_d / B_d / C_d at update time and E_d enters the dynamics row on the impulsive control slice; the initial Fix boundary condition picks up the linearized impulse at node 0. The static CSR pattern reserves the du[0, slice_imp] columns in the initial-Fix rows so warm-start structure stays valid across iterations.
  • CTCS constraints are supported; LICQ-style absolute-value inequalities are affine and fit in the nonneg cone.
Warm-start

Unlike QPAX, MoreauPTRSolver passes a :class:moreau._types.WarmStart from the previous successful solve into each solver.solve() call when the status is :attr:moreau.SolverStatus.Solved or :attr:moreau.SolverStatus.AlmostSolved.

Conic formulation

Moreau solves::

min  0.5 zᵀ P z + qᵀ z
s.t. A z + s = b,  s ∈ K

where K is a product of zero, nonneg, and SOC cones (first to last). Zero cone: s = 0 → Az = b. Nonneg cone: s ≥ 0 → Az ≤ b. SOC(d): ‖(b − Az)[1:]‖ ≤ (b − Az)[0].

Note

Moreau performs internal arithmetic in float64. Pass float_dtype="float64" to :class:openscvx.problem.Problem for tight inner-solver tolerances; the default float32 caps conditioning.

MoreauPTRSolver

Bases: PTRSolver

JAX-native conic backend for the PTR convex subproblem.

Assembles each SCP subproblem as a sparse conic program and dispatches to moreau.jax.Solver. See the module docstring for the SOC epigraph encoding, warm-start policy, and float64 advice.

Compared to :class:QPAXPTRSolver, this backend uses fewer decision variables and constraint rows for the same PTR physics (SOC epigraphs for |nu| instead of two nonneg slack rows each), warm-starts between SCP iterations on successful solves, and natively handles user :class:~openscvx.solvers.cones.SOCConstraint convex constraints.

The JAX-pure entry point :meth:iteration_callback calls the jitted kernel on the :class:moreau.jax.Solver built in :meth:initialize, as (P_data, A_data, q, b) -> (JaxSolution, JaxSolveInfo), so the backend composes with jax.jit and jax.vmap. Moreau 0.4 removed the public moreau.jax.solver factory. Solver.solve returns only the solution and stores status on solver.info, which is not batched under vmap. The kernel has no warm-start argument, so every call is a cold start: both :meth:~openscvx.problem.Problem.solve and :meth:~openscvx.problem.Problem.solve_jax drive iteration_callback for the SCP body, so neither thread Moreau's _warm_start carry across SCP iterations. The OO warm-start path still mutates _warm_start on each :meth:solve call (the legacy NumPy entry point, no longer on the SCP hot path); restoring warm-start to the SCP loop requires routing (x, z, s) through :class:AlgorithmState as a real pytree carry — see the Future Extensions in plans/jax-pure-solve.md.

Scope

Supported — state/control box, dynamics linearization (continuous and impulsive), boundary Fix, uniform time grid, linearized nodal nonconvex, CTCS LICQ rows, user .convex() affine equality, affine inequality, and second-order-cone constraints.

Not supported — cross-node constraints (raises :class:NotImplementedError with a "use CVXPyPTRSolver" pointer).

Differentiability hook for future work

moreau.jax.Solver differentiates through the solve via implicit differentiation on the KKT conditions. Once the surrounding SCP pipeline stays in jit, jax.grad / jax.vmap can reach through a full SCvx solve.

Class attributes

SUPPORTED_CONE_TYPES: Accepts :class:~openscvx.solvers.cones.ZeroConeConstraint, :class:~openscvx.solvers.cones.NonnegConeConstraint, and :class:~openscvx.solvers.cones.SOCConstraint.

Parameters:

Name Type Description Default
max_iter Optional[int]

Maximum number of IPM iterations forwarded to :class:moreau.Settings. Defaults to 200.

None
verbose Optional[bool]

Whether Moreau prints per-iteration diagnostics. Forwarded to :class:moreau.Settings. Defaults to False.

None
device Optional[str]

Compute device for Moreau's JAX kernels. One of "auto", "cpu", or "cuda". Forwarded to :class:moreau.Settings. Defaults to "auto".

None
tol_gap_abs Optional[float]

Absolute duality-gap tolerance forwarded to :class:moreau.IPMSettings. None uses Moreau's default.

None
tol_feas Optional[float]

Primal/dual feasibility tolerance forwarded to :class:moreau.IPMSettings. None uses Moreau's default.

None
solver_args Optional[Dict]

Additional keyword arguments forwarded verbatim to :class:moreau.Settings. Use for settings not covered by the named params above. solver_args["ipm_settings"] may be a dict or a :class:moreau.IPMSettings object; if it is a dict, tol_gap_abs / tol_feas are merged into it. Raises ValueError at construction time if any top-level key or IPM tolerance overlaps with a named param.

None

Attributes:

Name Type Description
layout Optional[_ConicLayout]

:class:_ConicLayout describing flat decision-vector slot ranges. Populated by :meth:create_variables.

Source code in openscvx/solvers/moreau_ptr_solver.py
 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
class MoreauPTRSolver(PTRSolver):
    """JAX-native conic backend for the PTR convex subproblem.

    Assembles each SCP subproblem as a sparse conic program and dispatches to
    ``moreau.jax.Solver``. See the module docstring for the SOC epigraph
    encoding, warm-start policy, and float64 advice.

    Compared to :class:`QPAXPTRSolver`, this backend uses fewer decision
    variables and constraint rows for the same PTR physics (SOC epigraphs for
    ``|nu|`` instead of two nonneg slack rows each), warm-starts between SCP
    iterations on successful solves, and natively handles user
    :class:`~openscvx.solvers.cones.SOCConstraint` convex constraints.

    The JAX-pure entry point :meth:`iteration_callback` calls the jitted
    kernel on the :class:`moreau.jax.Solver` built in :meth:`initialize`,
    as ``(P_data, A_data, q, b) -> (JaxSolution, JaxSolveInfo)``, so the
    backend composes with ``jax.jit`` and ``jax.vmap``. Moreau 0.4 removed
    the public ``moreau.jax.solver`` factory. ``Solver.solve`` returns only
    the solution and stores status on ``solver.info``, which is not batched
    under ``vmap``. The kernel has no warm-start argument, so every call is
    a cold start: both
    :meth:`~openscvx.problem.Problem.solve` and
    :meth:`~openscvx.problem.Problem.solve_jax` drive
    ``iteration_callback`` for the SCP body, so neither thread Moreau's
    ``_warm_start`` carry across SCP iterations. The OO warm-start path
    still mutates ``_warm_start`` on each :meth:`solve` call (the legacy
    NumPy entry point, no longer on the SCP hot path); restoring
    warm-start to the SCP loop requires routing ``(x, z, s)`` through
    :class:`AlgorithmState` as a real pytree carry — see the
    Future Extensions in ``plans/jax-pure-solve.md``.

    Scope:
        Supported — state/control box, dynamics linearization (continuous
        and impulsive), boundary Fix, uniform time grid, linearized nodal
        nonconvex, CTCS LICQ rows, user ``.convex()`` affine equality,
        affine inequality, and second-order-cone constraints.

        Not supported — cross-node constraints (raises
        :class:`NotImplementedError` with a "use CVXPyPTRSolver" pointer).

    Differentiability hook for future work:
        ``moreau.jax.Solver`` differentiates through the solve via implicit
        differentiation on the KKT conditions. Once the surrounding SCP
        pipeline stays in ``jit``, ``jax.grad`` / ``jax.vmap`` can reach
        through a full SCvx solve.

    Class attributes:
        SUPPORTED_CONE_TYPES: Accepts
            :class:`~openscvx.solvers.cones.ZeroConeConstraint`,
            :class:`~openscvx.solvers.cones.NonnegConeConstraint`, and
            :class:`~openscvx.solvers.cones.SOCConstraint`.

    Args:
        max_iter: Maximum number of IPM iterations forwarded to
            :class:`moreau.Settings`. Defaults to ``200``.
        verbose: Whether Moreau prints per-iteration diagnostics.
            Forwarded to :class:`moreau.Settings`. Defaults to ``False``.
        device: Compute device for Moreau's JAX kernels. One of
            ``"auto"``, ``"cpu"``, or ``"cuda"``. Forwarded to
            :class:`moreau.Settings`. Defaults to ``"auto"``.
        tol_gap_abs: Absolute duality-gap tolerance forwarded to
            :class:`moreau.IPMSettings`. ``None`` uses Moreau's default.
        tol_feas: Primal/dual feasibility tolerance forwarded to
            :class:`moreau.IPMSettings`. ``None`` uses Moreau's default.
        solver_args: Additional keyword arguments forwarded verbatim to
            :class:`moreau.Settings`. Use for settings not covered by the
            named params above. ``solver_args["ipm_settings"]`` may be a
            dict or a :class:`moreau.IPMSettings` object; if it is a dict,
            ``tol_gap_abs`` / ``tol_feas`` are merged into it. Raises
            ``ValueError`` at construction time if any top-level key or
            IPM tolerance overlaps with a named param.

    Attributes:
        layout: :class:`_ConicLayout` describing flat decision-vector slot
            ranges. Populated by :meth:`create_variables`.
    """

    SUPPORTED_CONE_TYPES = frozenset({ZeroConeConstraint, NonnegConeConstraint, SOCConstraint})

    def __init__(
        self,
        *,
        max_iter: Optional[int] = None,
        verbose: Optional[bool] = None,
        device: Optional[str] = None,
        tol_gap_abs: Optional[float] = None,
        tol_feas: Optional[float] = None,
        solver_args: Optional[Dict] = None,
    ):
        if not _MOREAU_AVAILABLE:
            raise ImportError(
                "MoreauPTRSolver requires the `moreau` package. "
                "Install it with: pip install openscvx[moreau]"
            )

        # None sentinels at the signature surface let us distinguish
        # "user explicitly passed this" from "default applied" — only the
        # former should collide with the same key inside solver_args.
        _named = {
            k: v
            for k, v in (
                ("max_iter", max_iter),
                ("verbose", verbose),
                ("device", device),
            )
            if v is not None
        }
        _extra = dict(solver_args) if solver_args else {}
        _overlap = _named.keys() & _extra.keys()
        if _overlap:
            raise ValueError(
                f"Moreau settings {sorted(_overlap)} appear as both named arguments "
                "and inside solver_args; use one or the other."
            )
        merged = {**_named, **_extra}
        merged.setdefault("max_iter", 200)
        merged.setdefault("verbose", False)
        merged.setdefault("device", "auto")

        _ipm = {
            k: v for k, v in [("tol_gap_abs", tol_gap_abs), ("tol_feas", tol_feas)] if v is not None
        }
        if _ipm:
            existing_ipm = merged.get("ipm_settings", {})
            if not isinstance(existing_ipm, dict):
                raise ValueError(
                    "Cannot combine tol_gap_abs / tol_feas named arguments with an "
                    "ipm_settings object in solver_args; use one form or the other."
                )
            ipm_overlap = _ipm.keys() & existing_ipm.keys()
            if ipm_overlap:
                raise ValueError(
                    f"Moreau IPM settings {sorted(ipm_overlap)} appear as both named "
                    "arguments and inside solver_args['ipm_settings']; use one or the other."
                )
            merged["ipm_settings"] = {**_ipm, **existing_ipm}

        self.solver_args = merged

        self.layout: Optional[_ConicLayout] = None
        self._S_x: Optional[np.ndarray] = None
        self._c_x: Optional[np.ndarray] = None
        self._S_u: Optional[np.ndarray] = None
        self._c_u: Optional[np.ndarray] = None
        self._S_x_diag: Optional[np.ndarray] = None
        self._S_u_diag: Optional[np.ndarray] = None
        self._inv_S_x_diag: Optional[np.ndarray] = None
        self._inv_S_u_diag: Optional[np.ndarray] = None
        self._settings: Optional["Config"] = None
        self._jax_constraints: Optional["LoweredJaxConstraints"] = None

        # moreau.jax.Solver constructed at initialize().
        self._moreau: Optional[_MoreauJaxSolver] = None

        # Fixed CSR structure stored after initialize().
        self._P_diag_slots: Optional[np.ndarray] = None
        self._P_n_dx: int = 0  # N*n_x, for indexing into P_data
        self._coo_rows: Optional[np.ndarray] = None
        self._coo_cols: Optional[np.ndarray] = None
        self._n_con: int = 0

        # Populated by PTRSolver.lower_convex_constraints.
        self._impulsive_pins: List[Tuple[List[int], slice]] = []
        self._user_cone_constraints: List = []
        self._parameters_dict: dict = {}

        # Per-iteration data, set by update_* methods.
        self._dyn: dict = {}
        self._cons: dict = {}
        self._pen: dict = {}
        self._x_init: Optional[np.ndarray] = None
        self._x_term: Optional[np.ndarray] = None

        # Warm-start carry; reset to None when problem structure changes.
        self._warm_start = None

        # Last solve status from moreau (populated by solve()).
        self._last_status: moreau.SolverStatus = moreau.SolverStatus.Unsolved

    # ------------------------------------------------------------------
    # Setup
    # ------------------------------------------------------------------

    def create_variables(
        self,
        N: int,
        x_unified: "UnifiedState",
        u_unified: "UnifiedControl",
        jax_constraints: "LoweredJaxConstraints",
        dynamics_sparsity: Optional[tuple] = None,
        constraint_sparsity: Optional[list] = None,
    ) -> None:
        """Compute scaling matrices and the static conic decision-vector layout.

        Sparsity hints are accepted for interface symmetry with
        :class:`openscvx.solvers.cvxpy_ptr_solver.CVXPyPTRSolver` but ignored;
        numeric values are filled into a fixed CSR structure at solve time.

        Args:
            N: Number of discretization nodes.
            x_unified: Unified state bounds and scaling metadata.
            u_unified: Unified control bounds and scaling metadata.
            jax_constraints: Lowered JAX constraints (nodal structure only).
            dynamics_sparsity: Ignored.
            constraint_sparsity: Ignored.
        """
        del dynamics_sparsity, constraint_sparsity

        n_x = len(x_unified.max)
        n_u = len(u_unified.max)

        S_x, c_x = self._scaling(x_unified)
        S_u, c_u = self._scaling(u_unified)

        self._S_x = S_x
        self._c_x = c_x
        self._S_u = S_u
        self._c_u = c_u
        self._S_x_diag = np.diag(S_x)
        self._S_u_diag = np.diag(S_u)
        self._inv_S_x_diag = 1.0 / self._S_x_diag
        self._inv_S_u_diag = 1.0 / self._S_u_diag

        # JAX-side scaling diagonals for ``iteration_callback``. The dtype
        # tracks the global ``jax_enable_x64`` setting so the assembled
        # ``(P_data, A_data, q, b)`` lands in the dtype Moreau's functional
        # solver expects.
        f = jnp.float64 if jax.config.read("jax_enable_x64") else jnp.float32
        self._S_x_diag_j = jnp.asarray(self._S_x_diag, dtype=f)
        self._S_u_diag_j = jnp.asarray(self._S_u_diag, dtype=f)
        self._inv_S_x_diag_j = jnp.asarray(self._inv_S_x_diag, dtype=f)
        self._inv_S_u_diag_j = jnp.asarray(self._inv_S_u_diag, dtype=f)
        self._c_x_j = jnp.asarray(self._c_x, dtype=f)
        self._c_u_j = jnp.asarray(self._c_u, dtype=f)
        self._jax_dtype = f

        if any(c.is_equality for c in jax_constraints.nodal):
            raise NotImplementedError(
                "MoreauPTRSolver does not support L1-penalized equality "
                "constraints. Use CVXPyPTRSolver."
            )

        self.layout = _ConicLayout(N=N, n_x=n_x, n_u=n_u, n_nodal=len(jax_constraints.nodal))
        self._jax_constraints = jax_constraints
        self._x_unified = x_unified

    def initialize(self, lowered: "LoweredProblem", settings: "Config") -> None:
        """Build the static conic structure and construct ``moreau.jax.Solver``.

        Validates the supported constraint subset, enumerates all A-matrix
        nonzero positions (fixed CSR structure), builds a :class:`moreau.Cones`
        spec, and constructs :class:`moreau.jax.Solver`. Numeric values in
        ``A``, ``b``, ``P``, and ``q`` are filled at each :meth:`solve` call.

        Args:
            lowered: Lowered problem with constraint structure.
            settings: Problem configuration.

        Raises:
            RuntimeError: If :meth:`create_variables` was not called first.
            NotImplementedError: If cross-node constraints are present.
        """
        if self.layout is None:
            raise RuntimeError(
                "MoreauPTRSolver.initialize() called before create_variables(). "
                "Call create_variables() first."
            )

        if lowered.jax_constraints.cross_node:
            raise NotImplementedError(
                "MoreauPTRSolver does not yet support cross-node constraints "
                f"({len(lowered.jax_constraints.cross_node)} defined). "
                "Use CVXPyPTRSolver."
            )

        self._settings = settings
        # Reset warm-start on new initialization (problem structure may change).
        self._warm_start = None

        # Enumerate all (row, col) pairs in the A matrix (structural pass).
        coo_rows, coo_cols, n_eq, n_nn, soc_dims = self._structural_pass(settings)
        n_soc = sum(soc_dims)
        self._n_con = n_eq + n_nn + n_soc
        self._coo_rows = np.asarray(coo_rows, dtype=np.int32)
        self._coo_cols = np.asarray(coo_cols, dtype=np.int32)

        # Build CSR for A from the structural COO.
        n_coo = len(coo_rows)
        if n_coo > 0:
            A_struct = sp.csr_matrix(
                (np.ones(n_coo), (coo_rows, coo_cols)),
                shape=(self._n_con, self.layout.n_z),
            )
            A_struct.sort_indices()
        else:
            A_struct = sp.csr_matrix((self._n_con, self.layout.n_z))
        A_indptr = np.asarray(A_struct.indptr, dtype=np.int32)
        A_indices = np.asarray(A_struct.indices, dtype=np.int32)
        self._A_indptr = A_indptr
        self._A_indices = A_indices

        # Precompute the COO→CSR permutation so the JAX assembly can emit
        # ``coo_vals`` in COO traversal order (matching ``_structural_pass``)
        # and then ``A_data = coo_vals[csr_to_coo_perm]`` matches what
        # ``solve_qp_primal``/Moreau's ``solve_fn`` expects under the fixed
        # ``A_col_indices``. NumPy ``solve()`` keeps using scipy's sort path;
        # this permutation is consumed only by ``_assemble_conic_jax``.
        if n_coo > 0:
            A_pos = sp.csr_matrix(
                (np.arange(n_coo, dtype=np.int32), (coo_rows, coo_cols)),
                shape=(self._n_con, self.layout.n_z),
            )
            A_pos.sort_indices()
            self._csr_to_coo_perm = np.asarray(A_pos.data, dtype=np.int32)
        else:
            self._csr_to_coo_perm = np.zeros((0,), dtype=np.int32)

        # Build CSR for P (diagonal on dx/du slots only).
        L = self.layout
        N, n_x = L.N, L.n_x
        dx_cols = np.arange(L.sl_dx.start, L.sl_dx.stop, dtype=np.int32)
        du_cols = np.arange(L.sl_du.start, L.sl_du.stop, dtype=np.int32)
        self._P_diag_slots = np.concatenate([dx_cols, du_cols])
        self._P_n_dx = N * n_x  # boundary between dx and du in P_data

        # P is diagonal: for each slot col, the single nonzero is P[col, col].
        P_indptr = np.zeros(L.n_z + 1, dtype=np.int32)
        for col in self._P_diag_slots:
            P_indptr[col + 1] = 1
        P_indptr = np.cumsum(P_indptr)
        P_indices = self._P_diag_slots  # diagonal → col index == row index

        # Construct moreau.Cones spec.
        cones = moreau.Cones(
            num_zero_cones=n_eq,
            num_nonneg_cones=n_nn,
            so_cone_dims=soc_dims,
        )

        # Build moreau.Settings from solver_args.
        moreau_settings = _build_moreau_settings(self.solver_args)

        self._moreau = _MoreauJaxSolver(
            n=L.n_z,
            m=self._n_con,
            P_row_offsets=jnp.array(P_indptr),
            P_col_indices=jnp.array(P_indices),
            A_row_offsets=jnp.array(A_indptr),
            A_col_indices=jnp.array(A_indices),
            cones=cones,
            settings=moreau_settings,
        )

    # ------------------------------------------------------------------
    # Per-iteration update hooks
    # ------------------------------------------------------------------

    def update_dynamics_linearization(
        self,
        x_bar: np.ndarray,
        u_bar: np.ndarray,
        A_d: np.ndarray,
        B_d: np.ndarray,
        C_d: np.ndarray,
        x_prop: np.ndarray,
        x_prop_plus: Optional[np.ndarray] = None,
        D_d: Optional[np.ndarray] = None,
        E_d: Optional[np.ndarray] = None,
    ) -> None:
        A_eff = np.asarray(A_d, dtype=float)
        B_eff = np.asarray(B_d, dtype=float)
        C_eff = np.asarray(C_d, dtype=float)

        # Absorb the impulsive state Jacobian into the continuous step
        # matrices so the assembly row keeps a single A_d·dx + B_d·du term,
        # matching the recipe in CVXPyPTRSolver.update_dynamics_linearization
        # at openscvx/solvers/cvxpy_ptr_solver.py:636-654.
        if D_d is not None:
            D_arr = np.asarray(D_d, dtype=float)
            if D_arr.ndim == 3 and D_arr.shape[0] == A_eff.shape[0] + 1:
                D_steps = D_arr[1:]
            elif D_arr.ndim == 3 and D_arr.shape[0] == A_eff.shape[0]:
                D_steps = D_arr
            else:
                raise ValueError(
                    "Unexpected D_d shape for dynamics update: "
                    f"{D_arr.shape}, expected "
                    f"{(A_eff.shape[0] + 1, A_eff.shape[1], A_eff.shape[2])} "
                    f"or {(A_eff.shape[0], A_eff.shape[1], A_eff.shape[2])}."
                )
            A_eff = np.einsum("kij,kjl->kil", D_steps, A_eff)
            B_eff = np.einsum("kij,kjl->kil", D_steps, B_eff)
            C_eff = np.einsum("kij,kjl->kil", D_steps, C_eff)

        self._dyn = {
            "x_bar": np.asarray(x_bar, dtype=float),
            "u_bar": np.asarray(u_bar, dtype=float),
            "A_d": A_eff,
            "B_d": B_eff,
            "C_d": C_eff,
            "x_prop": np.asarray(x_prop, dtype=float),
            "x_prop_plus": (
                np.asarray(x_prop_plus, dtype=float) if x_prop_plus is not None else None
            ),
            "E_d": np.asarray(E_d, dtype=float) if E_d is not None else None,
        }

    def update_constraint_linearizations(
        self,
        nodal: Optional[List[dict]] = None,
        cross_node: Optional[List[dict]] = None,
    ) -> None:
        if cross_node:
            raise NotImplementedError(
                "MoreauPTRSolver received cross-node linearization data; "
                "cross-node constraints are not supported. Use CVXPyPTRSolver."
            )
        self._cons = {
            "nodal": [
                {
                    "g": np.asarray(d["g"], dtype=float),
                    "grad_g_x": np.asarray(d["grad_g_x"], dtype=float),
                    "grad_g_u": np.asarray(d["grad_g_u"], dtype=float),
                }
                for d in (nodal or [])
            ],
        }

    def update_penalties(
        self,
        lam_prox: np.ndarray,
        lam_cost: Union[float, np.ndarray],
        lam_vc: np.ndarray,
        lam_vb_nodal: np.ndarray,
        lam_vb_cross: np.ndarray,
    ) -> None:
        del lam_vb_cross  # cross-node rejected at initialize()
        self._pen = {
            "lam_prox": np.asarray(lam_prox, dtype=float),
            "lam_cost": np.asarray(lam_cost, dtype=float),
            "lam_vc": np.asarray(lam_vc, dtype=float),
            "lam_vb_nodal": np.asarray(lam_vb_nodal, dtype=float),
        }

    def update_boundary_conditions(
        self,
        x_init: Optional[np.ndarray] = None,
        x_term: Optional[np.ndarray] = None,
    ) -> None:
        if x_init is not None:
            self._x_init = np.asarray(x_init, dtype=float)
        if x_term is not None:
            self._x_term = np.asarray(x_term, dtype=float)

    # ------------------------------------------------------------------
    # Structural pass (called once at initialize)
    # ------------------------------------------------------------------

    def _structural_pass(
        self,
        settings: "Config",
    ) -> Tuple[List[int], List[int], int, int, List[int]]:
        """Enumerate all A-matrix ``(row, col)`` nonzero positions.

        Iterates through every constraint row in the exact order used by
        :meth:`_assemble_conic`, recording which columns are structurally
        nonzero.  Only the positions (not the values) matter here; values come
        from per-iteration data at solve time.

        Args:
            settings: Problem configuration (bounds, CTCS groups, time grid).

        Returns:
            tuple: ``(coo_rows, coo_cols, n_eq, n_nn, soc_dims)`` where
            ``coo_rows`` / ``coo_cols`` list every A-matrix nonzero in
            traversal order, ``n_eq`` / ``n_nn`` count zero- and nonneg-cone
            rows, and ``soc_dims`` lists SOC dimensions (2 per ``|nu[k,j]|``).
        """
        L = self.layout
        N, n_x, n_u = L.N, L.n_x, L.n_u
        jax_constraints = self._jax_constraints

        coo_rows: List[int] = []
        coo_cols: List[int] = []
        row = 0

        def add(r: int, c: int) -> None:
            coo_rows.append(r)
            coo_cols.append(c)

        # ================================================================
        # ZERO CONE (equality, s = 0 → Az = b)
        # ================================================================

        # State error definitions: x[k,j] − dx[k,j] = rhs  (N·n_x rows)
        for k in range(N):
            for j in range(n_x):
                add(row, L.x_idx(k, j))
                add(row, L.dx_idx(k, j))
                row += 1

        # Control error definitions: u[k,j] − du[k,j] = rhs  (N·n_u rows)
        for k in range(N):
            for j in range(n_u):
                add(row, L.u_idx(k, j))
                add(row, L.du_idx(k, j))
                row += 1

        # Dynamics (FOH, continuous PTR)  ((N-1)·n_x rows)
        for k in range(1, N):
            kp = k - 1
            for i in range(n_x):
                add(row, L.x_idx(k, i))
                for j in range(n_x):
                    add(row, L.dx_idx(kp, j))
                for j in range(n_u):
                    add(row, L.du_idx(kp, j))
                    add(row, L.du_idx(k, j))
                add(row, L.nu_idx(kp, i))
                row += 1

        # Linearized nodal constraints: grad·dx + grad·du − nu_vb = −g
        for c_idx, constraint in enumerate(jax_constraints.nodal):
            for node in constraint.nodes:
                for j in range(n_x):
                    add(row, L.dx_idx(node, j))
                for j in range(n_u):
                    add(row, L.du_idx(node, j))
                add(row, L.nu_vb_idx(c_idx, node))
                row += 1

        # Fix boundary conditions (initial / terminal).  Under impulsive
        # control the initial Fix row couples the post-impulse state at
        # node 0 to du[0, slice_imp]; declare those columns structurally
        # nonzero here so the static CSR pattern accommodates the
        # numerical values emitted in _assemble_conic.
        slice_imp = settings.sim.u.slice_impulsive
        has_impulsive = slice_imp.stop > slice_imp.start
        for i in range(settings.sim.true_state_slice.start, settings.sim.true_state_slice.stop):
            if settings.sim.x.initial_type[i] == "Fix":
                add(row, L.x_idx(0, i))
                if has_impulsive:
                    for j in range(slice_imp.start, slice_imp.stop):
                        add(row, L.du_idx(0, j))
                row += 1
            if settings.sim.x.final_type[i] == "Fix":
                add(row, L.x_idx(N - 1, i))
                row += 1

        # Impulsive zero-pin equalities: u[node, j] = const, one row per
        # (node, j) absorbed by lower_convex_constraints.
        for nodes, ctrl_slice in self._impulsive_pins:
            for node in nodes:
                for j in range(ctrl_slice.start, ctrl_slice.stop):
                    add(row, L.u_idx(node, j))
                    row += 1

        # User ZeroConeConstraint rows (hard equality, one row per scalar output).
        for cc in self._user_cone_constraints:
            if isinstance(cc, ZeroConeConstraint):
                for k in cc.nodes:
                    for _ in range(cc.m):
                        for j in range(n_x):
                            add(row, L.dx_idx(k, j))
                        for j in range(n_u):
                            add(row, L.du_idx(k, j))
                        row += 1

        # Uniform time grid: u[k,j] − u[k-1,j] = 0
        if settings.sim._uniform_time_grid:
            td = settings.sim.time_dilation_slice
            for k in range(1, N):
                for j in range(td.start, td.stop):
                    add(row, L.u_idx(k, j))
                    add(row, L.u_idx(k - 1, j))
                    row += 1

        # CTCS initial: S_x[idx]·x[0,idx] = −c_x[idx]  (one per CTCS group)
        for idx in range(settings.sim.ctcs_slice.start, settings.sim.ctcs_slice.stop):
            add(row, L.x_idx(0, idx))
            row += 1

        n_eq = row

        # ================================================================
        # NONNEG CONE (s = b − Az ≥ 0)
        # ================================================================

        # State box upper: x[k,j] ≤ x_max_scaled[j]
        for k in range(N):
            for j in range(n_x):
                add(row, L.x_idx(k, j))
                row += 1

        # State box lower: x[k,j] ≥ x_min_scaled[j]
        for k in range(N):
            for j in range(n_x):
                add(row, L.x_idx(k, j))
                row += 1

        # Control box upper
        for k in range(N):
            for j in range(n_u):
                add(row, L.u_idx(k, j))
                row += 1

        # Control box lower
        for k in range(N):
            for j in range(n_u):
                add(row, L.u_idx(k, j))
                row += 1

        # CTCS difference rows (two per node interval per group)
        for idx, nodes in zip(
            range(settings.sim.ctcs_slice.start, settings.sim.ctcs_slice.stop),
            settings.sim.ctcs_node_intervals,
        ):
            start_i = 1 if nodes[0] == 0 else nodes[0]
            for i in range(start_i, nodes[1]):
                # +direction
                add(row, L.x_idx(i, idx))
                add(row, L.x_idx(i - 1, idx))
                row += 1
                # −direction
                add(row, L.x_idx(i, idx))
                add(row, L.x_idx(i - 1, idx))
                row += 1

        # Pos epigraph: t_vb[c,k] ≥ nu_vb[c,k]
        for c_idx in range(L.n_nodal):
            for k in range(N):
                add(row, L.nu_vb_idx(c_idx, k))
                add(row, L.t_vb_idx(c_idx, k))
                row += 1

        # Pos epigraph non-negativity: t_vb[c,k] ≥ 0
        for c_idx in range(L.n_nodal):
            for k in range(N):
                add(row, L.t_vb_idx(c_idx, k))
                row += 1

        # User NonnegConeConstraint rows.
        for cc in self._user_cone_constraints:
            if isinstance(cc, NonnegConeConstraint):
                for k in cc.nodes:
                    for _ in range(cc.m):
                        for j in range(n_x):
                            add(row, L.dx_idx(k, j))
                        for j in range(n_u):
                            add(row, L.du_idx(k, j))
                        row += 1

        n_nn = row - n_eq

        # ================================================================
        # SOC rows: for each scalar |nu[k,j]| ≤ t_vc[k,j], SOC(2)
        # ================================================================
        soc_dims: List[int] = []
        for k in range(N - 1):
            for j in range(n_x):
                # s[0] = t_vc (row 0 of this SOC block)
                add(row, L.t_vc_idx(k, j))
                row += 1
                # s[1] = nu   (row 1 of this SOC block)
                add(row, L.nu_idx(k, j))
                row += 1
                soc_dims.append(2)

        # User SOCConstraint rows: each node contributes SOC(m_arg + 1).
        # Row layout: [bound, arg[0], arg[1], ..., arg[m_arg-1]].
        # Moreau convention s = b - Az ∈ K_soc: ‖s[1:]‖ ≤ s[0].
        # Since arg and bound are affine in (x, u), columns are dx[k, :] and du[k, :].
        for cc in self._user_cone_constraints:
            if isinstance(cc, SOCConstraint):
                soc_dim = cc.m_arg + 1
                for k in cc.nodes:
                    for _ in range(soc_dim):
                        for j in range(n_x):
                            add(row, L.dx_idx(k, j))
                        for j in range(n_u):
                            add(row, L.du_idx(k, j))
                        row += 1
                    soc_dims.append(soc_dim)

        return coo_rows, coo_cols, n_eq, n_nn, soc_dims

    # ------------------------------------------------------------------
    # Assembly (called each SCP iteration)
    # ------------------------------------------------------------------

    def _assemble_conic(
        self,
    ) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
        """Fill ``P_data``, COO A-values, ``q``, and ``b`` from per-iteration data.

        Iterates through every row in the same order as :meth:`_structural_pass`
        so the emitted value list matches ``self._coo_rows`` /
        ``self._coo_cols``. scipy builds the same sorted CSR each call, so
        ``A_csr.data`` aligns with the fixed ``A_indices`` from
        :meth:`initialize`.

        Returns:
            tuple: ``(P_data, coo_vals, q, b)`` as 1-D NumPy float arrays.

        Raises:
            RuntimeError: If per-iteration update hooks were not called.
        """
        if not (self._dyn and self._cons and self._pen):
            raise RuntimeError(
                "MoreauPTRSolver.solve() requires update_dynamics_linearization, "
                "update_constraint_linearizations, and update_penalties to all "
                "have been called this iteration."
            )

        L = self.layout
        settings = self._settings
        N, n_x, n_u = L.N, L.n_x, L.n_u
        inv_S_x = self._inv_S_x_diag
        inv_S_u = self._inv_S_u_diag
        S_x = self._S_x_diag
        S_u = self._S_u_diag
        c_x = self._c_x
        c_u = self._c_u
        slice_imp = settings.sim.u.slice_impulsive
        has_impulsive = slice_imp.stop > slice_imp.start

        lam_prox = self._pen["lam_prox"]  # (N, n_x + n_u)
        lam_cost = self._pen["lam_cost"]  # scalar or (n_x,)
        lam_vc = self._pen["lam_vc"]  # (N-1, n_x)
        lam_vb_nodal = self._pen["lam_vb_nodal"]  # (N, n_nodal or 1)

        x_bar = self._dyn["x_bar"]  # (N, n_x)
        u_bar = self._dyn["u_bar"]  # (N, n_u)
        A_d = self._dyn["A_d"]  # (N-1, n_x, n_x)
        B_d = self._dyn["B_d"]  # (N-1, n_x, n_u)
        C_d = self._dyn["C_d"]  # (N-1, n_x, n_u)
        x_prop = self._dyn["x_prop"]  # (N-1, n_x)
        E_d_arr = self._dyn["E_d"]  # (N, n_x, n_u) or None
        x_prop_plus_arr = self._dyn["x_prop_plus"]  # (N, n_x) or None

        lam_cost_arr = np.broadcast_to(lam_cost, (settings.sim.n_states,))

        # ---- P_data (diagonal trust-region weights on dx/du) ----
        # P_diag_slots = [dx_0..dx_{N·n_x-1}, du_0..du_{N·n_u-1}]
        P_data = np.empty(len(self._P_diag_slots))
        n_dx = self._P_n_dx  # N * n_x
        for k in range(N):
            for j in range(n_x):
                P_data[k * n_x + j] = 2.0 * lam_prox[k, j] + _P_DIAG_EPS
        for k in range(N):
            for j in range(n_u):
                P_data[n_dx + k * n_u + j] = 2.0 * lam_prox[k, n_x + j] + _P_DIAG_EPS

        # ---- q (linear cost vector) ----
        q = np.zeros(L.n_z)
        for i in range(settings.sim.true_state_slice.start, settings.sim.true_state_slice.stop):
            init_t = settings.sim.x.initial_type[i]
            final_t = settings.sim.x.final_type[i]
            if init_t == "Minimize":
                q[L.x_idx(0, i)] += lam_cost_arr[i]
            elif init_t == "Maximize":
                q[L.x_idx(0, i)] -= lam_cost_arr[i]
            if final_t == "Minimize":
                q[L.x_idx(N - 1, i)] += lam_cost_arr[i]
            elif final_t == "Maximize":
                q[L.x_idx(N - 1, i)] -= lam_cost_arr[i]
        for k in range(N - 1):
            for j in range(n_x):
                q[L.t_vc_idx(k, j)] += lam_vc[k, j]
        for c_idx in range(L.n_nodal):
            for k in range(N):
                q[L.t_vb_idx(c_idx, k)] += lam_vb_nodal[k, c_idx]

        # ---- A values and b (in same row order as _structural_pass) ----
        # Convention: s = b − Az.
        #   Zero cone:  s = 0  → A has same signs as "Az = b" formulation.
        #   Nonneg:     s ≥ 0  → b − Az ≥ 0.
        #   SOC:        s ∈ K  → (b − Az) ∈ K_soc.

        coo_vals: List[float] = []
        b_list: List[float] = []

        def emit(a_coeffs: List[float], rhs: float) -> None:
            """Append one constraint row's A coefficients and RHS."""
            coo_vals.extend(a_coeffs)
            b_list.append(rhs)

        # ================================================================
        # ZERO CONE rows
        # ================================================================

        # State error defs: x[k,j] − dx[k,j] = inv_S_x[j]·(x_bar[k,j] − c_x[j])
        for k in range(N):
            for j in range(n_x):
                emit([1.0, -1.0], inv_S_x[j] * (x_bar[k, j] - c_x[j]))

        # Control error defs: u[k,j] − du[k,j] = inv_S_u[j]·(u_bar[k,j] − c_u[j])
        for k in range(N):
            for j in range(n_u):
                emit([1.0, -1.0], inv_S_u[j] * (u_bar[k, j] - c_u[j]))

        # Dynamics (continuous FOH, with optional impulsive coupling at node k):
        #   x[k] − A_blk·dx[k-1] − B_blk·du[k-1] − C_blk·du[k]
        #        − E_blk·du[k][slice_imp] − nu[k-1]
        #     = inv_S_x·(x_prop_plus[k] − c_x)   if has_impulsive
        #     = inv_S_x·(x_prop[k-1]    − c_x)   otherwise
        # Mirrors CVXPyPTRSolver.constraints at cvxpy_ptr_solver.py:506-530.
        for k in range(1, N):
            kp = k - 1
            A_blk = (inv_S_x[:, None] * A_d[kp]) * S_x[None, :]
            B_blk = (inv_S_x[:, None] * B_d[kp]) * S_u[None, :]
            C_blk = (inv_S_x[:, None] * C_d[kp]) * S_u[None, :]
            if has_impulsive:
                E_blk = (inv_S_x[:, None] * E_d_arr[k]) * S_u[None, :]
                rhs_k = inv_S_x * (x_prop_plus_arr[k] - c_x)
            else:
                E_blk = None
                rhs_k = inv_S_x * (x_prop[kp] - c_x)
            for i in range(n_x):
                # Coefficients in the same col order as _structural_pass added them,
                # then sorted by scipy within the row — values line up correctly.
                coeffs: List[float] = [1.0]  # x[k, i]
                for j in range(n_x):
                    coeffs.append(-A_blk[i, j])  # dx[kp, j]
                for j in range(n_u):
                    coeffs.append(-B_blk[i, j])  # du[kp, j]
                    c_kj = -C_blk[i, j]
                    if has_impulsive and slice_imp.start <= j < slice_imp.stop:
                        c_kj -= E_blk[i, j]
                    coeffs.append(c_kj)  # du[k, j]
                coeffs.append(-1.0)  # nu[kp, i]
                emit(coeffs, rhs_k[i])

        # Linearized nodal constraints:
        #   grad_x·dx[k] + grad_u·du[k] − nu_vb[c,k] = −g[c,k]
        jax_constraints = self._jax_constraints
        for c_idx, constraint in enumerate(jax_constraints.nodal):
            data = self._cons["nodal"][c_idx]
            g = data["g"]  # (N,)
            grad_x = data["grad_g_x"]  # (N, n_x)
            grad_u = data["grad_g_u"]  # (N, n_u)
            for node in constraint.nodes:
                coeffs = []
                for j in range(n_x):
                    coeffs.append(grad_x[node, j])  # dx[node, j]
                for j in range(n_u):
                    coeffs.append(grad_u[node, j])  # du[node, j]
                coeffs.append(-1.0)  # nu_vb[c, node]
                emit(coeffs, -g[node])

        # Fix boundary conditions.  Under impulsive control the initial Fix
        # row couples x[0, i] to du[0, slice_imp] via the linearized impulse
        # Jacobian (CVXPy reference: cvxpy_ptr_solver.py:484-495).  Emit
        # coefficients in ascending column-index order so they match the
        # CSR sort applied to the structural pass.
        for i in range(settings.sim.true_state_slice.start, settings.sim.true_state_slice.stop):
            if settings.sim.x.initial_type[i] == "Fix":
                if has_impulsive:
                    coeffs = [S_x[i]]
                    for j in range(slice_imp.start, slice_imp.stop):
                        coeffs.append(-E_d_arr[0, i, j] * S_u[j])
                    emit(coeffs, x_prop_plus_arr[0, i] - c_x[i])
                else:
                    if self._x_init is None:
                        raise RuntimeError(
                            f"Fix initial condition on state {i} requires x_init; "
                            "call update_boundary_conditions() before solve()."
                        )
                    emit([S_x[i]], self._x_init[i] - c_x[i])
            if settings.sim.x.final_type[i] == "Fix":
                if self._x_term is None:
                    raise RuntimeError(
                        f"Fix final condition on state {i} requires x_term; "
                        "call update_boundary_conditions() before solve()."
                    )
                emit([S_x[i]], self._x_term[i] - c_x[i])

        # Impulsive zero-pin equalities: u[node, j] = −inv_S_u[j]·c_u[j].
        # Mirrors CVXPy's lowering of ``u_nonscaled[node][slice_imp] == 0``.
        for nodes, ctrl_slice in self._impulsive_pins:
            for node in nodes:
                for j in range(ctrl_slice.start, ctrl_slice.stop):
                    emit([1.0], -inv_S_u[j] * c_u[j])

        # User ZeroConeConstraint rows.
        # Linearize: (J_x·S_x)·dx_scaled + (J_u·S_u)·du_scaled = -f0.
        # Jacobians are w.r.t. physical x/u; dx_scaled = Δx_phys / S_x, so
        # the coefficient for dx_scaled[k, j] is J_x_phys[i, j] * S_x[j].
        params = self._parameters_dict
        for cc in self._user_cone_constraints:
            if isinstance(cc, ZeroConeConstraint):
                for k in cc.nodes:
                    x_k = x_bar[k]
                    u_k = u_bar[k]
                    f0 = np.asarray(cc.jax_fn(x_k, u_k, k, params), dtype=float).reshape(cc.m)
                    J_x = (
                        np.asarray(
                            jax.jacfwd(cc.jax_fn, argnums=0)(x_k, u_k, k, params), dtype=float
                        ).reshape(cc.m, n_x)
                        * S_x[None, :]
                    )
                    J_u = (
                        np.asarray(
                            jax.jacfwd(cc.jax_fn, argnums=1)(x_k, u_k, k, params), dtype=float
                        ).reshape(cc.m, n_u)
                        * S_u[None, :]
                    )
                    rhs = -f0
                    for i in range(cc.m):
                        coeffs = list(J_x[i]) + list(J_u[i])
                        emit(coeffs, float(rhs[i]))

        # Uniform time grid: u[k,j] − u[k-1,j] = 0
        if settings.sim._uniform_time_grid:
            td = settings.sim.time_dilation_slice
            for k in range(1, N):
                for j in range(td.start, td.stop):
                    emit([1.0, -1.0], 0.0)

        # CTCS initial: S_x[idx]·x[0,idx] = −c_x[idx]
        for idx in range(settings.sim.ctcs_slice.start, settings.sim.ctcs_slice.stop):
            emit([S_x[idx]], -c_x[idx])

        # ================================================================
        # NONNEG CONE rows (s = b − Az ≥ 0)
        # ================================================================
        x_max_sc = inv_S_x * (np.asarray(settings.sim.x.max, dtype=float) - c_x)
        x_min_sc = inv_S_x * (np.asarray(settings.sim.x.min, dtype=float) - c_x)
        u_max_sc = inv_S_u * (np.asarray(settings.sim.u.max, dtype=float) - c_u)
        u_min_sc = inv_S_u * (np.asarray(settings.sim.u.min, dtype=float) - c_u)

        # State box upper: s = x_max_sc[j] − x[k,j] ≥ 0
        for k in range(N):
            for j in range(n_x):
                emit([1.0], x_max_sc[j])

        # State box lower: s = x[k,j] − x_min_sc[j] ≥ 0  →  b=−x_min_sc, A=−1
        for k in range(N):
            for j in range(n_x):
                emit([-1.0], -x_min_sc[j])

        # Control box upper
        for k in range(N):
            for j in range(n_u):
                emit([1.0], u_max_sc[j])

        # Control box lower
        for k in range(N):
            for j in range(n_u):
                emit([-1.0], -u_min_sc[j])

        # CTCS difference rows
        for idx, nodes in zip(
            range(settings.sim.ctcs_slice.start, settings.sim.ctcs_slice.stop),
            settings.sim.ctcs_node_intervals,
        ):
            start_i = 1 if nodes[0] == 0 else nodes[0]
            x_max_un = float(settings.sim.x.max[idx])
            scale = S_x[idx]
            for i in range(start_i, nodes[1]):
                # Row for +direction: s = x_max − scale·(x[i]−x[i-1]) ≥ 0
                # structural cols: x[i,idx] then x[i-1,idx]; scipy sorts by col.
                # x[i-1,idx] < x[i,idx] in column index, so after sort:
                #   data = [−scale (at x[i-1]), +scale (at x[i])]
                # → s = x_max − (−scale·x[i-1] + scale·x[i]) = x_max − scale·(x[i]−x[i-1]) ✓
                emit([scale, -scale], x_max_un)  # col order: x[i], x[i-1]
                # Row for −direction: s = x_max − scale·(x[i-1]−x[i]) ≥ 0
                emit([-scale, scale], x_max_un)  # col order: x[i], x[i-1]

        # Pos epigraph: t_vb[c,k] − nu_vb[c,k] ≥ 0
        # structural col order: nu_vb first, t_vb second (nu_vb < t_vb in layout)
        # scipy sort: nu_vb first (smaller idx) → coefficients below match that order
        for c_idx in range(L.n_nodal):
            for k in range(N):
                # [nu_vb coeff, t_vb coeff] after sorting by col
                emit([1.0, -1.0], 0.0)  # s = 0 − (nu_vb − t_vb) = t_vb − nu_vb ≥ 0

        # Pos epigraph non-negativity: t_vb[c,k] ≥ 0
        for c_idx in range(L.n_nodal):
            for k in range(N):
                emit([-1.0], 0.0)  # s = 0 − (−t_vb) = t_vb ≥ 0

        # User NonnegConeConstraint rows.
        # s = b − Az ≥ 0;  A = J·S (scaled Jacobian), b = -f0.
        # Jacobians are w.r.t. physical x/u; multiply by S_x/S_u to get
        # coefficients for the scaled decision variables dx_scaled / du_scaled.
        for cc in self._user_cone_constraints:
            if isinstance(cc, NonnegConeConstraint):
                for k in cc.nodes:
                    x_k = x_bar[k]
                    u_k = u_bar[k]
                    f0 = np.asarray(cc.jax_fn(x_k, u_k, k, params), dtype=float).reshape(cc.m)
                    J_x = (
                        np.asarray(
                            jax.jacfwd(cc.jax_fn, argnums=0)(x_k, u_k, k, params), dtype=float
                        ).reshape(cc.m, n_x)
                        * S_x[None, :]
                    )
                    J_u = (
                        np.asarray(
                            jax.jacfwd(cc.jax_fn, argnums=1)(x_k, u_k, k, params), dtype=float
                        ).reshape(cc.m, n_u)
                        * S_u[None, :]
                    )
                    rhs = -f0
                    for i in range(cc.m):
                        coeffs = list(J_x[i]) + list(J_u[i])
                        emit(coeffs, float(rhs[i]))

        # ================================================================
        # SOC rows: SOC(2) for |nu[k,j]| ≤ t_vc[k,j]
        # s = b − Az: row 0 has only t_vc (coeff −1), row 1 has only nu (coeff −1)
        # s[0] = 0 − (−t_vc) = t_vc; s[1] = 0 − (−nu) = nu
        # ‖s[1:]‖ = |nu| ≤ s[0] = t_vc  ✓
        # ================================================================
        for k in range(N - 1):
            for j in range(n_x):
                emit([-1.0], 0.0)  # row for t_vc
                emit([-1.0], 0.0)  # row for nu

        # User SOCConstraint rows: SOC(m_arg + 1) per node.
        # Layout: [bound_row, arg_row_0, …, arg_row_{m_arg-1}].
        # Moreau convention: s = b − Az ∈ K_soc, ‖s[1:]‖ ≤ s[0].
        # Linearized: s[0] = bound0 + J_b·Δ, s[1+i] = arg0[i] + J_a[i]·Δ.
        # s = b − A·z → A = −J·S, b = val.  Jacobians scaled by S_x/S_u to
        # convert from physical-space to scaled-decision-variable coefficients.
        for cc in self._user_cone_constraints:
            if isinstance(cc, SOCConstraint):
                for k in cc.nodes:
                    x_k = x_bar[k]
                    u_k = u_bar[k]
                    # Bound function.
                    bound0 = float(np.asarray(cc.bound_fn(x_k, u_k, k, params)))
                    Jb_x = (
                        np.asarray(
                            jax.jacfwd(cc.bound_fn, argnums=0)(x_k, u_k, k, params), dtype=float
                        ).reshape(n_x)
                        * S_x
                    )
                    Jb_u = (
                        np.asarray(
                            jax.jacfwd(cc.bound_fn, argnums=1)(x_k, u_k, k, params), dtype=float
                        ).reshape(n_u)
                        * S_u
                    )
                    # Arg function.
                    arg0 = np.asarray(cc.arg_fn(x_k, u_k, k, params), dtype=float).reshape(cc.m_arg)
                    Ja_x = (
                        np.asarray(
                            jax.jacfwd(cc.arg_fn, argnums=0)(x_k, u_k, k, params), dtype=float
                        ).reshape(cc.m_arg, n_x)
                        * S_x[None, :]
                    )
                    Ja_u = (
                        np.asarray(
                            jax.jacfwd(cc.arg_fn, argnums=1)(x_k, u_k, k, params), dtype=float
                        ).reshape(cc.m_arg, n_u)
                        * S_u[None, :]
                    )
                    # Bound row: A = −J_b·S, b = bound0  →  s[0] = bound0 + J_b·Δ.
                    emit(list(-Jb_x) + list(-Jb_u), bound0)
                    # Arg rows: A = −J_a[i]·S, b = arg0[i]  →  s[1+i] = arg0[i] + J_a[i]·Δ.
                    for i in range(cc.m_arg):
                        emit(list(-Ja_x[i]) + list(-Ja_u[i]), float(arg0[i]))

        return (
            P_data,
            np.asarray(coo_vals, dtype=float),
            q,
            np.asarray(b_list, dtype=float),
        )

    # ------------------------------------------------------------------
    # Solve / unpack
    # ------------------------------------------------------------------

    def solve(self) -> PTRSolveResult:
        """Assemble the conic subproblem and dispatch to ``moreau.jax.Solver``.

        Updates the warm-start carry only when the solve status is
        :attr:`moreau.SolverStatus.Solved` or
        :attr:`moreau.SolverStatus.AlmostSolved`.

        Returns:
            PTRSolveResult: Unscaled trajectories and solver status for this
            SCP iteration.
        """
        P_data, coo_vals, q, b = self._assemble_conic()

        # Rebuild CSR from the same COO col/row arrays (with real values).
        # scipy sorts col indices within each row identically to how the
        # structural CSR was built at initialize(), so A_csr.data aligns with
        # the fixed A_col_indices passed to moreau.
        A_csr = sp.csr_matrix(
            (coo_vals, (self._coo_rows, self._coo_cols)),
            shape=(self._n_con, self.layout.n_z),
        )
        A_csr.sort_indices()

        P_j = jnp.asarray(P_data)
        A_j = jnp.asarray(A_csr.data)
        q_j = jnp.asarray(q)
        b_j = jnp.asarray(b)

        solution = self._moreau.solve(P_j, A_j, q_j, b_j, warm_start=self._warm_start)

        self._last_status = moreau.SolverStatus(int(np.asarray(self._moreau.info.status)))
        if _moreau_solve_ok(self._last_status):
            self._warm_start = solution.to_warm_start()

        z = np.asarray(solution.x)
        return self._unpack(z)

    def iteration_callback(self):
        """JAX-pure ``(state, SubproblemData) -> SubproblemSolution``.

        Composes :meth:`_assemble_conic_jax` + Moreau's jitted kernel
        + :meth:`_build_solution_jax` into a single ``@jax.jit``-decorated
        closure.

        The kernel (``moreau.jax.Solver._solve_raw``) returns
        ``(JaxSolution, JaxSolveInfo)`` and does **not** accept a warm-start
        (see the 2026-05-17 Decision Log entry in
        ``plans/solver-iteration-callbacks.md``). Moreau 0.4 removed the
        public ``moreau.jax.solver`` factory; ``Solver.solve`` drops status
        onto ``solver.info``, which does not batch under ``vmap``. Every call
        is a cold start; ``state`` is accepted only for cross-backend
        signature uniformity. Both :meth:`~openscvx.problem.Problem.solve`
        and :meth:`~openscvx.problem.Problem.solve_jax` route through this
        callback for the SCP body, so the warm-start carry isn't threaded
        on either path — threading it would require an
        :class:`AlgorithmState.moreau_carry` field (future extension in
        ``plans/jax-pure-solve.md``).

        The returned callable takes ``(state, data)``: ``state`` is the
        :class:`AlgorithmState` pytree, accepted for cross-backend signature
        uniformity but unused (the kernel takes no warm-start);
        ``data`` is the :class:`SubproblemData` pytree carrying the
        per-iteration linearization arrays, penalty weights, and boundary
        conditions.
        """
        if self.layout is None or self._settings is None:
            raise RuntimeError(
                "MoreauPTRSolver.iteration_callback() requires initialize() to "
                "have been called first."
            )

        # Public ``Solver.solve`` returns only the solution. The jitted kernel
        # it calls still returns ``(JaxSolution, JaxSolveInfo)``, which is
        # what ``vmap`` can carry as a pytree.
        solve_fn = self._moreau._solve_raw
        csr_to_coo_perm = jnp.asarray(self._csr_to_coo_perm)

        def step(state, data: SubproblemData) -> SubproblemSolution:
            del state  # The jitted kernel takes no warm-start.
            P_data, coo_vals, q, b = self._assemble_conic_jax(data)
            A_data = coo_vals[csr_to_coo_perm]
            sol, info = solve_fn(P_data, A_data, q, b)
            return self._build_solution_jax(sol, info, data)

        return jax.jit(step)

    # ------------------------------------------------------------------
    # JAX-pure assembly / unpack (used by iteration_callback)
    # ------------------------------------------------------------------

    def _assemble_conic_jax(
        self,
        data: SubproblemData,
    ) -> Tuple["jnp.ndarray", "jnp.ndarray", "jnp.ndarray", "jnp.ndarray"]:
        """JAX-pure counterpart of :meth:`_assemble_conic`.

        Returns ``(P_data, coo_vals, q, b)`` where ``coo_vals`` is emitted in
        the same COO traversal order as :meth:`_structural_pass` — the
        caller applies the precomputed ``csr_to_coo_perm`` to obtain the
        ``A_data`` array Moreau's fixed CSR layout expects.

        Mirrors ``_assemble_conic`` row-block by row-block; structural
        metadata (layout, BC types, impulsive pins, CTCS intervals) is
        Python-side and closes over the function.
        """
        L = self.layout
        sim = self._settings.sim
        N, n_x, n_u = L.N, L.n_x, L.n_u
        inv_S_x = self._inv_S_x_diag_j
        inv_S_u = self._inv_S_u_diag_j
        S_x = self._S_x_diag_j
        S_u = self._S_u_diag_j
        c_x = self._c_x_j
        c_u = self._c_u_j
        f = self._jax_dtype
        slice_imp = sim.u.slice_impulsive
        has_impulsive = slice_imp.stop > slice_imp.start
        eps = jnp.asarray(_P_DIAG_EPS, dtype=f)

        lam_prox = data.lam_prox
        lam_cost = data.lam_cost
        lam_vc = data.lam_vc
        lam_vb_nodal = data.lam_vb_nodal

        # ---------- P_data (diagonal on dx/du slots, in that order) ----------
        P_dx = (2.0 * lam_prox[:, :n_x] + eps).reshape(-1)
        P_du = (2.0 * lam_prox[:, n_x:] + eps).reshape(-1)
        P_data = jnp.concatenate([P_dx, P_du])

        # ---------- q (linear cost) ----------
        init_signs_np = np.zeros(sim.n_states, dtype=float)
        final_signs_np = np.zeros(sim.n_states, dtype=float)
        for i in range(sim.true_state_slice.start, sim.true_state_slice.stop):
            init_t = sim.x.initial_type[i]
            final_t = sim.x.final_type[i]
            if init_t == "Minimize":
                init_signs_np[i] = 1.0
            elif init_t == "Maximize":
                init_signs_np[i] = -1.0
            if final_t == "Minimize":
                final_signs_np[i] = 1.0
            elif final_t == "Maximize":
                final_signs_np[i] = -1.0
        init_signs = jnp.asarray(init_signs_np, dtype=f)
        final_signs = jnp.asarray(final_signs_np, dtype=f)
        lam_cost_arr = jnp.broadcast_to(jnp.asarray(lam_cost, dtype=f), (sim.n_states,))

        q = jnp.zeros((L.n_z,), dtype=f)
        x0_start = L.sl_x.start
        xN_start = L.sl_x.start + (N - 1) * n_x
        q = q.at[x0_start : x0_start + n_x].add(init_signs * lam_cost_arr)
        q = q.at[xN_start : xN_start + n_x].add(final_signs * lam_cost_arr)
        # L1 penalty on t_vc (epigraph of |nu|).
        q = q.at[L.sl_t_vc].add(lam_vc.reshape(-1))
        # Pos epigraph t_vb.
        for c_idx in range(L.n_nodal):
            q = q.at[L.sl_t_vb[c_idx]].add(lam_vb_nodal[:, c_idx])

        # ---------- coo_vals & b in COO traversal order ----------
        coo_blocks: List[jnp.ndarray] = []
        b_blocks: List[jnp.ndarray] = []

        # State error defs (N*n_x rows, 2 coeffs per row).
        state_err_coeffs = jnp.tile(jnp.asarray([1.0, -1.0], dtype=f), N * n_x)
        coo_blocks.append(state_err_coeffs)
        b_blocks.append((inv_S_x * (data.x_bar - c_x[None, :])).reshape(-1))

        # Control error defs (N*n_u rows, 2 coeffs per row).
        ctrl_err_coeffs = jnp.tile(jnp.asarray([1.0, -1.0], dtype=f), N * n_u)
        coo_blocks.append(ctrl_err_coeffs)
        b_blocks.append((inv_S_u * (data.u_bar - c_u[None, :])).reshape(-1))

        # Dynamics rows ((N-1) * n_x), n_per_row = 2 + n_x + 2*n_u.
        # Match _assemble_conic's emission order:
        #   [1.0 (x term)] + [-A_blk[i, :n_x]] +
        #   interleaved [-B_blk[i, j], -C_blk_with_E[i, j] for j in 0..n_u-1] +
        #   [-1.0 (nu term)]
        if has_impulsive:
            D_steps = data.D_d[1:]
            A_eff = jnp.einsum("kij,kjl->kil", D_steps, data.A_d)
            B_eff = jnp.einsum("kij,kjl->kil", D_steps, data.B_d)
            C_eff = jnp.einsum("kij,kjl->kil", D_steps, data.C_d)
        else:
            A_eff = data.A_d
            B_eff = data.B_d
            C_eff = data.C_d
        A_blk = (inv_S_x[None, :, None] * A_eff) * S_x[None, None, :]
        B_blk = (inv_S_x[None, :, None] * B_eff) * S_u[None, None, :]
        C_blk = (inv_S_x[None, :, None] * C_eff) * S_u[None, None, :]
        C_with_E = C_blk
        if has_impulsive:
            E_blk = (inv_S_x[None, :, None] * data.E_d[1:]) * S_u[None, None, :]
            imp_slice = slice(slice_imp.start, slice_imp.stop)
            C_with_E = C_with_E.at[:, :, imp_slice].add(E_blk[:, :, imp_slice])

        n_per_row = 2 + n_x + 2 * n_u
        dyn_vals = jnp.zeros((N - 1, n_x, n_per_row), dtype=f)
        dyn_vals = dyn_vals.at[:, :, 0].set(1.0)  # x[k, i]
        dyn_vals = dyn_vals.at[:, :, 1 : 1 + n_x].set(-A_blk)  # dx[kp, :]
        for j in range(n_u):
            base = 1 + n_x + 2 * j
            dyn_vals = dyn_vals.at[:, :, base].set(-B_blk[:, :, j])  # du[kp, j]
            dyn_vals = dyn_vals.at[:, :, base + 1].set(-C_with_E[:, :, j])  # du[k, j]
        dyn_vals = dyn_vals.at[:, :, -1].set(-1.0)  # nu[kp, i]
        coo_blocks.append(dyn_vals.reshape(-1))
        if has_impulsive:
            rhs_dyn = inv_S_x[None, :] * (data.x_prop_plus[1:] - c_x[None, :])
        else:
            rhs_dyn = inv_S_x[None, :] * (data.x_prop - c_x[None, :])
        b_blocks.append(rhs_dyn.reshape(-1))

        # Linearized nodal constraints (variable rows per constraint).
        for c_idx, constraint in enumerate(self._jax_constraints.nodal):
            nodes_tuple = tuple(constraint.nodes)
            if not nodes_tuple:
                continue
            nodes_arr = jnp.asarray(nodes_tuple)
            n_nodes = len(nodes_tuple)
            grad_x_vals = data.nodal_grad_x[nodes_arr, c_idx]  # (n_nodes, n_x)
            grad_u_vals = data.nodal_grad_u[nodes_arr, c_idx]  # (n_nodes, n_u)
            neg_one = jnp.full((n_nodes, 1), -1.0, dtype=f)
            nodal_vals = jnp.concatenate([grad_x_vals, grad_u_vals, neg_one], axis=1)
            coo_blocks.append(nodal_vals.reshape(-1))
            b_blocks.append(-data.nodal_g[nodes_arr, c_idx])

        # Boundary Fix rows — emit per-state, init then final, matching
        # _assemble_conic. Under impulsive control the initial Fix row also
        # carries du[0, slice_imp] coefficients.
        imp_j_list = list(range(slice_imp.start, slice_imp.stop)) if has_impulsive else []
        for i in range(sim.true_state_slice.start, sim.true_state_slice.stop):
            init_t = sim.x.initial_type[i]
            final_t = sim.x.final_type[i]
            if init_t == "Fix":
                if has_impulsive:
                    coeffs = [S_x[i]] + [-data.E_d[0, i, j] * S_u[j] for j in imp_j_list]
                    rhs_val = data.x_prop_plus[0, i] - c_x[i]
                else:
                    coeffs = [S_x[i]]
                    rhs_val = data.x_init[i] - c_x[i]
                coo_blocks.append(jnp.stack(coeffs))
                b_blocks.append(rhs_val[None])
            if final_t == "Fix":
                coo_blocks.append(jnp.stack([S_x[i]]))
                b_blocks.append((data.x_term[i] - c_x[i])[None])

        # Impulsive zero-pin equalities.
        for nodes, ctrl_slice in self._impulsive_pins:
            for _node in nodes:
                for j in range(ctrl_slice.start, ctrl_slice.stop):
                    coo_blocks.append(jnp.asarray([1.0], dtype=f))
                    b_blocks.append((-inv_S_u[j] * c_u[j])[None])

        # User ZeroConeConstraint rows (hard equality).
        # Coefficients scaled by S_x/S_u: dx_scaled = Δx_phys / S_x, so the
        # coefficient for dx_scaled[k, j] is J_x_phys[i, j] * S_x[j].
        params_user = data.params
        for cc in self._user_cone_constraints:
            if isinstance(cc, ZeroConeConstraint):
                for k in cc.nodes:
                    x_k = data.x_bar[k]
                    u_k = data.u_bar[k]
                    f0 = jnp.reshape(cc.jax_fn(x_k, u_k, k, params_user), (cc.m,))
                    J_x = (
                        jnp.reshape(
                            jax.jacfwd(cc.jax_fn, argnums=0)(x_k, u_k, k, params_user), (cc.m, n_x)
                        )
                        * S_x[None, :]
                    )
                    J_u = (
                        jnp.reshape(
                            jax.jacfwd(cc.jax_fn, argnums=1)(x_k, u_k, k, params_user), (cc.m, n_u)
                        )
                        * S_u[None, :]
                    )
                    row_vals = jnp.concatenate([J_x, J_u], axis=1)  # (cc.m, n_x+n_u)
                    coo_blocks.append(row_vals.reshape(-1))
                    b_blocks.append(-f0)

        # Uniform time grid: u[k, j] - u[k-1, j] = 0.
        if sim._uniform_time_grid:
            td = sim.time_dilation_slice
            n_tg_rows = (N - 1) * (td.stop - td.start)
            tg_coeffs = jnp.tile(jnp.asarray([1.0, -1.0], dtype=f), n_tg_rows)
            coo_blocks.append(tg_coeffs)
            b_blocks.append(jnp.zeros((n_tg_rows,), dtype=f))

        # CTCS initial: S_x[idx] * x[0, idx] = -c_x[idx].
        ctcs_start = sim.ctcs_slice.start
        ctcs_stop = sim.ctcs_slice.stop
        if ctcs_stop > ctcs_start:
            ctcs_idx_arr = jnp.arange(ctcs_start, ctcs_stop)
            coo_blocks.append(S_x[ctcs_idx_arr])
            b_blocks.append(-c_x[ctcs_idx_arr])

        # State / control box (nonneg cone). All-constant coefficients.
        x_max_sc = inv_S_x * (jnp.asarray(sim.x.max, dtype=f) - c_x)
        x_min_sc = inv_S_x * (jnp.asarray(sim.x.min, dtype=f) - c_x)
        u_max_sc = inv_S_u * (jnp.asarray(sim.u.max, dtype=f) - c_u)
        u_min_sc = inv_S_u * (jnp.asarray(sim.u.min, dtype=f) - c_u)
        # State box upper: N*n_x rows of coeff +1, RHS x_max_sc tiled.
        coo_blocks.append(jnp.ones((N * n_x,), dtype=f))
        b_blocks.append(jnp.tile(x_max_sc, N))
        # State box lower: N*n_x rows of coeff -1, RHS -x_min_sc tiled.
        coo_blocks.append(jnp.full((N * n_x,), -1.0, dtype=f))
        b_blocks.append(jnp.tile(-x_min_sc, N))
        # Control box upper
        coo_blocks.append(jnp.ones((N * n_u,), dtype=f))
        b_blocks.append(jnp.tile(u_max_sc, N))
        # Control box lower
        coo_blocks.append(jnp.full((N * n_u,), -1.0, dtype=f))
        b_blocks.append(jnp.tile(-u_min_sc, N))

        # CTCS difference rows.
        for idx, nodes in zip(
            range(ctcs_start, ctcs_stop),
            sim.ctcs_node_intervals,
        ):
            start_i = 1 if nodes[0] == 0 else nodes[0]
            scale = S_x[idx]
            x_max_un = float(sim.x.max[idx])
            for _ in range(start_i, nodes[1]):
                # +direction: emission order [x[i], x[i-1]] = [scale, -scale]
                coo_blocks.append(jnp.stack([scale, -scale]))
                b_blocks.append(jnp.asarray([x_max_un], dtype=f))
                # -direction: [-scale, scale]
                coo_blocks.append(jnp.stack([-scale, scale]))
                b_blocks.append(jnp.asarray([x_max_un], dtype=f))

        # Pos epigraph: t_vb[c, k] >= nu_vb[c, k].
        # Emission order matches _assemble_conic: [+1 (nu_vb), -1 (t_vb)].
        for _c_idx in range(L.n_nodal):
            coeffs_block = jnp.tile(jnp.asarray([1.0, -1.0], dtype=f), N)
            coo_blocks.append(coeffs_block)
            b_blocks.append(jnp.zeros((N,), dtype=f))

        # Pos epigraph non-negativity: t_vb[c, k] >= 0.
        for _c_idx in range(L.n_nodal):
            coo_blocks.append(jnp.full((N,), -1.0, dtype=f))
            b_blocks.append(jnp.zeros((N,), dtype=f))

        # User NonnegConeConstraint rows.
        # Jacobians scaled by S_x/S_u for the dx_scaled / du_scaled convention.
        for cc in self._user_cone_constraints:
            if isinstance(cc, NonnegConeConstraint):
                for k in cc.nodes:
                    x_k = data.x_bar[k]
                    u_k = data.u_bar[k]
                    f0 = jnp.reshape(cc.jax_fn(x_k, u_k, k, params_user), (cc.m,))
                    J_x = (
                        jnp.reshape(
                            jax.jacfwd(cc.jax_fn, argnums=0)(x_k, u_k, k, params_user), (cc.m, n_x)
                        )
                        * S_x[None, :]
                    )
                    J_u = (
                        jnp.reshape(
                            jax.jacfwd(cc.jax_fn, argnums=1)(x_k, u_k, k, params_user), (cc.m, n_u)
                        )
                        * S_u[None, :]
                    )
                    row_vals = jnp.concatenate([J_x, J_u], axis=1)
                    coo_blocks.append(row_vals.reshape(-1))
                    b_blocks.append(-f0)

        # SOC: 2 rows per |nu| pair, coeffs [-1] each (t_vc row, then nu row).
        n_soc = 2 * (N - 1) * n_x
        soc_coeffs = jnp.full((n_soc,), -1.0, dtype=f)
        coo_blocks.append(soc_coeffs)
        b_blocks.append(jnp.zeros((n_soc,), dtype=f))

        # User SOCConstraint rows: SOC(m_arg + 1) per node.
        # Bound row:  A = −J_b·S, b = bound0  →  s[0] = b − A·z = bound0 + J_b·Δ.
        # Arg rows:   A = −J_a[i]·S, b = arg0[i].
        # Jacobians scaled by S_x/S_u to convert physical Jacobians to
        # coefficients for scaled decision variables dx_scaled / du_scaled.
        for cc in self._user_cone_constraints:
            if isinstance(cc, SOCConstraint):
                for k in cc.nodes:
                    x_k = data.x_bar[k]
                    u_k = data.u_bar[k]
                    bound0 = jnp.reshape(cc.bound_fn(x_k, u_k, k, params_user), ())
                    Jb_x = (
                        jnp.reshape(
                            jax.jacfwd(cc.bound_fn, argnums=0)(x_k, u_k, k, params_user), (n_x,)
                        )
                        * S_x
                    )
                    Jb_u = (
                        jnp.reshape(
                            jax.jacfwd(cc.bound_fn, argnums=1)(x_k, u_k, k, params_user), (n_u,)
                        )
                        * S_u
                    )
                    arg0 = jnp.reshape(cc.arg_fn(x_k, u_k, k, params_user), (cc.m_arg,))
                    Ja_x = (
                        jnp.reshape(
                            jax.jacfwd(cc.arg_fn, argnums=0)(x_k, u_k, k, params_user),
                            (cc.m_arg, n_x),
                        )
                        * S_x[None, :]
                    )
                    Ja_u = (
                        jnp.reshape(
                            jax.jacfwd(cc.arg_fn, argnums=1)(x_k, u_k, k, params_user),
                            (cc.m_arg, n_u),
                        )
                        * S_u[None, :]
                    )
                    # Bound row A coeffs (negated, concatenated x then u).
                    bound_A = jnp.concatenate([-Jb_x, -Jb_u])  # (n_x + n_u,)
                    coo_blocks.append(bound_A)
                    b_blocks.append(bound0[None])
                    # Arg rows A coeffs (negated).
                    arg_A = jnp.concatenate([-Ja_x, -Ja_u], axis=1)  # (m_arg, n_x+n_u)
                    coo_blocks.append(arg_A.reshape(-1))
                    b_blocks.append(arg0)

        coo_vals = jnp.concatenate(coo_blocks) if coo_blocks else jnp.zeros((0,), dtype=f)
        b_vec = jnp.concatenate(b_blocks) if b_blocks else jnp.zeros((0,), dtype=f)
        return P_data, coo_vals, q, b_vec

    def _build_solution_jax(
        self,
        sol,
        info,
        data: SubproblemData,
    ) -> SubproblemSolution:
        """Unpack ``(JaxSolution, JaxSolveInfo)`` into a :class:`SubproblemSolution`.

        Mirrors :meth:`_unpack`: scaled-to-physical trajectories, virtual
        controls in their natural orientation, ``nu_vb`` stacked to
        ``(N, n_nodal)``. ``status_code`` is derived from ``info.status`` via
        :func:`_moreau_status_to_code`.
        """
        L = self.layout
        N, n_x, n_u = L.N, L.n_x, L.n_u
        f = self._jax_dtype
        z = sol.x

        x_scaled = z[L.sl_x].reshape(N, n_x)
        u_scaled = z[L.sl_u].reshape(N, n_u)
        x = x_scaled * self._S_x_diag_j[None, :] + self._c_x_j[None, :]
        u = u_scaled * self._S_u_diag_j[None, :] + self._c_u_j[None, :]
        nu = z[L.sl_nu].reshape(N - 1, n_x)
        if L.n_nodal:
            nu_vb = jnp.stack([z[sl] for sl in L.sl_nu_vb], axis=-1)
        else:
            nu_vb = jnp.zeros((N, 0), dtype=f)

        cost = self._reconstruct_cost_jax(z, data)
        status_code = _moreau_status_to_code(info.status)

        return SubproblemSolution(
            x=x,
            u=u,
            nu=nu,
            nu_vb=nu_vb,
            nu_vb_cross=jnp.zeros((0,), dtype=f),
            cost=cost,
            status_code=status_code,
        )

    def _reconstruct_cost_jax(
        self,
        z: "jnp.ndarray",
        data: SubproblemData,
    ) -> "jnp.ndarray":
        """JAX-pure mirror of :meth:`_reconstruct_cost`."""
        L = self.layout
        sim = self._settings.sim
        N, n_x = L.N, L.n_x
        f = self._jax_dtype
        lam_prox = data.lam_prox
        lam_cost_arr = jnp.broadcast_to(jnp.asarray(data.lam_cost, dtype=f), (sim.n_states,))
        lam_vc = data.lam_vc
        lam_vb_nodal = data.lam_vb_nodal

        dx = z[L.sl_dx].reshape(N, n_x)
        du = z[L.sl_du].reshape(N, L.n_u)
        x_scaled = z[L.sl_x].reshape(N, n_x)
        t_vc = z[L.sl_t_vc].reshape(N - 1, n_x)

        cost = jnp.sum(lam_prox[:, :n_x] * dx**2) + jnp.sum(lam_prox[:, n_x:] * du**2)
        for i in range(sim.true_state_slice.start, sim.true_state_slice.stop):
            init_t = sim.x.initial_type[i]
            final_t = sim.x.final_type[i]
            if init_t == "Minimize":
                cost = cost + lam_cost_arr[i] * x_scaled[0, i]
            elif init_t == "Maximize":
                cost = cost - lam_cost_arr[i] * x_scaled[0, i]
            if final_t == "Minimize":
                cost = cost + lam_cost_arr[i] * x_scaled[-1, i]
            elif final_t == "Maximize":
                cost = cost - lam_cost_arr[i] * x_scaled[-1, i]
        cost = cost + jnp.sum(lam_vc * t_vc)
        for c_idx in range(L.n_nodal):
            t_vb = z[L.sl_t_vb[c_idx]]
            cost = cost + jnp.dot(lam_vb_nodal[:, c_idx], t_vb)
        return cost.astype(f)

    def _unpack(self, z: np.ndarray) -> PTRSolveResult:
        """Map the flat solution vector into a :class:`PTRSolveResult`.

        Args:
            z: Primal solution from Moreau, length ``layout.n_z``.

        Returns:
            PTRSolveResult: Unscaled ``x`` / ``u`` trajectories, slacks, cost,
            and ``"optimal"`` or ``"infeasible"`` status.
        """
        L = self.layout
        N, n_x, n_u = L.N, L.n_x, L.n_u

        x_scaled = z[L.sl_x].reshape(N, n_x)
        u_scaled = z[L.sl_u].reshape(N, n_u)
        x = x_scaled * self._S_x_diag[None, :] + self._c_x[None, :]
        u = u_scaled * self._S_u_diag[None, :] + self._c_u[None, :]

        nu = z[L.sl_nu].reshape(N - 1, n_x)
        nu_vb = [np.asarray(z[sl]) for sl in L.sl_nu_vb]
        nu_vb_cross: List[float] = []

        is_ok = _moreau_solve_ok(self._last_status)
        status = "optimal" if is_ok else "infeasible"

        cost = self._reconstruct_cost(z)

        return PTRSolveResult(
            x=x,
            u=u,
            nu=nu,
            nu_vb=nu_vb,
            nu_vb_cross=nu_vb_cross,
            cost=cost,
            status=status,
        )

    def _reconstruct_cost(self, z: np.ndarray) -> float:
        """Recompute the PTR objective at ``z`` from stored penalty weights.

        Uses epigraph variables ``t_vc`` / ``t_vb`` (equal to ``|nu|`` /
        ``max(nu_vb, 0)`` at optimality) instead of absolute values or
        positive parts.

        Args:
            z: Primal solution vector.

        Returns:
            Scalar PTR cost at ``z``.
        """
        L = self.layout
        settings = self._settings
        N, n_x = L.N, L.n_x
        lam_prox = self._pen["lam_prox"]
        lam_cost_arr = np.broadcast_to(self._pen["lam_cost"], (settings.sim.n_states,))
        lam_vc = self._pen["lam_vc"]
        lam_vb_nodal = self._pen["lam_vb_nodal"]

        dx = z[L.sl_dx].reshape(N, n_x)
        du = z[L.sl_du].reshape(N, L.n_u)
        x = z[L.sl_x].reshape(N, n_x)
        t_vc = z[L.sl_t_vc].reshape(N - 1, n_x)

        cost = float(np.sum(lam_prox[:, :n_x] * dx**2) + np.sum(lam_prox[:, n_x:] * du**2))
        for i in range(settings.sim.true_state_slice.start, settings.sim.true_state_slice.stop):
            init_t = settings.sim.x.initial_type[i]
            final_t = settings.sim.x.final_type[i]
            if init_t == "Minimize":
                cost += float(lam_cost_arr[i] * x[0, i])
            elif init_t == "Maximize":
                cost -= float(lam_cost_arr[i] * x[0, i])
            if final_t == "Minimize":
                cost += float(lam_cost_arr[i] * x[-1, i])
            elif final_t == "Maximize":
                cost -= float(lam_cost_arr[i] * x[-1, i])
        cost += float(np.sum(lam_vc * t_vc))
        for c_idx in range(L.n_nodal):
            t_vb = z[L.sl_t_vb[c_idx]]
            cost += float(np.dot(lam_vb_nodal[:, c_idx], t_vb))
        return cost

    # ------------------------------------------------------------------
    # Misc API
    # ------------------------------------------------------------------

    def get_stats(self) -> dict:
        """Return conic problem dimensions for the diagnostics summary box.

        Returns:
            dict: Keys ``n_variables``, ``n_parameters`` (always 0), and
            ``n_constraints``.
        """
        if self.layout is None:
            return {"n_variables": 0, "n_parameters": 0, "n_constraints": 0}
        return {
            "n_variables": self.layout.n_z,
            "n_parameters": 0,
            "n_constraints": self._n_con if self._n_con else -1,
        }

    def citation(self) -> List[str]:
        """Return BibTeX citation entries for Moreau.

        Returns:
            list[str]: BibTeX strings for inclusion in a bibliography.
        """
        return [
            r"""@software{moreau2024,
  title={Moreau: GPU-Accelerated Conic Optimization Solver},
  author={{Moreau Contributors}},
  url={https://docs.moreau.so},
  year={2024}
}"""
        ]
citation() -> List[str]

Return BibTeX citation entries for Moreau.

Returns:

Type Description
List[str]

list[str]: BibTeX strings for inclusion in a bibliography.

Source code in openscvx/solvers/moreau_ptr_solver.py
    def citation(self) -> List[str]:
        """Return BibTeX citation entries for Moreau.

        Returns:
            list[str]: BibTeX strings for inclusion in a bibliography.
        """
        return [
            r"""@software{moreau2024,
  title={Moreau: GPU-Accelerated Conic Optimization Solver},
  author={{Moreau Contributors}},
  url={https://docs.moreau.so},
  year={2024}
}"""
        ]
create_variables(N: int, x_unified: UnifiedState, u_unified: UnifiedControl, jax_constraints: LoweredJaxConstraints, dynamics_sparsity: Optional[tuple] = None, constraint_sparsity: Optional[list] = None) -> None

Compute scaling matrices and the static conic decision-vector layout.

Sparsity hints are accepted for interface symmetry with :class:openscvx.solvers.cvxpy_ptr_solver.CVXPyPTRSolver but ignored; numeric values are filled into a fixed CSR structure at solve time.

Parameters:

Name Type Description Default
N int

Number of discretization nodes.

required
x_unified UnifiedState

Unified state bounds and scaling metadata.

required
u_unified UnifiedControl

Unified control bounds and scaling metadata.

required
jax_constraints LoweredJaxConstraints

Lowered JAX constraints (nodal structure only).

required
dynamics_sparsity Optional[tuple]

Ignored.

None
constraint_sparsity Optional[list]

Ignored.

None
Source code in openscvx/solvers/moreau_ptr_solver.py
def create_variables(
    self,
    N: int,
    x_unified: "UnifiedState",
    u_unified: "UnifiedControl",
    jax_constraints: "LoweredJaxConstraints",
    dynamics_sparsity: Optional[tuple] = None,
    constraint_sparsity: Optional[list] = None,
) -> None:
    """Compute scaling matrices and the static conic decision-vector layout.

    Sparsity hints are accepted for interface symmetry with
    :class:`openscvx.solvers.cvxpy_ptr_solver.CVXPyPTRSolver` but ignored;
    numeric values are filled into a fixed CSR structure at solve time.

    Args:
        N: Number of discretization nodes.
        x_unified: Unified state bounds and scaling metadata.
        u_unified: Unified control bounds and scaling metadata.
        jax_constraints: Lowered JAX constraints (nodal structure only).
        dynamics_sparsity: Ignored.
        constraint_sparsity: Ignored.
    """
    del dynamics_sparsity, constraint_sparsity

    n_x = len(x_unified.max)
    n_u = len(u_unified.max)

    S_x, c_x = self._scaling(x_unified)
    S_u, c_u = self._scaling(u_unified)

    self._S_x = S_x
    self._c_x = c_x
    self._S_u = S_u
    self._c_u = c_u
    self._S_x_diag = np.diag(S_x)
    self._S_u_diag = np.diag(S_u)
    self._inv_S_x_diag = 1.0 / self._S_x_diag
    self._inv_S_u_diag = 1.0 / self._S_u_diag

    # JAX-side scaling diagonals for ``iteration_callback``. The dtype
    # tracks the global ``jax_enable_x64`` setting so the assembled
    # ``(P_data, A_data, q, b)`` lands in the dtype Moreau's functional
    # solver expects.
    f = jnp.float64 if jax.config.read("jax_enable_x64") else jnp.float32
    self._S_x_diag_j = jnp.asarray(self._S_x_diag, dtype=f)
    self._S_u_diag_j = jnp.asarray(self._S_u_diag, dtype=f)
    self._inv_S_x_diag_j = jnp.asarray(self._inv_S_x_diag, dtype=f)
    self._inv_S_u_diag_j = jnp.asarray(self._inv_S_u_diag, dtype=f)
    self._c_x_j = jnp.asarray(self._c_x, dtype=f)
    self._c_u_j = jnp.asarray(self._c_u, dtype=f)
    self._jax_dtype = f

    if any(c.is_equality for c in jax_constraints.nodal):
        raise NotImplementedError(
            "MoreauPTRSolver does not support L1-penalized equality "
            "constraints. Use CVXPyPTRSolver."
        )

    self.layout = _ConicLayout(N=N, n_x=n_x, n_u=n_u, n_nodal=len(jax_constraints.nodal))
    self._jax_constraints = jax_constraints
    self._x_unified = x_unified
get_stats() -> dict

Return conic problem dimensions for the diagnostics summary box.

Returns:

Name Type Description
dict dict

Keys n_variables, n_parameters (always 0), and

dict

n_constraints.

Source code in openscvx/solvers/moreau_ptr_solver.py
def get_stats(self) -> dict:
    """Return conic problem dimensions for the diagnostics summary box.

    Returns:
        dict: Keys ``n_variables``, ``n_parameters`` (always 0), and
        ``n_constraints``.
    """
    if self.layout is None:
        return {"n_variables": 0, "n_parameters": 0, "n_constraints": 0}
    return {
        "n_variables": self.layout.n_z,
        "n_parameters": 0,
        "n_constraints": self._n_con if self._n_con else -1,
    }
initialize(lowered: LoweredProblem, settings: Config) -> None

Build the static conic structure and construct moreau.jax.Solver.

Validates the supported constraint subset, enumerates all A-matrix nonzero positions (fixed CSR structure), builds a :class:moreau.Cones spec, and constructs :class:moreau.jax.Solver. Numeric values in A, b, P, and q are filled at each :meth:solve call.

Parameters:

Name Type Description Default
lowered LoweredProblem

Lowered problem with constraint structure.

required
settings Config

Problem configuration.

required

Raises:

Type Description
RuntimeError

If :meth:create_variables was not called first.

NotImplementedError

If cross-node constraints are present.

Source code in openscvx/solvers/moreau_ptr_solver.py
def initialize(self, lowered: "LoweredProblem", settings: "Config") -> None:
    """Build the static conic structure and construct ``moreau.jax.Solver``.

    Validates the supported constraint subset, enumerates all A-matrix
    nonzero positions (fixed CSR structure), builds a :class:`moreau.Cones`
    spec, and constructs :class:`moreau.jax.Solver`. Numeric values in
    ``A``, ``b``, ``P``, and ``q`` are filled at each :meth:`solve` call.

    Args:
        lowered: Lowered problem with constraint structure.
        settings: Problem configuration.

    Raises:
        RuntimeError: If :meth:`create_variables` was not called first.
        NotImplementedError: If cross-node constraints are present.
    """
    if self.layout is None:
        raise RuntimeError(
            "MoreauPTRSolver.initialize() called before create_variables(). "
            "Call create_variables() first."
        )

    if lowered.jax_constraints.cross_node:
        raise NotImplementedError(
            "MoreauPTRSolver does not yet support cross-node constraints "
            f"({len(lowered.jax_constraints.cross_node)} defined). "
            "Use CVXPyPTRSolver."
        )

    self._settings = settings
    # Reset warm-start on new initialization (problem structure may change).
    self._warm_start = None

    # Enumerate all (row, col) pairs in the A matrix (structural pass).
    coo_rows, coo_cols, n_eq, n_nn, soc_dims = self._structural_pass(settings)
    n_soc = sum(soc_dims)
    self._n_con = n_eq + n_nn + n_soc
    self._coo_rows = np.asarray(coo_rows, dtype=np.int32)
    self._coo_cols = np.asarray(coo_cols, dtype=np.int32)

    # Build CSR for A from the structural COO.
    n_coo = len(coo_rows)
    if n_coo > 0:
        A_struct = sp.csr_matrix(
            (np.ones(n_coo), (coo_rows, coo_cols)),
            shape=(self._n_con, self.layout.n_z),
        )
        A_struct.sort_indices()
    else:
        A_struct = sp.csr_matrix((self._n_con, self.layout.n_z))
    A_indptr = np.asarray(A_struct.indptr, dtype=np.int32)
    A_indices = np.asarray(A_struct.indices, dtype=np.int32)
    self._A_indptr = A_indptr
    self._A_indices = A_indices

    # Precompute the COO→CSR permutation so the JAX assembly can emit
    # ``coo_vals`` in COO traversal order (matching ``_structural_pass``)
    # and then ``A_data = coo_vals[csr_to_coo_perm]`` matches what
    # ``solve_qp_primal``/Moreau's ``solve_fn`` expects under the fixed
    # ``A_col_indices``. NumPy ``solve()`` keeps using scipy's sort path;
    # this permutation is consumed only by ``_assemble_conic_jax``.
    if n_coo > 0:
        A_pos = sp.csr_matrix(
            (np.arange(n_coo, dtype=np.int32), (coo_rows, coo_cols)),
            shape=(self._n_con, self.layout.n_z),
        )
        A_pos.sort_indices()
        self._csr_to_coo_perm = np.asarray(A_pos.data, dtype=np.int32)
    else:
        self._csr_to_coo_perm = np.zeros((0,), dtype=np.int32)

    # Build CSR for P (diagonal on dx/du slots only).
    L = self.layout
    N, n_x = L.N, L.n_x
    dx_cols = np.arange(L.sl_dx.start, L.sl_dx.stop, dtype=np.int32)
    du_cols = np.arange(L.sl_du.start, L.sl_du.stop, dtype=np.int32)
    self._P_diag_slots = np.concatenate([dx_cols, du_cols])
    self._P_n_dx = N * n_x  # boundary between dx and du in P_data

    # P is diagonal: for each slot col, the single nonzero is P[col, col].
    P_indptr = np.zeros(L.n_z + 1, dtype=np.int32)
    for col in self._P_diag_slots:
        P_indptr[col + 1] = 1
    P_indptr = np.cumsum(P_indptr)
    P_indices = self._P_diag_slots  # diagonal → col index == row index

    # Construct moreau.Cones spec.
    cones = moreau.Cones(
        num_zero_cones=n_eq,
        num_nonneg_cones=n_nn,
        so_cone_dims=soc_dims,
    )

    # Build moreau.Settings from solver_args.
    moreau_settings = _build_moreau_settings(self.solver_args)

    self._moreau = _MoreauJaxSolver(
        n=L.n_z,
        m=self._n_con,
        P_row_offsets=jnp.array(P_indptr),
        P_col_indices=jnp.array(P_indices),
        A_row_offsets=jnp.array(A_indptr),
        A_col_indices=jnp.array(A_indices),
        cones=cones,
        settings=moreau_settings,
    )
iteration_callback()

JAX-pure (state, SubproblemData) -> SubproblemSolution.

Composes :meth:_assemble_conic_jax + Moreau's jitted kernel + :meth:_build_solution_jax into a single @jax.jit-decorated closure.

The kernel (moreau.jax.Solver._solve_raw) returns (JaxSolution, JaxSolveInfo) and does not accept a warm-start (see the 2026-05-17 Decision Log entry in plans/solver-iteration-callbacks.md). Moreau 0.4 removed the public moreau.jax.solver factory; Solver.solve drops status onto solver.info, which does not batch under vmap. Every call is a cold start; state is accepted only for cross-backend signature uniformity. Both :meth:~openscvx.problem.Problem.solve and :meth:~openscvx.problem.Problem.solve_jax route through this callback for the SCP body, so the warm-start carry isn't threaded on either path — threading it would require an :class:AlgorithmState.moreau_carry field (future extension in plans/jax-pure-solve.md).

The returned callable takes (state, data): state is the :class:AlgorithmState pytree, accepted for cross-backend signature uniformity but unused (the kernel takes no warm-start); data is the :class:SubproblemData pytree carrying the per-iteration linearization arrays, penalty weights, and boundary conditions.

Source code in openscvx/solvers/moreau_ptr_solver.py
def iteration_callback(self):
    """JAX-pure ``(state, SubproblemData) -> SubproblemSolution``.

    Composes :meth:`_assemble_conic_jax` + Moreau's jitted kernel
    + :meth:`_build_solution_jax` into a single ``@jax.jit``-decorated
    closure.

    The kernel (``moreau.jax.Solver._solve_raw``) returns
    ``(JaxSolution, JaxSolveInfo)`` and does **not** accept a warm-start
    (see the 2026-05-17 Decision Log entry in
    ``plans/solver-iteration-callbacks.md``). Moreau 0.4 removed the
    public ``moreau.jax.solver`` factory; ``Solver.solve`` drops status
    onto ``solver.info``, which does not batch under ``vmap``. Every call
    is a cold start; ``state`` is accepted only for cross-backend
    signature uniformity. Both :meth:`~openscvx.problem.Problem.solve`
    and :meth:`~openscvx.problem.Problem.solve_jax` route through this
    callback for the SCP body, so the warm-start carry isn't threaded
    on either path — threading it would require an
    :class:`AlgorithmState.moreau_carry` field (future extension in
    ``plans/jax-pure-solve.md``).

    The returned callable takes ``(state, data)``: ``state`` is the
    :class:`AlgorithmState` pytree, accepted for cross-backend signature
    uniformity but unused (the kernel takes no warm-start);
    ``data`` is the :class:`SubproblemData` pytree carrying the
    per-iteration linearization arrays, penalty weights, and boundary
    conditions.
    """
    if self.layout is None or self._settings is None:
        raise RuntimeError(
            "MoreauPTRSolver.iteration_callback() requires initialize() to "
            "have been called first."
        )

    # Public ``Solver.solve`` returns only the solution. The jitted kernel
    # it calls still returns ``(JaxSolution, JaxSolveInfo)``, which is
    # what ``vmap`` can carry as a pytree.
    solve_fn = self._moreau._solve_raw
    csr_to_coo_perm = jnp.asarray(self._csr_to_coo_perm)

    def step(state, data: SubproblemData) -> SubproblemSolution:
        del state  # The jitted kernel takes no warm-start.
        P_data, coo_vals, q, b = self._assemble_conic_jax(data)
        A_data = coo_vals[csr_to_coo_perm]
        sol, info = solve_fn(P_data, A_data, q, b)
        return self._build_solution_jax(sol, info, data)

    return jax.jit(step)
solve() -> PTRSolveResult

Assemble the conic subproblem and dispatch to moreau.jax.Solver.

Updates the warm-start carry only when the solve status is :attr:moreau.SolverStatus.Solved or :attr:moreau.SolverStatus.AlmostSolved.

Returns:

Name Type Description
PTRSolveResult PTRSolveResult

Unscaled trajectories and solver status for this

PTRSolveResult

SCP iteration.

Source code in openscvx/solvers/moreau_ptr_solver.py
def solve(self) -> PTRSolveResult:
    """Assemble the conic subproblem and dispatch to ``moreau.jax.Solver``.

    Updates the warm-start carry only when the solve status is
    :attr:`moreau.SolverStatus.Solved` or
    :attr:`moreau.SolverStatus.AlmostSolved`.

    Returns:
        PTRSolveResult: Unscaled trajectories and solver status for this
        SCP iteration.
    """
    P_data, coo_vals, q, b = self._assemble_conic()

    # Rebuild CSR from the same COO col/row arrays (with real values).
    # scipy sorts col indices within each row identically to how the
    # structural CSR was built at initialize(), so A_csr.data aligns with
    # the fixed A_col_indices passed to moreau.
    A_csr = sp.csr_matrix(
        (coo_vals, (self._coo_rows, self._coo_cols)),
        shape=(self._n_con, self.layout.n_z),
    )
    A_csr.sort_indices()

    P_j = jnp.asarray(P_data)
    A_j = jnp.asarray(A_csr.data)
    q_j = jnp.asarray(q)
    b_j = jnp.asarray(b)

    solution = self._moreau.solve(P_j, A_j, q_j, b_j, warm_start=self._warm_start)

    self._last_status = moreau.SolverStatus(int(np.asarray(self._moreau.info.status)))
    if _moreau_solve_ok(self._last_status):
        self._warm_start = solution.to_warm_start()

    z = np.asarray(solution.x)
    return self._unpack(z)