@louisultra/dsh-verymath 0.0.0-stage → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (284) hide show
  1. package/CHANGELOG.md +133 -0
  2. package/LICENSE +21 -0
  3. package/NOTICE.md +35 -0
  4. package/README.md +108 -2
  5. package/README_EN.md +105 -0
  6. package/UPSTREAM.json +106 -0
  7. package/cordis.patch.yml +12 -0
  8. package/docs/capability-examples.md +581 -0
  9. package/docs/examples/README.md +32 -0
  10. package/docs/examples/bad_scan.md +10 -0
  11. package/docs/examples/broken-proof.lean +9 -0
  12. package/docs/examples/claims.md +7 -0
  13. package/docs/examples/knapsack.json +10 -0
  14. package/docs/examples/matrix.json +1 -0
  15. package/docs/examples/points.csv +21 -0
  16. package/docs/examples/qp.json +8 -0
  17. package/docs/examples/research-ws/project/GOALS.yaml +4 -0
  18. package/docs/examples/research-ws/workstreams/ws-lsa/report.md +13 -0
  19. package/docs/examples/research-ws/workstreams/ws-lsa/reviews/r1.json +1 -0
  20. package/docs/examples/research-ws/workstreams/ws-lsa/status.yaml +1 -0
  21. package/docs/examples/source.csv +4 -0
  22. package/lib/core/error.d.ts +20 -0
  23. package/lib/core/error.js +25 -0
  24. package/lib/core/gates.d.ts +42 -0
  25. package/lib/core/gates.js +217 -0
  26. package/lib/core/glossary.d.ts +101 -0
  27. package/lib/core/glossary.js +243 -0
  28. package/lib/core/graph.d.ts +118 -0
  29. package/lib/core/graph.js +460 -0
  30. package/lib/core/index.d.ts +120 -0
  31. package/lib/core/index.js +197 -0
  32. package/lib/core/paper.d.ts +163 -0
  33. package/lib/core/paper.js +73 -0
  34. package/lib/core/paths.d.ts +2 -0
  35. package/lib/core/paths.js +12 -0
  36. package/lib/core/sage.d.ts +61 -0
  37. package/lib/core/sage.js +212 -0
  38. package/lib/core/skills.d.ts +11 -0
  39. package/lib/core/skills.js +110 -0
  40. package/lib/tool/index.d.ts +21 -0
  41. package/lib/tool/index.js +1144 -0
  42. package/package.json +92 -4
  43. package/skills/after-ocr/SKILL.md +123 -0
  44. package/skills/after-ocr/references/audit-schema.md +94 -0
  45. package/skills/after-ocr/references/error-taxonomy.md +179 -0
  46. package/skills/after-ocr/scripts/merge_audit_logs.py +329 -0
  47. package/skills/after-ocr/scripts/scan_markdown_ocr.py +350 -0
  48. package/skills/after-ocr/tests/test_scripts.py +84 -0
  49. package/skills/discover-math-problems/SKILL.md +115 -0
  50. package/skills/discover-math-problems/references/artifact-contract.md +93 -0
  51. package/skills/discover-math-problems/references/autonomous-research-protocol.md +86 -0
  52. package/skills/discover-math-problems/references/conjecture-generation-protocol.md +63 -0
  53. package/skills/discover-math-problems/references/extremal-graph-variants.md +53 -0
  54. package/skills/graph-theory-paper-reading/SKILL.md +600 -0
  55. package/skills/invariant-computation/SKILL.md +169 -0
  56. package/skills/invariant-computation/examples/invariant_summary.example.json +51 -0
  57. package/skills/invariant-computation/manifest.yaml +46 -0
  58. package/skills/invariant-computation/references/INDEX.md +20 -0
  59. package/skills/invariant-computation/references/failure_modes.md +40 -0
  60. package/skills/invariant-computation/references/method_route_map.md +177 -0
  61. package/skills/invariant-computation/references/source_notes.md +19 -0
  62. package/skills/invariant-computation/references/tool_catalog.md +65 -0
  63. package/skills/invariant-computation/references/validation_checks.md +52 -0
  64. package/skills/invariant-computation/schema/invariant_summary.schema.json +260 -0
  65. package/skills/lean-formalization/SKILL.md +111 -0
  66. package/skills/lean-formalization/lean-runtime/config/env.example +5 -0
  67. package/skills/lean-formalization/lean-runtime/config/lean_agent.example.toml +28 -0
  68. package/skills/lean-formalization/lean-runtime/config/numina_runtime.example.toml +12 -0
  69. package/skills/lean-formalization/lean-runtime/examples/smoke/LocalLeanSmoke.lean +7 -0
  70. package/skills/lean-formalization/lean-runtime/prompts/complete_sorries.md +3 -0
  71. package/skills/lean-formalization/lean-runtime/prompts/formalize_statement.md +3 -0
  72. package/skills/lean-formalization/lean-runtime/prompts/prove_theorem.md +3 -0
  73. package/skills/lean-formalization/lean-runtime/prompts/repair_lean_file.md +3 -0
  74. package/skills/lean-formalization/lean-runtime/references/backend_adapter_checklist.md +36 -0
  75. package/skills/lean-formalization/lean-runtime/references/direct_lean_workflow.md +48 -0
  76. package/skills/lean-formalization/lean-runtime/references/failure_taxonomy.md +17 -0
  77. package/skills/lean-formalization/lean-runtime/references/interactive_orchestration.md +83 -0
  78. package/skills/lean-formalization/lean-runtime/references/lean_agent_capability_map.md +116 -0
  79. package/skills/lean-formalization/lean-runtime/references/lean_lsp_mcp_adapter.md +219 -0
  80. package/skills/lean-formalization/lean-runtime/references/lean_runtime_configuration.md +92 -0
  81. package/skills/lean-formalization/lean-runtime/references/numina_reverse_analysis.md +80 -0
  82. package/skills/lean-formalization/lean-runtime/references/numina_runtime.md +41 -0
  83. package/skills/lean-formalization/lean-runtime/references/numina_subagent_troubleshooting.md +77 -0
  84. package/skills/lean-formalization/lean-runtime/references/review_checklist.md +10 -0
  85. package/skills/lean-formalization/lean-runtime/references/specialist_agent_patterns.md +65 -0
  86. package/skills/lean-formalization/lean-runtime/schemas/config.schema.json +12 -0
  87. package/skills/lean-formalization/lean-runtime/schemas/result.schema.json +33 -0
  88. package/skills/lean-formalization/lean-runtime/schemas/task.schema.json +30 -0
  89. package/skills/lean-formalization/lean-runtime/scripts/ai4m_lean.py +222 -0
  90. package/skills/lean-formalization/lean-runtime/scripts/check_lean_project.py +134 -0
  91. package/skills/lean-formalization/lean-runtime/scripts/common.py +296 -0
  92. package/skills/lean-formalization/lean-runtime/scripts/configure_lean.py +222 -0
  93. package/skills/lean-formalization/lean-runtime/scripts/detect_sorry.py +49 -0
  94. package/skills/lean-formalization/lean-runtime/scripts/direct_task.py +100 -0
  95. package/skills/lean-formalization/lean-runtime/scripts/extract_minimal_failure.py +74 -0
  96. package/skills/lean-formalization/lean-runtime/scripts/numina_runtime.py +414 -0
  97. package/skills/lean-formalization/lean-runtime/scripts/smoke_test.py +75 -0
  98. package/skills/lean-formalization/lean-runtime/scripts/tool_status.py +79 -0
  99. package/skills/lean-formalization/lean-runtime/scripts/validate_patch.py +81 -0
  100. package/skills/lean-formalization/lean-runtime/scripts/verify_delivery.py +484 -0
  101. package/skills/lean-formalization/lean-runtime/tests/fixtures/after_bad.lean +4 -0
  102. package/skills/lean-formalization/lean-runtime/tests/fixtures/after_statement_changed.lean +4 -0
  103. package/skills/lean-formalization/lean-runtime/tests/fixtures/before.lean +4 -0
  104. package/skills/lean-formalization/lean-runtime/tests/fixtures/failure.lean +7 -0
  105. package/skills/lean-formalization/lean-runtime/tests/test_check_lean_project.py +59 -0
  106. package/skills/lean-formalization/lean-runtime/tests/test_cli.py +377 -0
  107. package/skills/lean-formalization/lean-runtime/tests/test_common_config.py +84 -0
  108. package/skills/lean-formalization/lean-runtime/tests/test_configure_lean.py +138 -0
  109. package/skills/lean-formalization/lean-runtime/tests/test_detect_sorry.py +24 -0
  110. package/skills/lean-formalization/lean-runtime/tests/test_direct_task.py +69 -0
  111. package/skills/lean-formalization/lean-runtime/tests/test_numina_runtime.py +168 -0
  112. package/skills/lean-formalization/lean-runtime/tests/test_validate_patch.py +29 -0
  113. package/skills/lean-setup/SKILL.md +99 -0
  114. package/skills/least-squares/README.md +85 -0
  115. package/skills/least-squares/SKILL.md +613 -0
  116. package/skills/least-squares/examples.md +380 -0
  117. package/skills/math-beamer/SKILL.md +325 -0
  118. package/skills/math-beamer/references/build-and-layout-audit.md +63 -0
  119. package/skills/math-beamer/references/math-domain-patterns.md +56 -0
  120. package/skills/math-beamer/references/template-policy.md +43 -0
  121. package/skills/math-beamer/references/template-source-index.md +51 -0
  122. package/skills/math-beamer/templates/catalog.yaml +235 -0
  123. package/skills/math-beamer/templates/packs/algebra-number-theory-talk/main.tex +45 -0
  124. package/skills/math-beamer/templates/packs/algebra-number-theory-talk/template.yaml +9 -0
  125. package/skills/math-beamer/templates/packs/algorithm-talk/main.tex +43 -0
  126. package/skills/math-beamer/templates/packs/algorithm-talk/template.yaml +9 -0
  127. package/skills/math-beamer/templates/packs/analysis-core-talk/main.tex +49 -0
  128. package/skills/math-beamer/templates/packs/analysis-core-talk/template.yaml +19 -0
  129. package/skills/math-beamer/templates/packs/backup-heavy-talk/main.tex +40 -0
  130. package/skills/math-beamer/templates/packs/backup-heavy-talk/template.yaml +9 -0
  131. package/skills/math-beamer/templates/packs/beamerposter-a0/main.tex +45 -0
  132. package/skills/math-beamer/templates/packs/beamerposter-a0/template.yaml +12 -0
  133. package/skills/math-beamer/templates/packs/combinatorics-graph-talk/main.tex +53 -0
  134. package/skills/math-beamer/templates/packs/combinatorics-graph-talk/template.yaml +18 -0
  135. package/skills/math-beamer/templates/packs/control-systems-talk/main.tex +51 -0
  136. package/skills/math-beamer/templates/packs/control-systems-talk/template.yaml +18 -0
  137. package/skills/math-beamer/templates/packs/course-lecture-zh/main.tex +43 -0
  138. package/skills/math-beamer/templates/packs/course-lecture-zh/template.yaml +9 -0
  139. package/skills/math-beamer/templates/packs/data-experiment-results/main.tex +45 -0
  140. package/skills/math-beamer/templates/packs/data-experiment-results/template.yaml +9 -0
  141. package/skills/math-beamer/templates/packs/dynamical-systems-talk/main.tex +42 -0
  142. package/skills/math-beamer/templates/packs/dynamical-systems-talk/template.yaml +9 -0
  143. package/skills/math-beamer/templates/packs/geometry-topology-talk/main.tex +43 -0
  144. package/skills/math-beamer/templates/packs/geometry-topology-talk/template.yaml +9 -0
  145. package/skills/math-beamer/templates/packs/information-coding-crypto-talk/main.tex +49 -0
  146. package/skills/math-beamer/templates/packs/information-coding-crypto-talk/template.yaml +18 -0
  147. package/skills/math-beamer/templates/packs/logic-foundations-category-talk/main.tex +51 -0
  148. package/skills/math-beamer/templates/packs/logic-foundations-category-talk/template.yaml +18 -0
  149. package/skills/math-beamer/templates/packs/numerical-analysis-talk/main.tex +51 -0
  150. package/skills/math-beamer/templates/packs/numerical-analysis-talk/template.yaml +9 -0
  151. package/skills/math-beamer/templates/packs/optimization-talk/main.tex +58 -0
  152. package/skills/math-beamer/templates/packs/optimization-talk/template.yaml +9 -0
  153. package/skills/math-beamer/templates/packs/pde-analysis-talk/main.tex +49 -0
  154. package/skills/math-beamer/templates/packs/pde-analysis-talk/template.yaml +9 -0
  155. package/skills/math-beamer/templates/packs/probability-statistics-talk/main.tex +52 -0
  156. package/skills/math-beamer/templates/packs/probability-statistics-talk/template.yaml +9 -0
  157. package/skills/math-beamer/templates/packs/reading-group-paper/main.tex +46 -0
  158. package/skills/math-beamer/templates/packs/reading-group-paper/template.yaml +9 -0
  159. package/skills/math-beamer/templates/packs/seminar-minimal-en/main.tex +60 -0
  160. package/skills/math-beamer/templates/packs/seminar-minimal-en/template.yaml +13 -0
  161. package/skills/math-beamer/templates/packs/seminar-minimal-zh/main.tex +60 -0
  162. package/skills/math-beamer/templates/packs/seminar-minimal-zh/template.yaml +13 -0
  163. package/skills/math-beamer/templates/packs/theorem-proof-talk/main.tex +60 -0
  164. package/skills/math-beamer/templates/packs/theorem-proof-talk/template.yaml +9 -0
  165. package/skills/math-beamer/templates/packs/thesis-defense/main.tex +42 -0
  166. package/skills/math-beamer/templates/packs/thesis-defense/template.yaml +9 -0
  167. package/skills/math-beamer/templates/packs/workshop-tutorial/main.tex +32 -0
  168. package/skills/math-beamer/templates/packs/workshop-tutorial/template.yaml +9 -0
  169. package/skills/math-beamer/templates/preview-gallery.md +32 -0
  170. package/skills/math-beamer/templates/previews/algebra-number-theory-talk-content.png +0 -0
  171. package/skills/math-beamer/templates/previews/algebra-number-theory-talk-cover.png +0 -0
  172. package/skills/math-beamer/templates/previews/algorithm-talk-content.png +0 -0
  173. package/skills/math-beamer/templates/previews/algorithm-talk-cover.png +0 -0
  174. package/skills/math-beamer/templates/previews/analysis-core-talk-content.png +0 -0
  175. package/skills/math-beamer/templates/previews/analysis-core-talk-cover.png +0 -0
  176. package/skills/math-beamer/templates/previews/backup-heavy-talk-content.png +0 -0
  177. package/skills/math-beamer/templates/previews/backup-heavy-talk-cover.png +0 -0
  178. package/skills/math-beamer/templates/previews/beamerposter-a0-content.png +0 -0
  179. package/skills/math-beamer/templates/previews/beamerposter-a0-cover.png +0 -0
  180. package/skills/math-beamer/templates/previews/combinatorics-graph-talk-content.png +0 -0
  181. package/skills/math-beamer/templates/previews/combinatorics-graph-talk-cover.png +0 -0
  182. package/skills/math-beamer/templates/previews/control-systems-talk-content.png +0 -0
  183. package/skills/math-beamer/templates/previews/control-systems-talk-cover.png +0 -0
  184. package/skills/math-beamer/templates/previews/course-lecture-zh-content.png +0 -0
  185. package/skills/math-beamer/templates/previews/course-lecture-zh-cover.png +0 -0
  186. package/skills/math-beamer/templates/previews/data-experiment-results-content.png +0 -0
  187. package/skills/math-beamer/templates/previews/data-experiment-results-cover.png +0 -0
  188. package/skills/math-beamer/templates/previews/dynamical-systems-talk-content.png +0 -0
  189. package/skills/math-beamer/templates/previews/dynamical-systems-talk-cover.png +0 -0
  190. package/skills/math-beamer/templates/previews/geometry-topology-talk-content.png +0 -0
  191. package/skills/math-beamer/templates/previews/geometry-topology-talk-cover.png +0 -0
  192. package/skills/math-beamer/templates/previews/information-coding-crypto-talk-content.png +0 -0
  193. package/skills/math-beamer/templates/previews/information-coding-crypto-talk-cover.png +0 -0
  194. package/skills/math-beamer/templates/previews/logic-foundations-category-talk-content.png +0 -0
  195. package/skills/math-beamer/templates/previews/logic-foundations-category-talk-cover.png +0 -0
  196. package/skills/math-beamer/templates/previews/numerical-analysis-talk-content.png +0 -0
  197. package/skills/math-beamer/templates/previews/numerical-analysis-talk-cover.png +0 -0
  198. package/skills/math-beamer/templates/previews/optimization-talk-content.png +0 -0
  199. package/skills/math-beamer/templates/previews/optimization-talk-cover.png +0 -0
  200. package/skills/math-beamer/templates/previews/pde-analysis-talk-content.png +0 -0
  201. package/skills/math-beamer/templates/previews/pde-analysis-talk-cover.png +0 -0
  202. package/skills/math-beamer/templates/previews/probability-statistics-talk-content.png +0 -0
  203. package/skills/math-beamer/templates/previews/probability-statistics-talk-cover.png +0 -0
  204. package/skills/math-beamer/templates/previews/reading-group-paper-content.png +0 -0
  205. package/skills/math-beamer/templates/previews/reading-group-paper-cover.png +0 -0
  206. package/skills/math-beamer/templates/previews/seminar-minimal-en-content.png +0 -0
  207. package/skills/math-beamer/templates/previews/seminar-minimal-en-cover.png +0 -0
  208. package/skills/math-beamer/templates/previews/seminar-minimal-zh-content.png +0 -0
  209. package/skills/math-beamer/templates/previews/seminar-minimal-zh-cover.png +0 -0
  210. package/skills/math-beamer/templates/previews/theorem-proof-talk-content.png +0 -0
  211. package/skills/math-beamer/templates/previews/theorem-proof-talk-cover.png +0 -0
  212. package/skills/math-beamer/templates/previews/thesis-defense-content.png +0 -0
  213. package/skills/math-beamer/templates/previews/thesis-defense-cover.png +0 -0
  214. package/skills/math-beamer/templates/previews/workshop-tutorial-content.png +0 -0
  215. package/skills/math-beamer/templates/previews/workshop-tutorial-cover.png +0 -0
  216. package/skills/math-beamer/templates/review-report.md +54 -0
  217. package/skills/math-beamer/templates/slide-source-ledger.md +22 -0
  218. package/skills/math-beamer/templates/source-packet.md +50 -0
  219. package/skills/math-glossary/SKILL.md +347 -0
  220. package/skills/math-glossary/references/glossary-schema.md +71 -0
  221. package/skills/math-glossary/references/glossary-usage-guide.md +176 -0
  222. package/skills/math-glossary/references/glossary-web-template.md +127 -0
  223. package/skills/math-glossary/references/glossary.schema.json +76 -0
  224. package/skills/math-glossary/references/user-manual.md +435 -0
  225. package/skills/math-glossary/requirements-ai.txt +3 -0
  226. package/skills/math-glossary/requirements.txt +3 -0
  227. package/skills/math-glossary/scripts/glossary_backup.py +42 -0
  228. package/skills/math-glossary/scripts/glossary_build.py +467 -0
  229. package/skills/math-glossary/scripts/glossary_enrich_examples.py +283 -0
  230. package/skills/math-glossary/scripts/glossary_export.py +333 -0
  231. package/skills/math-glossary/scripts/glossary_web.py +1265 -0
  232. package/skills/math-paper-reading/README.md +163 -0
  233. package/skills/math-paper-reading/SKILL.md +48 -0
  234. package/skills/math-paper-reading/agent_router.md +36 -0
  235. package/skills/math-paper-reading/references/proof_pattern_taxonomy.md +123 -0
  236. package/skills/math-paper-reading/references/quality_rubric.md +36 -0
  237. package/skills/math-paper-reading/skill_base.md +627 -0
  238. package/skills/math-paper-reading/skill_literature_search.md +866 -0
  239. package/skills/math-paper-reading/skill_paper_deep_read.md +1024 -0
  240. package/skills/math-paper-reading/skill_pathway_proof.md +718 -0
  241. package/skills/math-paper-reading/skill_reference_manager.md +746 -0
  242. package/skills/matlab-runner/SKILL.md +217 -0
  243. package/skills/matlab-runner/examples/README.md +33 -0
  244. package/skills/matlab-runner/examples/matrix_report.m +28 -0
  245. package/skills/matlab-runner/examples/plot_damped_sine.m +64 -0
  246. package/skills/matlab-runner/examples/test_vector_norm.m +12 -0
  247. package/skills/matlab-runner/references/client-setup.md +24 -0
  248. package/skills/matlab-runner/references/file-session-safety.md +86 -0
  249. package/skills/matlab-runner/references/numerical-safety.md +126 -0
  250. package/skills/matlab-runner/references/resource-safety.md +125 -0
  251. package/skills/mixed-integer-programming/SKILL.md +119 -0
  252. package/skills/mixed-integer-programming/lp-examples.md +251 -0
  253. package/skills/mixed-integer-programming/mip-examples-verified.md +118 -0
  254. package/skills/open-problem-research-pipeline/SKILL.md +76 -0
  255. package/skills/open-problem-research-pipeline/skill_literature_analysis.md +201 -0
  256. package/skills/open-problem-research-pipeline/skill_literature_proof_framework.md +206 -0
  257. package/skills/open-problem-research-pipeline/skill_literature_search.md +172 -0
  258. package/skills/open-problem-research-pipeline/skill_qskill.md +177 -0
  259. package/skills/osqp-solver/SKILL.md +245 -0
  260. package/skills/osqp-solver/references/citation.md +25 -0
  261. package/skills/osqp-solver/references/dual-infeasible-example.json +14 -0
  262. package/skills/osqp-solver/references/feasible-example.json +21 -0
  263. package/skills/osqp-solver/references/primal-infeasible-example.json +17 -0
  264. package/skills/osqp-solver/references/python-api.md +95 -0
  265. package/skills/osqp-solver/references/verification.md +94 -0
  266. package/skills/osqp-solver/scripts/check_osqp_environment.py +120 -0
  267. package/skills/osqp-solver/scripts/solve_qp.py +943 -0
  268. package/skills/paper-writing/SKILL.md +115 -0
  269. package/skills/paper-writing/skill_claim_evidence_ledger.md +55 -0
  270. package/skills/paper-writing/skill_formula_environment_and_readability.md +41 -0
  271. package/skills/paper-writing/skill_latex_build_and_layout_audit.md +73 -0
  272. package/skills/paper-writing/skill_notation_and_variable_consistency.md +42 -0
  273. package/skills/paper-writing/skill_paper_skeleton_and_logical_architecture.md +54 -0
  274. package/skills/paper-writing/skill_proof_obligation_and_assumption_audit.md +57 -0
  275. package/skills/paper-writing/templates/claim-evidence-ledger.md +23 -0
  276. package/skills/paper-writing/templates/proof-obligation-ledger.md +22 -0
  277. package/skills/paper-writing/templates/rapid-prototype-paper-skeleton.md +46 -0
  278. package/skills/paper-writing/templates/source-packet.md +37 -0
  279. package/skills/paper-writing/templates/submission-readiness.md +41 -0
  280. package/skills/proof-blueprint-review/SKILL.md +129 -0
  281. package/skills/proof-blueprint-review/references/agent-mediated-proof-protocol.md +57 -0
  282. package/skills/proof-blueprint-review/references/generation-agent.md +45 -0
  283. package/skills/proof-blueprint-review/references/proof-acceptance-contract.md +41 -0
  284. package/skills/proof-blueprint-review/references/verification-agent.md +37 -0
