@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,613 @@
1
+ ---
2
+ name: least-squares
3
+ description: "Fits linear, polynomial, and nonlinear models to data using least squares regression. Supports OLS, WLS, Ridge/Lasso regularization, custom nonlinear curve fitting, constrained least squares, MCMC Bayesian fitting, and statistical inference via numpy, scipy, scikit-learn, statsmodels, lmfit, cvxpy, iminuit, nlopt, jaxopt, and emcee. When no local library is available, searches GitHub for open-source fitting code. Use for regression, trend analysis, curve fitting, and parameter estimation. Author: 李爽夕. In DSH, check the Python scientific stack first (verymath_python_check) and follow the built-in 12-tier degradation ladder when libraries are missing."
4
+ ---
5
+
6
+ <!--
7
+ 作者:李爽夕(metadata.author 字段因 DSH 技能解析器单行 frontmatter 约定移至此处)
8
+ 数据来源:部分 benchmark 示例数据来自 NIST Statistical Reference Datasets (StRD)
9
+ https://itl.nist.gov/div898/strd/nls/nls_main.shtml
10
+ NIST 数据为美国政府公共领域产品,可自由使用,需注明来源。
11
+ -->
12
+
13
+ # 最小二乘拟合:数据建模与参数估计
14
+
15
+ ## DSH Integration Notes
16
+
17
+ - 本技能由 `@louisultra/dsh-verymath` 插件提供。开始前先调 `verymath_python_check`
18
+ 确认 Python 可用;本技能内置 12 级工具降级链(scipy → numpy → sklearn → … → GitHub 搜索),
19
+ 环境缺库时按阶梯降级并如实报告可用层级,不要静默换用弱工具。
20
+ - NIST StRD 基准数据为美国政府公共领域产品(来源注明于文内)。
21
+ - 产物(拟合结果、诊断表)写入当前会话工作区。
22
+
23
+
24
+ ## 适用场景
25
+
26
+ - **线性回归**:建立变量间的线性关系,如 `y = a + bx` 拟合销售趋势
27
+ - **多项式拟合**:拟合非线性但光滑的关系,如 `y = a + bx + cx^2` 拟合生长曲线
28
+ - **自定义模型拟合**:使用已知函数形式拟合,如指数衰减 `y = a*exp(-bx) + c`
29
+ - **加权拟合**:处理不同精度的数据点,如方差已知的测量数据
30
+ - **正则化回归**:防止过拟合,处理多重共线性,如 Ridge/Lasso 回归
31
+ - **带约束拟合**:参数有物理上下限或等式约束,如浓度必须为正
32
+ - **贝叶斯拟合**:需要参数后验分布,如 MCMC 采样
33
+
34
+ **输入**:可以是 **(x, y) 数据点**,也可以是 **已构建设计矩阵的 X, y**。
35
+
36
+ ## Quick Start(先做这个)
37
+
38
+ 按下面清单执行并在回答中保留结构。**环境准备必须先于拟合**。
39
+
40
+ - [ ] **环境准备与依赖安装(必须第一步)**:
41
+ 1. 检测 Python 环境中已安装的科学计算包:`pip list | findstr -i "numpy scipy scikit-learn statsmodels lmfit matplotlib cvxpy iminuit nlopt jax emcee"` 或 `pip list | grep -iE "numpy|scipy|scikit-learn|statsmodels|lmfit|matplotlib|cvxpy|iminuit|nlopt|jax|emcee"`
42
+ 2. 按需列出可用/缺失包,**询问用户**是否安装缺失的包
43
+ 3. 用户确认后执行安装:`pip install numpy scipy scikit-learn matplotlib`
44
+ 4. 安装完成后验证导入:
45
+ ```python
46
+ import numpy; import scipy; import sklearn
47
+ print(f"numpy={numpy.__version__}, scipy={scipy.__version__}, sklearn={sklearn.__version__}")
48
+ ```
49
+ 5. 若全部不可用且安装失败 → 走 GitHub 搜索路径
50
+ - [ ] 路径判断:用户给的是数据点/设计矩阵,还是要求从 GitHub 找代码
51
+ - [ ] 数据准备:确保 x, y 为等长 numpy 数组,无 NaN/Inf
52
+ - [ ] 问题识别:判断是线性、多项式、自定义函数、带约束还是贝叶斯拟合
53
+ - [ ] 工具选择:优先使用可用工具(scipy.curve_fit > numpy.linalg.lstsq > numpy.polyfit > scikit-learn > lmfit > cvxpy > iminuit > nlopt > jaxopt > emcee > statsmodels > GitHub 搜索)
54
+ - [ ] 拟合执行:调用相应函数,捕获可能异常
55
+ - [ ] 结果验证:计算残差、R^2,可视化检查拟合效果
56
+
57
+ ## 执行流程(三条路径)
58
+
59
+ ```mermaid
60
+ flowchart LR
61
+ A[Design_matrix_X_y]
62
+ B[Raw_xy_points]
63
+ C[GitHub_search]
64
+ A --> A1[Solve_via_lstsq_or_Ridge]
65
+ B --> B1[Identify_linear_poly_or_custom]
66
+ B1 --> B2[Choose_method]
67
+ B2 --> B3[Fit_and_report]
68
+ A1 --> B3
69
+ C --> C1[Search_GitHub_for_fitting_code]
70
+ C1 --> C2[Fetch_and_adapt_code]
71
+ C2 --> C3[Run_and_report]
72
+ ```
73
+
74
+ ### 路径 A:已有设计矩阵 X, y
75
+
76
+ 1. 核对维度:`X` 的行数与 `y` 长度一致。
77
+ 2. 直接用 `np.linalg.lstsq`、`Ridge`、`Lasso` 求解。
78
+
79
+ ### 路径 B:原始 (x, y) 数据点
80
+
81
+ 用户未给设计矩阵时,按下面交付物顺序推进:
82
+
83
+ | 步骤 | 内容 |
84
+ |------|------|
85
+ | 1. 重述 | 用一两句话复述拟合需求,便于用户确认。 |
86
+ | 2. 方法选择 | 线性/多项式/自定义函数?若未指定,默认线性。 |
87
+ | 3. 拟合 | 调用相应函数,捕获可能异常。 |
88
+ | 4. 评估 | 给出 R^2、残差、参数估计及误差。 |
89
+
90
+ ### 路径 C:GitHub 搜索开源代码
91
+
92
+ 当本地不可用科学计算库(numpy/scipy 出问题),**或用户明确要求从 GitHub 找代码**时,走此路径。
93
+
94
+ **Step 1:搜索**
95
+ 用 WebSearch 搜索 GitHub,关键词格式:
96
+ ```
97
+ site:github.com least squares fitting python <问题特征>
98
+ ```
99
+ 例如:`site:github.com least squares polynomial fitting python`、`site:github.com weighted least squares regression python`
100
+
101
+ **Step 2:筛选**
102
+ - 优先选择 Star 数高、近期更新、有 README 的仓库
103
+ - 优先选择纯 Python + numpy 实现(无需编译)
104
+ - 确认代码支持当前问题类型(线性/多项式/自定义函数)
105
+
106
+ **Step 3:获取代码**
107
+ 用 WebFetch 抓取仓库的 README 和关键 Python 文件,理解其 API 和调用方式。
108
+
109
+ **Step 4:适配与运行**
110
+ - 将用户数据转化为该代码要求的输入格式
111
+ - 编写调用脚本,运行拟合
112
+ - 若代码有 bug 或不适配,向用户说明并尝试修复
113
+
114
+ **Step 5:报告**
115
+ 按下方输出模板给出结果,并注明代码来源(GitHub URL)。
116
+
117
+ ## 输出模板(推荐)
118
+
119
+ 回答尽量按以下模板组织:
120
+
121
+ ```markdown
122
+ ### 环境与依赖
123
+ - Python 版本:3.x.x
124
+ - 环境检测结果:
125
+ - [已安装] numpy 2.x.x
126
+ - [已安装] scipy 1.x.x
127
+ - [已安装] scikit-learn 1.x.x
128
+ - [未安装] statsmodels — 用户选择不安装(非必需)
129
+ - [未安装] lmfit — pip install lmfit (1.8s, 安装成功 ✓)
130
+ - 安装操作记录:
131
+ - pip install lmfit → 成功 (version 1.3.2)
132
+ - 选用工具:scipy.optimize.curve_fit
133
+
134
+ ### 问题重述
135
+ ...
136
+
137
+ ### 拟合方法
138
+ - 模型类型:...
139
+ - 求解器/库:...
140
+
141
+ ### 拟合结果
142
+ - 参数:...
143
+ - 参数误差:...
144
+
145
+ ### 拟合质量
146
+ - R^2 = ...
147
+ - 残差平方和 = ...
148
+ - RMSE = ...
149
+
150
+ ### 诊断信息
151
+ - 条件数:...
152
+ - 求解时间:...
153
+ - 拟合方法:...
154
+
155
+ ### 可视化建议
156
+ ...
157
+ ```
158
+
159
+ ## 歧义与澄清
160
+
161
+ - **何时提问**:
162
+ - 未指定多项式阶数时:"需要几阶多项式拟合?"
163
+ - 未指定正则化强度时:"正则化参数 alpha 设为多少?"
164
+ - 自定义函数缺少初始参数时:"请提供参数初始猜测值"
165
+ - **何时假设**:
166
+ - 未指定模型类型时,默认用线性拟合
167
+ - 未提供权重时,假设等权重
168
+ - 未指定正则化时,不使用正则化
169
+ - **常见歧义处理**:
170
+ 1. "拟合曲线":默认为 2 阶多项式,可询问是否接受
171
+ 2. "精确拟合":使用更高阶多项式但警告过拟合风险
172
+ 3. "防止过拟合":自动添加 L2 正则化 (Ridge)
173
+ 4. "特征选择":建议 L1 正则化 (Lasso)
174
+
175
+ ## 范围与边界(本 skill 边界)
176
+
177
+ ### 能做什么
178
+
179
+ - 线性/多项式最小二乘(<= 20 阶)
180
+ - 自定义非线性函数拟合(参数 <= 10 个)
181
+ - 加权最小二乘(已知方差或权重)
182
+ - 正则化回归(Ridge, Lasso, ElasticNet)
183
+ - 带约束的最小二乘(通过 cvxpy 或 iminuit)
184
+ - MCMC 贝叶斯拟合(通过 emcee)
185
+ - 中小规模数据(样本数 <= 10^5,特征数 <= 1000)
186
+
187
+ ### 不能做什么
188
+
189
+ - 非高斯误差的最大似然估计
190
+ - 大规模数据拟合(需要在线/分布式算法)
191
+ - 非最小二乘的鲁棒回归(如 Huber, RANSAC)——可用 scikit-learn
192
+ - 自动模型选择(需人工指定模型形式)
193
+
194
+ ### 超出范围时如何告知
195
+
196
+ - 建议替代工具:`statsmodels`(统计推断)、`lmfit`(高级拟合)
197
+ - 大规模数据用 `sklearn.linear_model.SGDRegressor`
198
+ - 提供简化建议:降维、抽样、使用更简单模型
199
+
200
+ ## 环境与导入
201
+
202
+ ```python
203
+ import numpy as np
204
+ import scipy
205
+ from scipy.optimize import curve_fit, least_squares
206
+
207
+ # 机器学习(正则化回归)
208
+ import sklearn
209
+ from sklearn.linear_model import LinearRegression, Ridge, Lasso, ElasticNet
210
+
211
+ # 统计推断
212
+ import statsmodels.api as sm # 完整统计输出(p 值、置信区间)
213
+ import lmfit # 高级非线性拟合(参数约束、模型比较)
214
+
215
+ # 可视化
216
+ import matplotlib.pyplot as plt
217
+
218
+ # 带约束拟合
219
+ import cvxpy as cvx # Apache 2.0, 凸优化约束拟合
220
+
221
+ # 高级非线性优化
222
+ import iminuit # MIT, CERN Minuit 非线性优化
223
+ import nlopt # LGPL, 非线性优化库(多算法)
224
+
225
+ # JAX 生态(自动微分 + 优化)
226
+ import jax # Apache 2.0, 自动微分
227
+ import jaxopt # JAX 优化工具
228
+
229
+ # MCMC 贝叶斯拟合
230
+ import emcee # MIT, 仿射不变 MCMC 采样器
231
+ ```
232
+
233
+ ## 多工具支持
234
+
235
+ 本 skill 支持多种拟合工具。工具优先级:**scipy.curve_fit > numpy.linalg.lstsq > numpy.polyfit > scikit-learn > lmfit > cvxpy > iminuit > nlopt > jaxopt > emcee > statsmodels > GitHub 搜索**。
236
+
237
+ ---
238
+
239
+ ### Tier 1:核心工具(零依赖,全覆盖)
240
+
241
+ #### numpy.linalg.lstsq(线性最小二乘,零额外依赖)
242
+
243
+ ```python
244
+ import numpy as np
245
+
246
+ # 设计矩阵 X (m x n),观测值 y (m,)
247
+ beta, residuals, rank, s = np.linalg.lstsq(X, y, rcond=None)
248
+ y_pred = X @ beta
249
+ r2 = 1 - np.sum((y - y_pred)**2) / np.sum((y - np.mean(y))**2)
250
+ ```
251
+
252
+ 特点:无需额外安装、直接求解正规方程、适合线性模型。
253
+
254
+ #### numpy.polyfit / polyval(多项式拟合)
255
+
256
+ ```python
257
+ coeffs = np.polyfit(x, y, deg=2)
258
+ y_pred = np.polyval(coeffs, x)
259
+ ```
260
+
261
+ 特点:一线多项式拟合、自动处理 Vandermonde 矩阵、适合光滑趋势。
262
+
263
+ #### scipy.optimize.curve_fit(自定义非线性拟合)
264
+
265
+ ```python
266
+ from scipy.optimize import curve_fit
267
+
268
+ def model(x, a, b, c):
269
+ return a * np.exp(-b * x) + c
270
+
271
+ popt, pcov = curve_fit(model, x, y, p0=[1.0, 1.0, 0.0], method='trf')
272
+ perr = np.sqrt(np.diag(pcov))
273
+ ```
274
+
275
+ 特点:自定义函数形式、支持 `lm`/`trf`/`dogbox` 三种方法、
276
+ `trf` 适合复杂模型(如有理函数)、支持参数边界。
277
+
278
+ #### scipy.optimize.least_squares(通用非线性最小二乘)
279
+
280
+ ```python
281
+ from scipy.optimize import least_squares
282
+
283
+ def residuals(params, x, y):
284
+ return y - model(x, *params)
285
+
286
+ result = least_squares(residuals, x0=[...], args=(x, y),
287
+ bounds=([lower], [upper]), method='trf')
288
+ ```
289
+
290
+ 特点:更灵活的残差定义、支持多种方法(`trf`/`dogbox`/`lm`)、
291
+ 支持稀疏 Jacobian、可处理大规模问题。
292
+
293
+ ---
294
+
295
+ ### Tier 2:扩展工具(统计推断 + 高级拟合)
296
+
297
+ #### scikit-learn(正则化回归,机器学习生态)
298
+
299
+ ```python
300
+ from sklearn.linear_model import LinearRegression, Ridge, Lasso, ElasticNet
301
+ from sklearn.preprocessing import StandardScaler
302
+
303
+ scaler = StandardScaler()
304
+ Xs = scaler.fit_transform(X)
305
+
306
+ ridge = Ridge(alpha=1.0).fit(Xs, y)
307
+ lasso = Lasso(alpha=0.1, max_iter=10000).fit(Xs, y)
308
+ elastic = ElasticNet(alpha=0.1, l1_ratio=0.5).fit(Xs, y)
309
+ ```
310
+
311
+ 安装:`pip install scikit-learn`
312
+ 特点:支持 Ridge (L2)、Lasso (L1)、ElasticNet (L1+L2)、
313
+ 交叉验证自动选 alpha、标准化预处理、特征选择。
314
+
315
+ #### statsmodels(统计推断增强)
316
+
317
+ 当用户需要 p 值、置信区间、ANOVA 等完整统计输出时使用:
318
+
319
+ ```python
320
+ import statsmodels.api as sm
321
+
322
+ X = sm.add_constant(x) # 添加截距
323
+ model = sm.OLS(y, X)
324
+ results = model.fit()
325
+ print(results.summary()) # 完整统计报告
326
+ print(results.pvalues) # 各参数 p 值
327
+ print(results.conf_int()) # 置信区间
328
+ print(results.rsquared) # R^2
329
+ print(results.aic, results.bic) # 信息准则
330
+ ```
331
+
332
+ 安装:`pip install statsmodels`
333
+ 特点:R 风格完整输出、p 值/t 检验/F 检验、残差诊断(DW/d 检验等)、
334
+ 信息准则(AIC/BIC)、异方差稳健标准误。
335
+
336
+ #### lmfit(高级非线性拟合)
337
+
338
+ 当 curve_fit 不够灵活时(需参数约束、多模型比较等):
339
+
340
+ ```python
341
+ from lmfit import Model
342
+
343
+ def func(x, a, b, c):
344
+ return a * np.exp(-b * x) + c
345
+
346
+ model = Model(func)
347
+ params = model.make_params(a=5, b=1, c=0)
348
+ params['a'].set(min=0) # 参数约束
349
+ params['b'].set(min=0, max=10)
350
+ result = model.fit(y, params, x=x)
351
+ print(result.fit_report()) # 包含误差、相关性、卡方
352
+ print(result.best_values) # 最优参数
353
+ print(result.covar) # 协方差矩阵
354
+ ```
355
+
356
+ 安装:`pip install lmfit`
357
+ 特点:参数约束(min/max/expr/vary)、多模型比较、支持复合模型、
358
+ 内置多种谱线模型(Gaussian/Lorentzian/Voigt)、自定义目标函数。
359
+
360
+ #### cvxpy(带约束最小二乘)
361
+
362
+ 当参数有线性或二次约束时(如非负性、总和约束、参数关系):
363
+
364
+ ```python
365
+ import cvxpy as cvx
366
+
367
+ # 约束最小二乘:min ||A x - b||_2 s.t. x >= 0, sum(x) == 1
368
+ x = cvx.Variable(n)
369
+ objective = cvx.Minimize(cvx.norm(A @ x - b, 2))
370
+ constraints = [x >= 0, cvx.sum(x) == 1]
371
+ prob = cvx.Problem(objective, constraints)
372
+ prob.solve(solver=cvx.CLARABEL)
373
+
374
+ # 或带二次正则化:min ||A x - b||_2^2 + lambda * ||x||_2^2
375
+ x = cvx.Variable(n)
376
+ objective = cvx.Minimize(cvx.sum_squares(A @ x - b) + lam * cvx.sum_squares(x))
377
+ prob = cvx.Problem(objective)
378
+ prob.solve()
379
+ ```
380
+
381
+ 安装:`pip install cvxpy`
382
+ 特点:凸约束下的最小二乘、参数的线性/二次/锥约束、多求解器后端、
383
+ SOCP/SDP 均可处理、适合物理约束(如浓度非负、概率和为1)。
384
+
385
+ ---
386
+
387
+ ### Tier 3:高级优化工具
388
+
389
+ #### iminuit(CERN Minuit,非线性优化)
390
+
391
+ ```python
392
+ from iminuit import Minuit
393
+ from iminuit.cost import LeastSquares
394
+
395
+ # 使用 LeastSquares 代价函数
396
+ least_squares_cost = LeastSquares(x, y, yerr, model)
397
+ m = Minuit(least_squares_cost, a=1.0, b=1.0, c=0.0)
398
+ m.limits['a'] = (0, None) # 参数边界
399
+ m.migrad() # 梯度优化
400
+ m.hesse() # Hesse 误差矩阵
401
+ print(m.values, m.errors)
402
+ print(m.covariance) # 参数协方差
403
+ print(m.fval) # 目标函数值
404
+ ```
405
+
406
+ 安装:`pip install iminuit`
407
+ 特点:CERN ROOT 团队开发(MIT 许可证)、robust 非线性优化、
408
+ 支持参数边界、支持 Likelihood 和 LeastSquares 代价函数、
409
+ 提供 Minos 不对称误差、profile 轮廓扫描、Pythonic 接口。
410
+
411
+ #### nlopt(多算法非线性优化)
412
+
413
+ ```python
414
+ import nlopt
415
+
416
+ def objective(params, grad):
417
+ # 返回残差平方和
418
+ pred = model(x, *params)
419
+ rss = np.sum((y - pred)**2)
420
+ if grad.size > 0:
421
+ # 提供梯度(可选,加速收敛)
422
+ pass
423
+ return rss
424
+
425
+ opt = nlopt.opt(nlopt.LN_BOBYQA, n_params) # BOBYQA 无导数优化
426
+ # 或 opt = nlopt.opt(nlopt.LD_LBFGS, n_params) # LBFGS 梯度优化
427
+ opt.set_min_objective(objective)
428
+ opt.set_lower_bounds(lower_bounds)
429
+ opt.set_upper_bounds(upper_bounds)
430
+ opt.set_ftol_rel(1e-8)
431
+ params = opt.optimize(initial_guess)
432
+ ```
433
+
434
+ 安装:`pip install nlopt`
435
+ 特点:MIT/LGPL 许可证、支持数十种优化算法(局部/全局、有梯度/无梯度)、
436
+ 支持不等式约束、C/C++/Fortran/Python 多语言绑定、
437
+ NLOPT_LN_BOBYQA(无导数)和 NLOPT_LD_LBFGS(梯度)最常用。
438
+
439
+ #### jaxopt(JAX 优化,自动微分)
440
+
441
+ ```python
442
+ import jax.numpy as jnp
443
+ import jaxopt
444
+
445
+ def residuals(params):
446
+ a, b, c = params
447
+ return y - a * jnp.exp(-b * x) + c
448
+
449
+ def rss(params):
450
+ res = residuals(params)
451
+ return jnp.sum(res**2)
452
+
453
+ # 用自动微分进行梯度优化
454
+ solver = jaxopt.ScipyMinimize(fun=rss, method="L-BFGS-B")
455
+ result = solver.run(init_params=jnp.array([1.0, 1.0, 0.0]))
456
+ print(result.params, result.state.fun_val)
457
+ ```
458
+
459
+ 安装:`pip install jax jaxopt`
460
+ 特点:Apache 2.0 许可证、自动微分(无需手写梯度)、
461
+ 支持 GPU/TPU 加速、多种优化器(L-BFGS、Gauss-Newton、Levenberg-Marquardt)、
462
+ 适合需要梯度的精确拟合和大型参数问题。
463
+
464
+ ---
465
+
466
+ ### Tier 4:贝叶斯拟合
467
+
468
+ #### emcee(MCMC 贝叶斯参数估计)
469
+
470
+ ```python
471
+ import emcee
472
+
473
+ def log_prior(params):
474
+ # 定义先验分布
475
+ a, b, c = params
476
+ if 0 < a < 10 and 0 < b < 5:
477
+ return 0.0
478
+ return -np.inf
479
+
480
+ def log_likelihood(params, x, y, yerr):
481
+ model_y = model(x, *params)
482
+ return -0.5 * np.sum((y - model_y)**2 / yerr**2 + np.log(yerr**2))
483
+
484
+ def log_probability(params, x, y, yerr):
485
+ lp = log_prior(params)
486
+ if not np.isfinite(lp):
487
+ return -np.inf
488
+ return lp + log_likelihood(params, x, y, yerr)
489
+
490
+ # 初始化 walkers
491
+ nwalkers, ndim = 32, 3
492
+ p0 = np.array([1.0, 1.0, 0.0]) + 1e-3 * np.random.randn(nwalkers, ndim)
493
+
494
+ sampler = emcee.EnsembleSampler(nwalkers, ndim, log_probability,
495
+ args=(x, y, yerr))
496
+ sampler.run_mcmc(p0, 5000, progress=True)
497
+
498
+ # 获取后验
499
+ flat_samples = sampler.get_chain(discard=1000, thin=10, flat=True)
500
+ for i, name in enumerate(['a', 'b', 'c']):
501
+ mcmc = np.percentile(flat_samples[:, i], [16, 50, 84])
502
+ q = np.diff(mcmc)
503
+ print(f"{name} = {mcmc[1]:.3f} (+{q[1]:.3f} / -{q[0]:.3f})")
504
+ ```
505
+
506
+ 安装:`pip install emcee`
507
+ 特点:MIT 许可证、仿射不变 MCMC 采样器(无需调 proposal scale)、
508
+ 支持多线程并行、工业界广泛使用、适合参数后验分布和不确定性量化、
509
+ 可与 corner.py 结合绘制参数协方差图。
510
+
511
+ ---
512
+
513
+ ### 工具选择指南
514
+
515
+ | 工具 | 安装方式 | 授权 | 适用场景 | 特色功能 |
516
+ |------|---------|------|----------|----------|
517
+ | numpy.linalg.lstsq | 内置 | BSD | 线性最小二乘 | 零依赖、直接求解 |
518
+ | numpy.polyfit | 内置 | BSD | 多项式拟合 | 一线命令 |
519
+ | **scipy.curve_fit** | `pip install scipy` | **BSD** | **非线性拟合首选** | **trf/lm/dogbox 三方法** |
520
+ | scipy.least_squares | 内置 scipy | BSD | 通用非线性 LS | 稀疏 Jacobian、bounds |
521
+ | scikit-learn | `pip install scikit-learn` | BSD | 正则化回归 | Ridge/Lasso/ElasticNet |
522
+ | statsmodels | `pip install statsmodels` | BSD | 统计推断 | R 风格输出、p 值 |
523
+ | lmfit | `pip install lmfit` | BSD | 高级拟合 | 参数约束、复合模型 |
524
+ | cvxpy | `pip install cvxpy` | Apache 2.0 | 约束拟合 | 线性和凸约束 |
525
+ | iminuit | `pip install iminuit` | MIT | 非线性优化 | Minos 不对称误差 |
526
+ | nlopt | `pip install nlopt` | MIT/LGPL | 多算法优化 | 40+ 算法支持 |
527
+ | jaxopt | `pip install jax jaxopt` | Apache 2.0 | 自动微分优化 | GPU 加速、精确梯度 |
528
+ | emcee | `pip install emcee` | MIT | MCMC 贝叶斯 | 仿射不变、不确定性量化 |
529
+
530
+ ### 自动检测与降级策略
531
+
532
+ Agent 应按以下顺序尝试导入并使用拟合工具:
533
+
534
+ ```
535
+ 1. from scipy.optimize import curve_fit → 非线性拟合首选
536
+ 2. numpy.linalg.lstsq → 线性拟合
537
+ 3. numpy.polyfit → 多项式拟合
538
+ 4. from sklearn.linear_model import Ridge, Lasso → 正则化
539
+ 5. import lmfit → 高级非线性(参数约束)
540
+ 6. import cvxpy → 带约束最小二乘
541
+ 7. import iminuit → Minuit 非线性优化
542
+ 8. import nlopt → 多算法优化
543
+ 9. import jaxopt → JAX 自动微分优化
544
+ 10. import emcee → MCMC 贝叶斯
545
+ 11. import statsmodels → 统计推断
546
+ 12. 以上均不可用 → 走路径 C:GitHub 搜索开源代码
547
+ ```
548
+
549
+ ## 接口速查
550
+
551
+ ```python
552
+ # 1. 线性最小二乘
553
+ np.linalg.lstsq(X, y, rcond=None)
554
+
555
+ # 2. 多项式拟合
556
+ coeffs = np.polyfit(x, y, deg=2)
557
+ y_pred = np.polyval(coeffs, x)
558
+
559
+ # 3. 自定义函数拟合
560
+ from scipy.optimize import curve_fit
561
+ popt, pcov = curve_fit(f, x, y, p0=[...], method='trf')
562
+
563
+ # 4. 非线性最小二乘
564
+ from scipy.optimize import least_squares
565
+ result = least_squares(fun, x0, args=(...), method='trf')
566
+
567
+ # 5. 正则化回归
568
+ from sklearn.linear_model import Ridge, Lasso
569
+ Ridge(alpha=1.0).fit(X, y)
570
+ Lasso(alpha=0.1).fit(X, y)
571
+
572
+ # 6. 约束最小二乘
573
+ import cvxpy as cvx
574
+ prob = cvx.Problem(cvx.Minimize(cvx.norm(A@x - b)), constraints)
575
+ prob.solve()
576
+
577
+ # 7. 高级非线性
578
+ from iminuit import Minuit; from iminuit.cost import LeastSquares
579
+ m = Minuit(LeastSquares(x, y, yerr, model), a=1.0, b=1.0); m.migrad()
580
+
581
+ # 8. MCMC
582
+ import emcee
583
+ sampler = emcee.EnsembleSampler(nwalkers, ndim, log_prob, args=(x, y, yerr))
584
+ ```
585
+
586
+ ## 依赖
587
+
588
+ ```bash
589
+ # 核心(必装)
590
+ pip install numpy scipy matplotlib scikit-learn
591
+
592
+ # 扩展(选装)
593
+ pip install statsmodels lmfit cvxpy
594
+
595
+ # 高级优化(选装)
596
+ pip install iminuit nlopt jax jaxopt
597
+
598
+ # 贝叶斯(选装)
599
+ pip install emcee corner
600
+ ```
601
+
602
+ ## 错误处理
603
+
604
+ 1. **奇异矩阵**:检测条件数,建议正则化或减少特征
605
+ 2. **不收敛**:提供更好的初始值,增加最大迭代次数,切换方法(`lm` → `trf`)
606
+ 3. **数值溢出**:缩放数据(标准化),使用 double 精度
607
+ 4. **过拟合警告**:当阶数 >= 样本数/3 时警告
608
+ 5. **curve_fit `lm` 失败**:对有理函数等复杂模型,`lm` 容易陷入局部极小值——换用 `method='trf'`
609
+ 6. **有理函数多极点**:尝试多组初值 + `trf`,仍不行用 `differential_evolution` 全局搜索
610
+
611
+ ## 建模示例
612
+
613
+ 详见 [examples.md](examples.md),包含 8 个完整示例(线性拟合、多项式拟合、指数衰减、Ridge 正则化、加权最小二乘、非线性最小二乘、Lasso 特征选择、有理函数拟合 NIST StRD)。