@@ -0,0 +1,943 @@
1
+ #!/usr/bin/env python3
2
+ """Solve and independently verify a small dense JSON quadratic program."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import contextlib
8
+ import io
9
+ import json
10
+ import math
11
+ import os
12
+ import re
13
+ import sys
14
+ import tempfile
15
+ from pathlib import Path
16
+ from typing import Any, Iterable
17
+
18
+
19
+ SCHEMA_VERSION = "osqp-solver-result-v1"
20
+ OSQP_REQUIREMENT = "osqp>=1,<2"
21
+ SUPPORTED_OSQP_MAJOR = 1
22
+ MAX_INPUT_BYTES = 32 * 1024 * 1024
23
+ MAX_DENSE_VARIABLES = 1000
24
+ MAX_DENSE_ENTRIES = 2_000_000
25
+ STATUS_BY_VALUE = {
26
+ 1: ("solved", False, "solution"),
27
+ 2: ("solved_inaccurate", True, "solution"),
28
+ 3: ("primal_infeasible", False, "primal_certificate"),
29
+ 4: ("primal_infeasible_inaccurate", True, "primal_certificate"),
30
+ 5: ("dual_infeasible", False, "dual_certificate"),
31
+ 6: ("dual_infeasible_inaccurate", True, "dual_certificate"),
32
+ 7: ("maximum_iterations_reached", False, "failure"),
33
+ 8: ("time_limit_reached", False, "failure"),
34
+ 9: ("problem_non_convex", False, "failure"),
35
+ 10: ("interrupted", False, "failure"),
36
+ 11: ("unsolved", False, "failure"),
37
+ }
38
+
39
+ BOOLEAN_SETTINGS = {
40
+ "adaptive_rho",
41
+ "polishing",
42
+ "scaled_termination",
43
+ "warm_starting",
44
+ }
45
+ INTEGER_SETTINGS = {
46
+ "adaptive_rho_interval": (0, None),
47
+ "check_termination": (0, None),
48
+ "max_iter": (1, None),
49
+ "polish_refine_iter": (1, None),
50
+ "scaling": (0, None),
51
+ }
52
+ FLOAT_SETTINGS = {
53
+ "adaptive_rho_fraction": (0.0, None, False, False),
54
+ "adaptive_rho_tolerance": (1.0, None, True, False),
55
+ "alpha": (0.0, 2.0, False, False),
56
+ "delta": (0.0, None, False, False),
57
+ "eps_abs": (0.0, None, True, False),
58
+ "eps_dual_inf": (0.0, None, False, False),
59
+ "eps_prim_inf": (0.0, None, False, False),
60
+ "eps_rel": (0.0, None, True, False),
61
+ "rho": (0.0, None, False, False),
62
+ "sigma": (0.0, None, False, False),
63
+ "time_limit": (0.0, None, False, False),
64
+ }
65
+ ALLOWED_SETTINGS = (
66
+ BOOLEAN_SETTINGS | set(INTEGER_SETTINGS) | set(FLOAT_SETTINGS) | {"verbose"}
67
+ )
68
+ ALLOWED_TOP_LEVEL_FIELDS = {"name", "P", "q", "A", "l", "u", "settings"}
69
+
70
+
71
+ class InputError(ValueError):
72
+ """Raised when the JSON problem is not a valid runner input."""
73
+
74
+
75
+ class DependencyError(RuntimeError):
76
+ """Raised when the numerical runtime is unavailable."""
77
+
78
+
79
+ def _number(value: Any, label: str, *, allow_infinity: bool = False) -> float:
80
+ if isinstance(value, bool):
81
+ raise InputError(f"{label} must be numeric, not boolean")
82
+
83
+ if isinstance(value, str) and allow_infinity:
84
+ normalized = value.strip().lower()
85
+ if normalized in {"inf", "+inf", "infinity", "+infinity"}:
86
+ return math.inf
87
+ if normalized in {"-inf", "-infinity"}:
88
+ return -math.inf
89
+
90
+ if not isinstance(value, (int, float)):
91
+ raise InputError(f"{label} must be numeric")
92
+
93
+ result = float(value)
94
+ if math.isnan(result):
95
+ raise InputError(f"{label} must not be NaN")
96
+ if not allow_infinity and not math.isfinite(result):
97
+ raise InputError(f"{label} must be finite")
98
+ return result
99
+
100
+
101
+ def _vector(raw: Any, label: str, *, allow_infinity: bool = False) -> list[float]:
102
+ if not isinstance(raw, list):
103
+ raise InputError(f"{label} must be a JSON array")
104
+ return [
105
+ _number(value, f"{label}[{index}]", allow_infinity=allow_infinity)
106
+ for index, value in enumerate(raw)
107
+ ]
108
+
109
+
110
+ def _matrix(raw: Any, label: str) -> list[list[float]]:
111
+ if not isinstance(raw, list):
112
+ raise InputError(f"{label} must be a JSON array of rows")
113
+ matrix: list[list[float]] = []
114
+ width: int | None = None
115
+ for row_index, row in enumerate(raw):
116
+ if not isinstance(row, list):
117
+ raise InputError(f"{label}[{row_index}] must be a JSON array")
118
+ parsed = [
119
+ _number(value, f"{label}[{row_index}][{column_index}]")
120
+ for column_index, value in enumerate(row)
121
+ ]
122
+ if width is None:
123
+ width = len(parsed)
124
+ elif len(parsed) != width:
125
+ raise InputError(f"{label} rows must all have the same length")
126
+ matrix.append(parsed)
127
+ return matrix
128
+
129
+
130
+ def _validate_settings(raw: Any) -> dict[str, Any]:
131
+ if raw is None:
132
+ return {"verbose": False}
133
+ if not isinstance(raw, dict):
134
+ raise InputError("settings must be a JSON object")
135
+ settings: dict[str, Any] = {}
136
+ for key, value in raw.items():
137
+ if not isinstance(key, str) or not key:
138
+ raise InputError("settings keys must be non-empty strings")
139
+ if key not in ALLOWED_SETTINGS:
140
+ allowed = ", ".join(sorted(ALLOWED_SETTINGS))
141
+ raise InputError(f"unsupported settings.{key}; allowed settings: {allowed}")
142
+
143
+ if key == "verbose":
144
+ if not isinstance(value, bool):
145
+ raise InputError("settings.verbose must be boolean")
146
+ if value:
147
+ raise InputError(
148
+ "settings.verbose=true is not supported because stdout is reserved "
149
+ "for one machine-readable JSON report"
150
+ )
151
+ settings[key] = False
152
+ elif key in BOOLEAN_SETTINGS:
153
+ if not isinstance(value, bool):
154
+ raise InputError(f"settings.{key} must be boolean")
155
+ settings[key] = value
156
+ elif key in INTEGER_SETTINGS:
157
+ if isinstance(value, bool) or not isinstance(value, int):
158
+ raise InputError(f"settings.{key} must be an integer")
159
+ lower, upper = INTEGER_SETTINGS[key]
160
+ if value < lower or (upper is not None and value > upper):
161
+ interval = f">= {lower}" if upper is None else f"in [{lower}, {upper}]"
162
+ raise InputError(f"settings.{key} must be {interval}")
163
+ settings[key] = value
164
+ else:
165
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
166
+ raise InputError(f"settings.{key} must be numeric")
167
+ number = float(value)
168
+ if not math.isfinite(number):
169
+ raise InputError(f"settings.{key} must be finite")
170
+ lower, upper, include_lower, include_upper = FLOAT_SETTINGS[key]
171
+ lower_ok = number >= lower if include_lower else number > lower
172
+ upper_ok = (
173
+ True
174
+ if upper is None
175
+ else number <= upper
176
+ if include_upper
177
+ else number < upper
178
+ )
179
+ if not lower_ok or not upper_ok:
180
+ left = "[" if include_lower else "("
181
+ right = "]" if include_upper else ")"
182
+ upper_text = "infinity" if upper is None else str(upper)
183
+ raise InputError(
184
+ f"settings.{key} must be in {left}{lower}, {upper_text}{right}"
185
+ )
186
+ settings[key] = number
187
+
188
+ if settings.get("eps_abs", 1e-3) == 0.0 and settings.get("eps_rel", 1e-3) == 0.0:
189
+ raise InputError("settings.eps_abs and settings.eps_rel cannot both be zero")
190
+ settings["verbose"] = False
191
+ return settings
192
+
193
+
194
+ def validate_problem(raw: Any) -> dict[str, Any]:
195
+ if not isinstance(raw, dict):
196
+ raise InputError("the input root must be a JSON object")
197
+ unknown = sorted(set(raw) - ALLOWED_TOP_LEVEL_FIELDS)
198
+ if unknown:
199
+ raise InputError(f"unknown top-level field(s): {', '.join(unknown)}")
200
+
201
+ missing = [key for key in ("P", "q", "A", "l", "u") if key not in raw]
202
+ if missing:
203
+ raise InputError(f"missing required field(s): {', '.join(missing)}")
204
+
205
+ q = _vector(raw["q"], "q")
206
+ if not q:
207
+ raise InputError("q must contain at least one variable")
208
+ n = len(q)
209
+ if n > MAX_DENSE_VARIABLES:
210
+ raise InputError(
211
+ f"dense runner limit exceeded: n={n}, maximum is "
212
+ f"{MAX_DENSE_VARIABLES}; use the native sparse OSQP API"
213
+ )
214
+
215
+ p_matrix = _matrix(raw["P"], "P")
216
+ if len(p_matrix) != n or any(len(row) != n for row in p_matrix):
217
+ raise InputError(f"P must have shape ({n}, {n})")
218
+
219
+ max_abs_p = max((abs(value) for row in p_matrix for value in row), default=0.0)
220
+ symmetry_tolerance = 1e-10 * max(1.0, max_abs_p)
221
+ max_asymmetry = max(
222
+ abs(p_matrix[i][j] - p_matrix[j][i])
223
+ for i in range(n)
224
+ for j in range(n)
225
+ )
226
+ if max_asymmetry > symmetry_tolerance:
227
+ raise InputError(
228
+ "P must be symmetric; "
229
+ f"max asymmetry {max_asymmetry:.3e} exceeds {symmetry_tolerance:.3e}"
230
+ )
231
+ p_matrix = [
232
+ [
233
+ 0.5
234
+ * (
235
+ p_matrix[row_index][column_index]
236
+ + p_matrix[column_index][row_index]
237
+ )
238
+ for column_index in range(n)
239
+ ]
240
+ for row_index in range(n)
241
+ ]
242
+
243
+ a_matrix = _matrix(raw["A"], "A")
244
+ if a_matrix and any(len(row) != n for row in a_matrix):
245
+ raise InputError(f"A must have {n} columns")
246
+ m = len(a_matrix)
247
+ dense_entries = n * n + m * n
248
+ if dense_entries > MAX_DENSE_ENTRIES:
249
+ raise InputError(
250
+ "dense runner limit exceeded: "
251
+ f"P and A contain {dense_entries} logical entries, maximum is "
252
+ f"{MAX_DENSE_ENTRIES}; use the native sparse OSQP API"
253
+ )
254
+
255
+ lower = _vector(raw["l"], "l", allow_infinity=True)
256
+ upper = _vector(raw["u"], "u", allow_infinity=True)
257
+ if len(lower) != m or len(upper) != m:
258
+ raise InputError(f"l and u must each have length {m}")
259
+ for index, (lo, hi) in enumerate(zip(lower, upper)):
260
+ if lo == math.inf:
261
+ raise InputError(f"l[{index}] cannot be +infinity")
262
+ if hi == -math.inf:
263
+ raise InputError(f"u[{index}] cannot be -infinity")
264
+ if lo > hi:
265
+ raise InputError(f"l[{index}] must be <= u[{index}]")
266
+
267
+ settings = _validate_settings(raw.get("settings"))
268
+ settings.setdefault("verbose", False)
269
+ return {
270
+ "name": str(raw.get("name", "unnamed-qp")),
271
+ "P": p_matrix,
272
+ "q": q,
273
+ "A": a_matrix,
274
+ "l": lower,
275
+ "u": upper,
276
+ "settings": settings,
277
+ "dimensions": {"n": n, "m": m},
278
+ "structural_checks": {
279
+ "symmetric_P": True,
280
+ "max_P_asymmetry": max_asymmetry,
281
+ "P_canonicalized": bool(max_asymmetry > 0.0),
282
+ "consistent_dimensions": True,
283
+ "ordered_bounds": True,
284
+ "dense_entries": dense_entries,
285
+ },
286
+ }
287
+
288
+
289
+ def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
290
+ result: dict[str, Any] = {}
291
+ for key, value in pairs:
292
+ if key in result:
293
+ raise InputError(f"duplicate JSON object key: {key}")
294
+ result[key] = value
295
+ return result
296
+
297
+
298
+ def load_problem(path: Path) -> dict[str, Any]:
299
+ try:
300
+ input_size = path.stat().st_size
301
+ if input_size > MAX_INPUT_BYTES:
302
+ raise InputError(
303
+ f"input file is {input_size} bytes; maximum is {MAX_INPUT_BYTES} "
304
+ "for the small dense runner"
305
+ )
306
+ raw = json.loads(
307
+ path.read_text(encoding="utf-8"),
308
+ object_pairs_hook=_unique_object,
309
+ )
310
+ except OSError as exc:
311
+ raise InputError(f"cannot read {path}: {exc}") from exc
312
+ except json.JSONDecodeError as exc:
313
+ raise InputError(f"invalid JSON in {path}: {exc}") from exc
314
+ return validate_problem(raw)
315
+
316
+
317
+ def _parse_osqp_major(version: Any) -> int | None:
318
+ if not isinstance(version, str):
319
+ return None
320
+ match = re.match(r"^\s*(\d+)(?:\.|$)", version)
321
+ if match is None:
322
+ return None
323
+ return int(match.group(1))
324
+
325
+
326
+ def load_numeric_stack() -> tuple[Any, Any, Any]:
327
+ try:
328
+ import numpy as np
329
+ import osqp
330
+ from scipy import sparse
331
+ except ModuleNotFoundError as exc:
332
+ raise DependencyError(
333
+ f"missing Python dependency {exc.name!r}; run: "
334
+ f"python3 -m pip install '{OSQP_REQUIREMENT}'"
335
+ ) from exc
336
+ version = getattr(osqp, "__version__", None)
337
+ major = _parse_osqp_major(version)
338
+ if major != SUPPORTED_OSQP_MAJOR:
339
+ shown = version if version is not None else "unknown"
340
+ raise DependencyError(
341
+ f"incompatible OSQP version {shown!r}; this runner requires "
342
+ f"{OSQP_REQUIREMENT}"
343
+ )
344
+ return np, osqp, sparse
345
+
346
+
347
+ def _norm_inf(np: Any, values: Any) -> float:
348
+ array = np.asarray(values, dtype=float)
349
+ if array.size == 0:
350
+ return 0.0
351
+ return float(np.max(np.abs(array)))
352
+
353
+
354
+ def _finite_float(value: Any) -> float | int | None:
355
+ if value is None:
356
+ return None
357
+ if isinstance(value, bool):
358
+ return int(value)
359
+ try:
360
+ number = float(value)
361
+ except (TypeError, ValueError):
362
+ return None
363
+ if not math.isfinite(number):
364
+ return None
365
+ if number.is_integer() and isinstance(value, int):
366
+ return int(value)
367
+ return number
368
+
369
+
370
+ def _array_list(np: Any, value: Any) -> list[float] | None:
371
+ if value is None:
372
+ return None
373
+ array = np.asarray(value, dtype=float).reshape(-1)
374
+ if not bool(np.all(np.isfinite(array))):
375
+ return None
376
+ return [float(item) for item in array]
377
+
378
+
379
+ def _normalized_certificate(
380
+ np: Any,
381
+ certificate: Any,
382
+ expected_size: int,
383
+ ) -> tuple[Any | None, float | None, str | None]:
384
+ if certificate is None:
385
+ return None, None, "certificate is missing"
386
+ try:
387
+ vector = np.asarray(certificate, dtype=float).reshape(-1)
388
+ except (TypeError, ValueError) as exc:
389
+ return None, None, f"certificate is not numeric: {exc}"
390
+ if vector.size != expected_size:
391
+ return (
392
+ None,
393
+ None,
394
+ f"certificate has length {vector.size}; expected {expected_size}",
395
+ )
396
+ if not bool(np.all(np.isfinite(vector))):
397
+ return None, None, "certificate contains a non-finite value"
398
+ norm = _norm_inf(np, vector)
399
+ if norm == 0.0:
400
+ return None, norm, "certificate is the zero vector"
401
+ normalized = vector / norm
402
+ if not bool(np.all(np.isfinite(normalized))):
403
+ return None, norm, "certificate normalization produced a non-finite value"
404
+ return normalized, norm, None
405
+
406
+
407
+ def _first_attribute(obj: Any, *names: str) -> Any:
408
+ for name in names:
409
+ if hasattr(obj, name):
410
+ return getattr(obj, name)
411
+ return None
412
+
413
+
414
+ def _solver_statistics(info: Any) -> dict[str, Any]:
415
+ fields = {
416
+ "objective": ("obj_val",),
417
+ "dual_objective": ("dual_obj_val",),
418
+ "primal_residual": ("prim_res", "pri_res"),
419
+ "dual_residual": ("dual_res", "dua_res"),
420
+ "duality_gap": ("duality_gap",),
421
+ "iterations": ("iter",),
422
+ "rho_updates": ("rho_updates",),
423
+ "rho_estimate": ("rho_estimate",),
424
+ "setup_time": ("setup_time",),
425
+ "solve_time": ("solve_time",),
426
+ "update_time": ("update_time",),
427
+ "polish_time": ("polish_time",),
428
+ "run_time": ("run_time",),
429
+ }
430
+ return {
431
+ output_name: _finite_float(_first_attribute(info, *source_names))
432
+ for output_name, source_names in fields.items()
433
+ }
434
+
435
+
436
+ def verify_solution(
437
+ np: Any,
438
+ problem: dict[str, Any],
439
+ p_matrix: Any,
440
+ a_matrix: Any,
441
+ x: Any,
442
+ y: Any,
443
+ min_eigenvalue: float,
444
+ psd_tolerance: float,
445
+ verify_tolerance: float,
446
+ ) -> dict[str, Any]:
447
+ q = np.asarray(problem["q"], dtype=float)
448
+ lower = np.asarray(problem["l"], dtype=float)
449
+ upper = np.asarray(problem["u"], dtype=float)
450
+ x = np.asarray(x, dtype=float).reshape(-1)
451
+ y = np.asarray(y, dtype=float).reshape(-1)
452
+ if x.size != q.size or y.size != lower.size:
453
+ return {
454
+ "kind": "solution",
455
+ "passed": False,
456
+ "reason": (
457
+ f"solution dimensions are x={x.size}, y={y.size}; expected "
458
+ f"x={q.size}, y={lower.size}"
459
+ ),
460
+ }
461
+ if not bool(np.all(np.isfinite(x))) or not bool(np.all(np.isfinite(y))):
462
+ return {
463
+ "kind": "solution",
464
+ "passed": False,
465
+ "reason": "solution contains a non-finite primal or dual value",
466
+ }
467
+ ax = a_matrix @ x
468
+
469
+ lower_violation = np.where(np.isfinite(lower), np.maximum(lower - ax, 0.0), 0.0)
470
+ upper_violation = np.where(np.isfinite(upper), np.maximum(ax - upper, 0.0), 0.0)
471
+ primal_violation = max(
472
+ _norm_inf(np, lower_violation),
473
+ _norm_inf(np, upper_violation),
474
+ )
475
+ stationarity = _norm_inf(np, p_matrix @ x + q + a_matrix.T @ y)
476
+ objective = float(0.5 * x @ (p_matrix @ x) + q @ x)
477
+
478
+ projected = np.minimum(np.maximum(ax, lower), upper)
479
+ eps_abs = float(problem["settings"].get("eps_abs", 1e-3))
480
+ eps_rel = float(problem["settings"].get("eps_rel", 1e-3))
481
+ eps_primal = eps_abs + eps_rel * max(_norm_inf(np, ax), _norm_inf(np, projected))
482
+ eps_dual = eps_abs + eps_rel * max(
483
+ _norm_inf(np, p_matrix @ x),
484
+ _norm_inf(np, a_matrix.T @ y),
485
+ _norm_inf(np, q),
486
+ )
487
+ primal_threshold = max(verify_tolerance, eps_primal)
488
+ dual_threshold = max(verify_tolerance, eps_dual)
489
+
490
+ normal_cone_violations: list[float] = []
491
+ lower_complementarity: list[float] = []
492
+ upper_complementarity: list[float] = []
493
+ for lo, hi, activity, dual in zip(lower, upper, ax, y):
494
+ lo_finite = math.isfinite(float(lo))
495
+ hi_finite = math.isfinite(float(hi))
496
+ at_lower = lo_finite and float(activity) <= float(lo) + primal_threshold
497
+ at_upper = hi_finite and float(activity) >= float(hi) - primal_threshold
498
+ dual_value = float(dual)
499
+
500
+ if at_lower and at_upper:
501
+ normal_cone_violations.append(0.0)
502
+ elif at_lower:
503
+ normal_cone_violations.append(max(dual_value, 0.0))
504
+ elif at_upper:
505
+ normal_cone_violations.append(max(-dual_value, 0.0))
506
+ else:
507
+ normal_cone_violations.append(abs(dual_value))
508
+
509
+ if lo_finite:
510
+ lower_multiplier = max(-dual_value, 0.0)
511
+ lower_slack = max(float(activity) - float(lo), 0.0)
512
+ lower_complementarity.append(lower_multiplier * lower_slack)
513
+ if hi_finite:
514
+ upper_multiplier = max(dual_value, 0.0)
515
+ upper_slack = max(float(hi) - float(activity), 0.0)
516
+ upper_complementarity.append(upper_multiplier * upper_slack)
517
+
518
+ normal_cone_violation = max(normal_cone_violations, default=0.0)
519
+ complementarity = max(
520
+ max(lower_complementarity, default=0.0),
521
+ max(upper_complementarity, default=0.0),
522
+ )
523
+ normal_cone_threshold = dual_threshold
524
+ complementarity_threshold = max(
525
+ verify_tolerance,
526
+ primal_threshold * max(1.0, _norm_inf(np, y)),
527
+ )
528
+
529
+ return {
530
+ "kind": "solution",
531
+ "passed": bool(
532
+ primal_violation <= primal_threshold
533
+ and stationarity <= dual_threshold
534
+ and normal_cone_violation <= normal_cone_threshold
535
+ and complementarity <= complementarity_threshold
536
+ and min_eigenvalue >= -psd_tolerance
537
+ ),
538
+ "primal_bound_violation_inf": primal_violation,
539
+ "stationarity_inf": stationarity,
540
+ "normal_cone_violation_inf": normal_cone_violation,
541
+ "complementarity_inf": complementarity,
542
+ "objective_recomputed": objective,
543
+ "minimum_P_eigenvalue": min_eigenvalue,
544
+ "psd_tolerance": psd_tolerance,
545
+ "primal_threshold": primal_threshold,
546
+ "dual_threshold": dual_threshold,
547
+ "normal_cone_threshold": normal_cone_threshold,
548
+ "complementarity_threshold": complementarity_threshold,
549
+ "requested_floor_tolerance": verify_tolerance,
550
+ }
551
+
552
+
553
+ def verify_primal_certificate(
554
+ np: Any,
555
+ problem: dict[str, Any],
556
+ a_matrix: Any,
557
+ certificate: Any,
558
+ verify_tolerance: float,
559
+ ) -> dict[str, Any]:
560
+ lower = np.asarray(problem["l"], dtype=float)
561
+ upper = np.asarray(problem["u"], dtype=float)
562
+ eps_certificate = float(problem["settings"].get("eps_prim_inf", 1e-4))
563
+ threshold = max(verify_tolerance, eps_certificate)
564
+ vector, certificate_norm, error = _normalized_certificate(
565
+ np, certificate, lower.size
566
+ )
567
+ if error is not None:
568
+ return {
569
+ "kind": "primal_infeasibility_certificate",
570
+ "passed": False,
571
+ "reason": error,
572
+ "certificate_norm_inf": certificate_norm,
573
+ "normalized": False,
574
+ "threshold": threshold,
575
+ }
576
+
577
+ positive = np.maximum(vector, 0.0)
578
+ negative = np.minimum(vector, 0.0)
579
+ invalid_positive_ray = np.where(np.isposinf(upper), positive, 0.0)
580
+ invalid_negative_ray = np.where(np.isneginf(lower), -negative, 0.0)
581
+ infinite_bound_violation = max(
582
+ _norm_inf(np, invalid_positive_ray),
583
+ _norm_inf(np, invalid_negative_ray),
584
+ )
585
+ finite_upper = np.isfinite(upper)
586
+ finite_lower = np.isfinite(lower)
587
+ with np.errstate(over="ignore", invalid="ignore"):
588
+ support = float(
589
+ upper[finite_upper] @ positive[finite_upper]
590
+ + lower[finite_lower] @ negative[finite_lower]
591
+ )
592
+ support_scale = float(
593
+ np.abs(upper[finite_upper]) @ positive[finite_upper]
594
+ + np.abs(lower[finite_lower]) @ (-negative[finite_lower])
595
+ )
596
+ strict_negative_margin = threshold * max(1.0, support_scale)
597
+ null_residual = _norm_inf(np, a_matrix.T @ vector)
598
+ finite_checks = all(
599
+ math.isfinite(value)
600
+ for value in (
601
+ support,
602
+ support_scale,
603
+ strict_negative_margin,
604
+ null_residual,
605
+ infinite_bound_violation,
606
+ )
607
+ )
608
+ return {
609
+ "kind": "primal_infeasibility_certificate",
610
+ "passed": bool(
611
+ finite_checks
612
+ and null_residual <= threshold
613
+ and infinite_bound_violation <= threshold
614
+ and support < -strict_negative_margin
615
+ ),
616
+ "A_transpose_v_inf": null_residual,
617
+ "support_value": _finite_float(support),
618
+ "support_scale": _finite_float(support_scale),
619
+ "infinite_bound_direction_violation_inf": infinite_bound_violation,
620
+ "certificate_norm_inf": certificate_norm,
621
+ "normalized": True,
622
+ "strict_negative_margin": _finite_float(strict_negative_margin),
623
+ "threshold": threshold,
624
+ }
625
+
626
+
627
+ def verify_dual_certificate(
628
+ np: Any,
629
+ problem: dict[str, Any],
630
+ p_matrix: Any,
631
+ a_matrix: Any,
632
+ certificate: Any,
633
+ verify_tolerance: float,
634
+ ) -> dict[str, Any]:
635
+ q = np.asarray(problem["q"], dtype=float)
636
+ lower = np.asarray(problem["l"], dtype=float)
637
+ upper = np.asarray(problem["u"], dtype=float)
638
+ eps_certificate = float(problem["settings"].get("eps_dual_inf", 1e-4))
639
+ threshold = max(verify_tolerance, eps_certificate)
640
+ vector, certificate_norm, error = _normalized_certificate(
641
+ np, certificate, q.size
642
+ )
643
+ if error is not None:
644
+ return {
645
+ "kind": "dual_infeasibility_certificate",
646
+ "passed": False,
647
+ "reason": error,
648
+ "certificate_norm_inf": certificate_norm,
649
+ "normalized": False,
650
+ "threshold": threshold,
651
+ }
652
+ a_direction = a_matrix @ vector
653
+
654
+ violations: list[float] = []
655
+ for lo, hi, direction in zip(lower, upper, a_direction):
656
+ if math.isfinite(lo) and math.isfinite(hi):
657
+ violations.append(abs(float(direction)))
658
+ elif math.isfinite(lo) and math.isposinf(hi):
659
+ violations.append(max(-float(direction), 0.0))
660
+ elif math.isneginf(lo) and math.isfinite(hi):
661
+ violations.append(max(float(direction), 0.0))
662
+ direction_violation = max(violations, default=0.0)
663
+ p_residual = _norm_inf(np, p_matrix @ vector)
664
+ with np.errstate(over="ignore", invalid="ignore"):
665
+ q_direction = float(q @ vector)
666
+ q_scale = float(np.abs(q) @ np.abs(vector))
667
+ strict_negative_margin = threshold * max(1.0, q_scale)
668
+ finite_checks = all(
669
+ math.isfinite(value)
670
+ for value in (
671
+ direction_violation,
672
+ p_residual,
673
+ q_direction,
674
+ q_scale,
675
+ strict_negative_margin,
676
+ )
677
+ )
678
+ return {
679
+ "kind": "dual_infeasibility_certificate",
680
+ "passed": bool(
681
+ finite_checks
682
+ and p_residual <= threshold
683
+ and direction_violation <= threshold
684
+ and q_direction < -strict_negative_margin
685
+ ),
686
+ "P_s_inf": p_residual,
687
+ "q_transpose_s": _finite_float(q_direction),
688
+ "q_direction_scale": _finite_float(q_scale),
689
+ "constraint_direction_violation_inf": direction_violation,
690
+ "certificate_norm_inf": certificate_norm,
691
+ "normalized": True,
692
+ "strict_negative_margin": _finite_float(strict_negative_margin),
693
+ "threshold": threshold,
694
+ }
695
+
696
+
697
+ def _payload_is_accepted(
698
+ payload_kind: str,
699
+ verification_passed: bool,
700
+ inaccurate: bool,
701
+ accept_inaccurate: bool,
702
+ ) -> bool:
703
+ return bool(
704
+ payload_kind != "failure"
705
+ and verification_passed
706
+ and (accept_inaccurate or not inaccurate)
707
+ )
708
+
709
+
710
+ def solve_problem(
711
+ problem: dict[str, Any],
712
+ *,
713
+ verify_tolerance: float,
714
+ accept_inaccurate: bool,
715
+ ) -> tuple[dict[str, Any], bool]:
716
+ np, osqp, sparse = load_numeric_stack()
717
+ p_matrix = np.asarray(problem["P"], dtype=float)
718
+ q = np.asarray(problem["q"], dtype=float)
719
+ if problem["A"]:
720
+ a_matrix = np.asarray(problem["A"], dtype=float)
721
+ else:
722
+ a_matrix = np.empty((0, problem["dimensions"]["n"]), dtype=float)
723
+ lower = np.asarray(problem["l"], dtype=float)
724
+ upper = np.asarray(problem["u"], dtype=float)
725
+
726
+ eigenvalues = np.linalg.eigvalsh(p_matrix)
727
+ min_eigenvalue = float(np.min(eigenvalues))
728
+ psd_tolerance = 1e-9 * max(1.0, _norm_inf(np, eigenvalues))
729
+ if min_eigenvalue < -psd_tolerance:
730
+ raise InputError(
731
+ "P is not positive semidefinite within the runner tolerance; "
732
+ f"minimum eigenvalue={min_eigenvalue:.6e}"
733
+ )
734
+
735
+ solver_stdout = io.StringIO()
736
+ with contextlib.redirect_stdout(solver_stdout):
737
+ model = osqp.OSQP()
738
+ model.setup(
739
+ P=sparse.csc_matrix(np.triu(p_matrix)),
740
+ q=q,
741
+ A=sparse.csc_matrix(a_matrix),
742
+ l=lower,
743
+ u=upper,
744
+ **problem["settings"],
745
+ )
746
+ result = model.solve()
747
+ status_value = int(result.info.status_val)
748
+ status_key, inaccurate, payload_kind = STATUS_BY_VALUE.get(
749
+ status_value, ("unknown", False, "failure")
750
+ )
751
+
752
+ verification: dict[str, Any] = {
753
+ "kind": "not_performed",
754
+ "passed": False,
755
+ "reason": f"status {status_key} has no accepted mathematical payload",
756
+ }
757
+ solution: dict[str, Any] | None = None
758
+ certificate: dict[str, Any] | None = None
759
+
760
+ if payload_kind == "solution":
761
+ x = np.asarray(result.x, dtype=float)
762
+ y = np.asarray(result.y, dtype=float)
763
+ verification = verify_solution(
764
+ np,
765
+ problem,
766
+ p_matrix,
767
+ a_matrix,
768
+ x,
769
+ y,
770
+ min_eigenvalue,
771
+ psd_tolerance,
772
+ verify_tolerance,
773
+ )
774
+ solution = {"x": _array_list(np, x), "y": _array_list(np, y)}
775
+ elif payload_kind == "primal_certificate":
776
+ values = result.prim_inf_cert
777
+ verification = verify_primal_certificate(
778
+ np, problem, a_matrix, values, verify_tolerance
779
+ )
780
+ certificate = {
781
+ "type": "primal_infeasibility",
782
+ "values": _array_list(np, values),
783
+ }
784
+ elif payload_kind == "dual_certificate":
785
+ values = result.dual_inf_cert
786
+ verification = verify_dual_certificate(
787
+ np, problem, p_matrix, a_matrix, values, verify_tolerance
788
+ )
789
+ certificate = {"type": "dual_infeasibility", "values": _array_list(np, values)}
790
+
791
+ accepted = _payload_is_accepted(
792
+ payload_kind,
793
+ bool(verification["passed"]),
794
+ inaccurate,
795
+ accept_inaccurate,
796
+ )
797
+ report = {
798
+ "schema_version": SCHEMA_VERSION,
799
+ "problem": {
800
+ "name": problem["name"],
801
+ "dimensions": problem["dimensions"],
802
+ "structural_checks": problem["structural_checks"],
803
+ },
804
+ "solver": {
805
+ "name": "OSQP",
806
+ "version": getattr(osqp, "__version__", None),
807
+ },
808
+ "status": {
809
+ "reported": str(result.info.status),
810
+ "value": status_value,
811
+ "classification": status_key,
812
+ "inaccurate": inaccurate,
813
+ "accepted": accepted,
814
+ "accept_inaccurate_requested": accept_inaccurate,
815
+ },
816
+ "settings": problem["settings"],
817
+ "statistics": _solver_statistics(result.info),
818
+ "solution": solution,
819
+ "certificate": certificate,
820
+ "verification": verification,
821
+ }
822
+ return report, accepted
823
+
824
+
825
+ def _write_report(report: dict[str, Any], output: Path | None, indent: int) -> None:
826
+ rendered = json.dumps(report, indent=indent, sort_keys=True, allow_nan=False)
827
+ if output is not None:
828
+ output.parent.mkdir(parents=True, exist_ok=True)
829
+ file_descriptor, temporary_name = tempfile.mkstemp(
830
+ dir=output.parent,
831
+ prefix=f".{output.name}.",
832
+ suffix=".tmp",
833
+ )
834
+ temporary_path = Path(temporary_name)
835
+ try:
836
+ with os.fdopen(file_descriptor, "w", encoding="utf-8") as handle:
837
+ handle.write(rendered + "\n")
838
+ handle.flush()
839
+ os.fsync(handle.fileno())
840
+ os.replace(temporary_path, output)
841
+ except Exception:
842
+ temporary_path.unlink(missing_ok=True)
843
+ raise
844
+ print(rendered)
845
+
846
+
847
+ def _error_report(kind: str, message: str) -> dict[str, Any]:
848
+ return {
849
+ "schema_version": SCHEMA_VERSION,
850
+ "error": {"kind": kind, "message": message},
851
+ }
852
+
853
+
854
+ def parse_args(argv: Iterable[str] | None = None) -> argparse.Namespace:
855
+ parser = argparse.ArgumentParser(description=__doc__)
856
+ parser.add_argument("input", type=Path, help="JSON problem file")
857
+ parser.add_argument("--output", type=Path, help="also write the JSON report here")
858
+ parser.add_argument(
859
+ "--verify-tol",
860
+ type=float,
861
+ default=1e-7,
862
+ help="floor for independent residual/certificate checks",
863
+ )
864
+ parser.add_argument(
865
+ "--accept-inaccurate",
866
+ action="store_true",
867
+ help="allow an inaccurate status only when independent checks pass",
868
+ )
869
+ parser.add_argument(
870
+ "--validate-only",
871
+ action="store_true",
872
+ help="run dependency-free structural JSON checks without solving",
873
+ )
874
+ parser.add_argument("--indent", type=int, default=2, help="JSON indentation")
875
+ args = parser.parse_args(argv)
876
+ if not math.isfinite(args.verify_tol) or args.verify_tol <= 0:
877
+ parser.error("--verify-tol must be finite and positive")
878
+ if args.indent < 0:
879
+ parser.error("--indent must be nonnegative")
880
+ return args
881
+
882
+
883
+ def main(argv: Iterable[str] | None = None) -> int:
884
+ args = parse_args(argv)
885
+ try:
886
+ args.input = args.input.expanduser().resolve(strict=False)
887
+ if args.output is not None:
888
+ args.output = args.output.expanduser().resolve(strict=False)
889
+ same_file = args.input == args.output
890
+ if args.output.exists() and args.input.exists():
891
+ same_file = same_file or os.path.samefile(args.input, args.output)
892
+ if same_file:
893
+ raise InputError("--output must not resolve to the input file")
894
+ problem = load_problem(args.input)
895
+ if args.validate_only:
896
+ report = {
897
+ "schema_version": "osqp-solver-validation-v1",
898
+ "valid": True,
899
+ "problem": {
900
+ "name": problem["name"],
901
+ "dimensions": problem["dimensions"],
902
+ "structural_checks": problem["structural_checks"],
903
+ },
904
+ "note": (
905
+ "Structural validation only; PSD and numerical checks "
906
+ "require OSQP."
907
+ ),
908
+ }
909
+ _write_report(report, args.output, args.indent)
910
+ return 0
911
+
912
+ report, accepted = solve_problem(
913
+ problem,
914
+ verify_tolerance=args.verify_tol,
915
+ accept_inaccurate=args.accept_inaccurate,
916
+ )
917
+ _write_report(report, args.output, args.indent)
918
+ return 0 if accepted else 3
919
+ except InputError as exc:
920
+ print(
921
+ json.dumps(_error_report("input", str(exc)), indent=args.indent),
922
+ file=sys.stderr,
923
+ )
924
+ return 2
925
+ except DependencyError as exc:
926
+ print(
927
+ json.dumps(_error_report("dependency", str(exc)), indent=args.indent),
928
+ file=sys.stderr,
929
+ )
930
+ return 2
931
+ except Exception as exc: # noqa: BLE001 - return a machine-readable solver error
932
+ print(
933
+ json.dumps(
934
+ _error_report("solver", f"{type(exc).__name__}: {exc}"),
935
+ indent=args.indent,
936
+ ),
937
+ file=sys.stderr,
938
+ )
939
+ return 3
940
+
941
+
942
+ if __name__ == "__main__":
943
+ raise SystemExit(main())