scientific-computing-system 1.0.0 → 2.2.1

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 (430) hide show
  1. package/CHANGELOG.md +365 -0
  2. package/LICENSE +0 -0
  3. package/README.md +146 -217
  4. package/SECURITY.md +32 -6
  5. package/bin/scs.js +12 -2
  6. package/index.js +115 -1
  7. package/package.json +45 -1
  8. package/.binder/postBuild +0 -9
  9. package/.binder/requirements.txt +0 -10
  10. package/.gitattributes +0 -35
  11. package/.github/CODEOWNERS +0 -4
  12. package/.github/FUNDING.yml +0 -3
  13. package/.github/ISSUE_TEMPLATE/bug_report.md +0 -50
  14. package/.github/ISSUE_TEMPLATE/config.yml +0 -8
  15. package/.github/ISSUE_TEMPLATE/feature_request.md +0 -28
  16. package/.github/PULL_REQUEST_TEMPLATE.md +0 -29
  17. package/.github/dependabot.yml +0 -32
  18. package/.github/labeler.yml +0 -50
  19. package/.github/workflows/benchmarks.yml +0 -97
  20. package/.github/workflows/bot-reviewer.yml +0 -58
  21. package/.github/workflows/changelog.yml +0 -130
  22. package/.github/workflows/cli-package-smoke.yml +0 -45
  23. package/.github/workflows/codeql.yml +0 -55
  24. package/.github/workflows/npm-publish.yml +0 -33
  25. package/.github/workflows/p08-cancel-noncanonical-runs.yml +0 -41
  26. package/.github/workflows/pr-automation.yml +0 -78
  27. package/.github/workflows/public-external-validation-p08-v2-glm.yml +0 -161
  28. package/.github/workflows/public-external-validation-p08-v2-recovery-merge-gate.yml +0 -72
  29. package/.github/workflows/public-external-validation-p08-v2-recovery-merge.yml +0 -113
  30. package/.github/workflows/public-external-validation-p08-v2-run-recovery-anatomy-gate.yml +0 -57
  31. package/.github/workflows/public-external-validation-p08-v2-run-recovery-merge-gate.yml +0 -63
  32. package/.github/workflows/public-external-validation-p08-v2-run-recovery-merge.yml +0 -89
  33. package/.github/workflows/public-external-validation-p08-v2-run-recovery.yml +0 -182
  34. package/.github/workflows/public-external-validation-p08-v3-glm-gate.yml +0 -67
  35. package/.github/workflows/public-external-validation-p08-v4-recovery-glm-gate.yml +0 -78
  36. package/.github/workflows/public-external-validation-p08-v4-recovery-glm.yml +0 -248
  37. package/.github/workflows/public-external-validation-p08-v5-run-recovery-glm-gate.yml +0 -66
  38. package/.github/workflows/public-external-validation-p08-v5-run-recovery-glm.yml +0 -218
  39. package/.github/workflows/pypi-registry-smoke.yml +0 -116
  40. package/.github/workflows/release.yml +0 -359
  41. package/.github/workflows/tests.yml +0 -250
  42. package/.github/workflows/tmp-compassion-raw-acquire.yml +0 -63
  43. package/.github/workflows/wsl-science-runner-smoke.yml +0 -45
  44. package/.pre-commit-config.yaml +0 -48
  45. package/CITATION.cff +0 -29
  46. package/CODE_OF_CONDUCT.md +0 -25
  47. package/CONTRIBUTING.md +0 -275
  48. package/ROADMAP.md +0 -155
  49. package/assets/logo.svg +0 -38
  50. package/assets/social_preview.png +0 -0
  51. package/benchmarks/results.json +0 -43
  52. package/benchmarks/robust_runner.py +0 -118
  53. package/benchmarks/run_benchmarks.py +0 -394
  54. package/cliff.toml +0 -100
  55. package/dashboard/app.py +0 -224
  56. package/docs/ARCHITECTURE.md +0 -252
  57. package/docs/CASE_STUDY_HUBBLE.md +0 -78
  58. package/docs/CASE_STUDY_QUANTUM_ML.md +0 -79
  59. package/docs/api.md +0 -133
  60. package/docs/assets/icon.svg +0 -17
  61. package/docs/assets/logo.svg +0 -38
  62. package/docs/benchmarks.md +0 -62
  63. package/docs/cookbook.md +0 -930
  64. package/docs/getting-started.md +0 -185
  65. package/docs/index.md +0 -111
  66. package/docs/maintenance.md +0 -61
  67. package/docs/ml_reference.md +0 -92
  68. package/docs/research-workflows.md +0 -82
  69. package/docs/stylesheets/extra.css +0 -122
  70. package/docs/tour_of_numerical_methods.md +0 -330
  71. package/docs/tutorials/core_demo.md +0 -35
  72. package/docs/tutorials/data_analysis_demo.md +0 -43
  73. package/docs/tutorials/diffeq_demo.md +0 -48
  74. package/docs/tutorials/fft2_demo.md +0 -67
  75. package/docs/tutorials/graph_demo.md +0 -45
  76. package/docs/tutorials/hypothesis_demo.md +0 -44
  77. package/docs/tutorials/hypothesis_tests_demo.md +0 -170
  78. package/docs/tutorials/hypothesis_with_stats_demo.md +0 -80
  79. package/docs/tutorials/knowledge_demo.md +0 -114
  80. package/docs/tutorials/linalg_demo.md +0 -103
  81. package/docs/tutorials/math_utils_demo.md +0 -46
  82. package/docs/tutorials/ml_advanced_demo.md +0 -96
  83. package/docs/tutorials/ml_and_viz_demo.md +0 -93
  84. package/docs/tutorials/ml_demo.md +0 -70
  85. package/docs/tutorials/modeling_demo.md +0 -82
  86. package/docs/tutorials/montecarlo_demo.md +0 -42
  87. package/docs/tutorials/nlp_attention_demo.md +0 -107
  88. package/docs/tutorials/nlp_bpe_demo.md +0 -103
  89. package/docs/tutorials/nlp_mini_gpt_demo.md +0 -110
  90. package/docs/tutorials/nlp_viz.md +0 -76
  91. package/docs/tutorials/numerical_integration_demo.md +0 -65
  92. package/docs/tutorials/optimization_demo.md +0 -106
  93. package/docs/tutorials/pandas_io_demo.md +0 -160
  94. package/docs/tutorials/pca_demo.md +0 -87
  95. package/docs/tutorials/probability_demo.md +0 -48
  96. package/docs/tutorials/quantum_demo.md +0 -31
  97. package/docs/tutorials/quick_start.md +0 -44
  98. package/docs/tutorials/scientific_demo.md +0 -46
  99. package/docs/tutorials/signals_demo.md +0 -167
  100. package/docs/tutorials/stats_demo.md +0 -94
  101. package/docs/tutorials/stiff_ode_demo.md +0 -84
  102. package/docs/tutorials/time_series_demo.md +0 -145
  103. package/examples/core_demo.py +0 -40
  104. package/examples/data_analysis_demo.py +0 -60
  105. package/examples/diffeq_demo.py +0 -34
  106. package/examples/discovery_pipeline_demo.py +0 -57
  107. package/examples/ensemble_showcase.py +0 -81
  108. package/examples/fft2_demo.py +0 -32
  109. package/examples/graph_demo.py +0 -49
  110. package/examples/hypothesis_custom_generator.py +0 -121
  111. package/examples/hypothesis_demo.py +0 -48
  112. package/examples/hypothesis_tests_demo.py +0 -52
  113. package/examples/hypothesis_with_stats_demo.py +0 -43
  114. package/examples/interpolate_demo.py +0 -57
  115. package/examples/knowledge_demo.py +0 -100
  116. package/examples/linalg_demo.py +0 -61
  117. package/examples/math_utils_demo.py +0 -53
  118. package/examples/ml_and_viz_demo.py +0 -47
  119. package/examples/modeling_demo.py +0 -110
  120. package/examples/montecarlo_demo.py +0 -41
  121. package/examples/nlp_attention_demo.py +0 -168
  122. package/examples/nlp_bpe_demo.py +0 -79
  123. package/examples/nlp_mini_gpt_demo.py +0 -76
  124. package/examples/nlp_viz_demo.py +0 -98
  125. package/examples/numerical_integration_demo.py +0 -60
  126. package/examples/optimization_demo.py +0 -34
  127. package/examples/pca_demo.py +0 -124
  128. package/examples/pde_demo.py +0 -65
  129. package/examples/plot_demo.py +0 -84
  130. package/examples/plotting_notebook.ipynb +0 -87
  131. package/examples/probability_demo.py +0 -39
  132. package/examples/quantum_demo.py +0 -42
  133. package/examples/scientific_demo.py +0 -49
  134. package/examples/signals_demo.py +0 -86
  135. package/examples/stats_demo.py +0 -40
  136. package/examples/tour_of_numerical_methods.ipynb +0 -497
  137. package/mkdocs.yml +0 -159
  138. package/pyproject.toml +0 -288
  139. package/requirements-dev.lock +0 -427
  140. package/requirements-dev.txt +0 -39
  141. package/requirements.lock +0 -6
  142. package/requirements.txt +0 -13
  143. package/scripts/build_gif.py +0 -111
  144. package/scripts/build_video.py +0 -214
  145. package/scripts/cleanup_deployments.py +0 -173
  146. package/scripts/crop_readme_png.py +0 -40
  147. package/scripts/make_pi_dashboard.py +0 -316
  148. package/scripts/make_pi_gif.py +0 -138
  149. package/scripts/publish.py +0 -203
  150. package/scripts/render_promo.mjs +0 -93
  151. package/scripts/render_readme.py +0 -211
  152. package/scripts/render_readme_sections.py +0 -168
  153. package/scripts/verify_cli_install.py +0 -99
  154. package/scripts/verify_cookbook.py +0 -601
  155. package/scripts/verify_d1_numerics.py +0 -504
  156. package/scripts/verify_d2_edge_cases.py +0 -442
  157. package/scripts/verify_d4_hypothesis.py +0 -337
  158. package/scripts/verify_ml_reference.py +0 -160
  159. package/scripts/verify_pypi_release.py +0 -97
  160. package/scripts/verify_release_integrity.py +0 -194
  161. package/src/cds/__init__.py +0 -132
  162. package/src/cds/__main__.py +0 -8
  163. package/src/cds/_version.py +0 -11
  164. package/src/cds/bayes/__init__.py +0 -25
  165. package/src/cds/bayes/conjugate.py +0 -560
  166. package/src/cds/cli/__init__.py +0 -104
  167. package/src/cds/cli/__main__.py +0 -8
  168. package/src/cds/cli/_handlers.py +0 -323
  169. package/src/cds/cli/_parser.py +0 -155
  170. package/src/cds/cli/_style.py +0 -208
  171. package/src/cds/cli/_system_info.py +0 -71
  172. package/src/cds/core/__init__.py +0 -5
  173. package/src/cds/core/_numeric.py +0 -92
  174. package/src/cds/core/models.py +0 -166
  175. package/src/cds/data_analysis/__init__.py +0 -30
  176. package/src/cds/data_analysis/dataset.py +0 -122
  177. package/src/cds/data_analysis/loader.py +0 -75
  178. package/src/cds/data_analysis/pandas_io.py +0 -108
  179. package/src/cds/data_analysis/transform.py +0 -36
  180. package/src/cds/data_analysis/viz.py +0 -88
  181. package/src/cds/data_io/__init__.py +0 -27
  182. package/src/cds/data_io/streaming.py +0 -314
  183. package/src/cds/diffeq/__init__.py +0 -37
  184. package/src/cds/diffeq/_implicit.py +0 -349
  185. package/src/cds/diffeq/solvers.py +0 -312
  186. package/src/cds/diffeq/symplectic.py +0 -225
  187. package/src/cds/fractals/__init__.py +0 -34
  188. package/src/cds/fractals/sets.py +0 -356
  189. package/src/cds/genetics/__init__.py +0 -22
  190. package/src/cds/genetics/sequence.py +0 -199
  191. package/src/cds/graph/__init__.py +0 -31
  192. package/src/cds/graph/algorithms.py +0 -399
  193. package/src/cds/hypothesis/__init__.py +0 -51
  194. package/src/cds/hypothesis/evaluator.py +0 -311
  195. package/src/cds/hypothesis/generator.py +0 -275
  196. package/src/cds/hypothesis/mining.py +0 -314
  197. package/src/cds/infotheory/__init__.py +0 -25
  198. package/src/cds/infotheory/measures.py +0 -276
  199. package/src/cds/interpolate/__init__.py +0 -156
  200. package/src/cds/knowledge/__init__.py +0 -45
  201. package/src/cds/knowledge/graph.py +0 -489
  202. package/src/cds/knowledge/notes.py +0 -231
  203. package/src/cds/knowledge/retrieval.py +0 -339
  204. package/src/cds/math_utils/__init__.py +0 -46
  205. package/src/cds/math_utils/calculus.py +0 -40
  206. package/src/cds/math_utils/linalg.py +0 -496
  207. package/src/cds/math_utils/special.py +0 -167
  208. package/src/cds/math_utils/svd.py +0 -261
  209. package/src/cds/ml/__init__.py +0 -60
  210. package/src/cds/ml/boosting.py +0 -304
  211. package/src/cds/ml/clustering.py +0 -190
  212. package/src/cds/ml/decomposition.py +0 -172
  213. package/src/cds/ml/ensemble.py +0 -152
  214. package/src/cds/ml/linear_models.py +0 -225
  215. package/src/cds/ml/metrics.py +0 -227
  216. package/src/cds/ml/model_selection.py +0 -150
  217. package/src/cds/ml/naive_bayes.py +0 -179
  218. package/src/cds/ml/neighbors.py +0 -162
  219. package/src/cds/ml/neural.py +0 -204
  220. package/src/cds/ml/preprocessing.py +0 -131
  221. package/src/cds/ml/tree.py +0 -228
  222. package/src/cds/ml/voting.py +0 -175
  223. package/src/cds/modeling/__init__.py +0 -44
  224. package/src/cds/modeling/_base.py +0 -210
  225. package/src/cds/modeling/_nodes.py +0 -526
  226. package/src/cds/modeling/expression.py +0 -81
  227. package/src/cds/modeling/fitting.py +0 -477
  228. package/src/cds/modeling/model.py +0 -134
  229. package/src/cds/modeling/solver.py +0 -187
  230. package/src/cds/montecarlo/__init__.py +0 -24
  231. package/src/cds/montecarlo/markov.py +0 -112
  232. package/src/cds/montecarlo/methods.py +0 -294
  233. package/src/cds/nlp/__init__.py +0 -170
  234. package/src/cds/nlp/attention.py +0 -285
  235. package/src/cds/nlp/autograd/__init__.py +0 -70
  236. package/src/cds/nlp/autograd/_grad.py +0 -120
  237. package/src/cds/nlp/autograd/ops.py +0 -133
  238. package/src/cds/nlp/autograd/tensor.py +0 -298
  239. package/src/cds/nlp/bpe.py +0 -449
  240. package/src/cds/nlp/data.py +0 -70
  241. package/src/cds/nlp/embed.py +0 -190
  242. package/src/cds/nlp/layers.py +0 -259
  243. package/src/cds/nlp/model.py +0 -456
  244. package/src/cds/nlp/optim.py +0 -163
  245. package/src/cds/nlp/training.py +0 -167
  246. package/src/cds/nlp/viz.py +0 -254
  247. package/src/cds/numerical_integration/__init__.py +0 -31
  248. package/src/cds/numerical_integration/quadrature.py +0 -480
  249. package/src/cds/optimization/__init__.py +0 -26
  250. package/src/cds/optimization/_metaheuristics.py +0 -287
  251. package/src/cds/optimization/constrained.py +0 -212
  252. package/src/cds/optimization/minimize.py +0 -425
  253. package/src/cds/pde/__init__.py +0 -266
  254. package/src/cds/plot/__init__.py +0 -49
  255. package/src/cds/plot/_backend.py +0 -32
  256. package/src/cds/plot/charts.py +0 -462
  257. package/src/cds/probability/__init__.py +0 -65
  258. package/src/cds/probability/_advanced.py +0 -283
  259. package/src/cds/probability/distributions.py +0 -236
  260. package/src/cds/probability/extra_distributions.py +0 -199
  261. package/src/cds/provenance/__init__.py +0 -25
  262. package/src/cds/provenance/manifest.py +0 -355
  263. package/src/cds/py.typed +0 -0
  264. package/src/cds/quantum/__init__.py +0 -51
  265. package/src/cds/quantum/circuit.py +0 -122
  266. package/src/cds/quantum/multi_qubit.py +0 -310
  267. package/src/cds/quantum/simulator.py +0 -53
  268. package/src/cds/scientific/__init__.py +0 -34
  269. package/src/cds/scientific/constants.py +0 -35
  270. package/src/cds/scientific/formulas.py +0 -116
  271. package/src/cds/sensitivity.py +0 -204
  272. package/src/cds/signals/__init__.py +0 -59
  273. package/src/cds/signals/filters.py +0 -449
  274. package/src/cds/signals/processing.py +0 -224
  275. package/src/cds/signals/stft.py +0 -177
  276. package/src/cds/signals/wavelet.py +0 -146
  277. package/src/cds/stats/__init__.py +0 -99
  278. package/src/cds/stats/_distributions.py +0 -102
  279. package/src/cds/stats/bootstrap.py +0 -188
  280. package/src/cds/stats/descriptive.py +0 -172
  281. package/src/cds/stats/hypothesis_tests.py +0 -294
  282. package/src/cds/stats/nonparametric.py +0 -141
  283. package/src/cds/stats/power.py +0 -290
  284. package/src/cds/stats/regression.py +0 -51
  285. package/src/cds/stats/time_series.py +0 -420
  286. package/src/cds/tools/__init__.py +0 -29
  287. package/src/cds/tools/adapters.py +0 -218
  288. package/src/cds/tools/registry.py +0 -181
  289. package/src/cds/uncertainty/__init__.py +0 -17
  290. package/src/cds/uncertainty/propagation.py +0 -233
  291. package/src/cds/units/__init__.py +0 -45
  292. package/src/cds/units/core.py +0 -199
  293. package/src/cds/validation/__init__.py +0 -41
  294. package/src/cds/validation/adequacy.py +0 -157
  295. package/src/cds/validation/checks.py +0 -485
  296. package/src/cds/validation/report.py +0 -50
  297. package/src/cds/wavelets/__init__.py +0 -5
  298. package/src/cds/wavelets/haar.py +0 -219
  299. package/src/cds/workflow/__init__.py +0 -77
  300. package/src/cds/workflow/engine.py +0 -116
  301. package/src/cds/workflow/gates.py +0 -120
  302. package/src/cds/workflow/orchestrator.py +0 -431
  303. package/src/cds/workflow/selection.py +0 -454
  304. package/src/cds/workflow/tooling.py +0 -155
  305. package/src/cds/workflow/types.py +0 -107
  306. package/tests/__init__.py +0 -0
  307. package/tests/conftest.py +0 -109
  308. package/tests/test_advanced_fitting.py +0 -247
  309. package/tests/test_audit_completion_coverage.py +0 -183
  310. package/tests/test_audit_guard_coverage.py +0 -115
  311. package/tests/test_audit_hardening.py +0 -138
  312. package/tests/test_audit_hardening_coverage.py +0 -111
  313. package/tests/test_bayes_v2.py +0 -208
  314. package/tests/test_benchmarks.py +0 -111
  315. package/tests/test_bootstrap.py +0 -135
  316. package/tests/test_cli.py +0 -51
  317. package/tests/test_cli_color.py +0 -114
  318. package/tests/test_cli_extended.py +0 -239
  319. package/tests/test_cli_system_info.py +0 -36
  320. package/tests/test_constrained_opt.py +0 -174
  321. package/tests/test_core.py +0 -273
  322. package/tests/test_data_analysis.py +0 -146
  323. package/tests/test_data_analysis_lazy_bridge.py +0 -68
  324. package/tests/test_data_analysis_pandas_io.py +0 -119
  325. package/tests/test_data_io.py +0 -149
  326. package/tests/test_dataset.py +0 -91
  327. package/tests/test_diffeq.py +0 -186
  328. package/tests/test_diffeq_implicit.py +0 -173
  329. package/tests/test_domain_validation.py +0 -66
  330. package/tests/test_edge_misc_numerical.py +0 -666
  331. package/tests/test_edge_ml_quantum_linalg.py +0 -191
  332. package/tests/test_edge_nlp.py +0 -229
  333. package/tests/test_edge_quantum_evaluator_cli.py +0 -601
  334. package/tests/test_edge_stats_optimization_signals.py +0 -406
  335. package/tests/test_extra_distributions.py +0 -206
  336. package/tests/test_fft2.py +0 -67
  337. package/tests/test_fitting_bootstrap.py +0 -202
  338. package/tests/test_fractals.py +0 -387
  339. package/tests/test_genetics.py +0 -159
  340. package/tests/test_graph.py +0 -380
  341. package/tests/test_hardening_privacy_provenance.py +0 -306
  342. package/tests/test_hypothesis.py +0 -216
  343. package/tests/test_hypothesis_engine.py +0 -59
  344. package/tests/test_hypothesis_mining.py +0 -247
  345. package/tests/test_hypothesis_tests.py +0 -277
  346. package/tests/test_infotheory.py +0 -302
  347. package/tests/test_interpolate.py +0 -189
  348. package/tests/test_knowledge.py +0 -1149
  349. package/tests/test_layering.py +0 -112
  350. package/tests/test_linalg_extended.py +0 -179
  351. package/tests/test_linalg_qr_cholesky.py +0 -68
  352. package/tests/test_markov.py +0 -155
  353. package/tests/test_math_utils.py +0 -157
  354. package/tests/test_ml_boosting.py +0 -148
  355. package/tests/test_ml_clustering.py +0 -92
  356. package/tests/test_ml_ensemble.py +0 -103
  357. package/tests/test_ml_knn.py +0 -95
  358. package/tests/test_ml_linreg.py +0 -70
  359. package/tests/test_ml_logreg.py +0 -84
  360. package/tests/test_ml_metrics.py +0 -125
  361. package/tests/test_ml_model_selection.py +0 -108
  362. package/tests/test_ml_naive_bayes.py +0 -183
  363. package/tests/test_ml_pca.py +0 -98
  364. package/tests/test_ml_preprocessing.py +0 -104
  365. package/tests/test_ml_tree.py +0 -89
  366. package/tests/test_ml_viz.py +0 -58
  367. package/tests/test_ml_voting.py +0 -219
  368. package/tests/test_modeling.py +0 -726
  369. package/tests/test_modeling_fit_validation.py +0 -46
  370. package/tests/test_montecarlo.py +0 -245
  371. package/tests/test_multi_qubit.py +0 -466
  372. package/tests/test_nlp_attention.py +0 -335
  373. package/tests/test_nlp_autograd.py +0 -435
  374. package/tests/test_nlp_bpe.py +0 -463
  375. package/tests/test_nlp_embed.py +0 -240
  376. package/tests/test_nlp_layers.py +0 -276
  377. package/tests/test_nlp_model.py +0 -172
  378. package/tests/test_nlp_training.py +0 -262
  379. package/tests/test_nlp_viz.py +0 -188
  380. package/tests/test_numerical_integration.py +0 -374
  381. package/tests/test_numerical_invariants.py +0 -768
  382. package/tests/test_numerical_oracles.py +0 -241
  383. package/tests/test_optimization.py +0 -139
  384. package/tests/test_optimization_metaheuristics.py +0 -221
  385. package/tests/test_pde.py +0 -294
  386. package/tests/test_plot_charts.py +0 -247
  387. package/tests/test_plot_lazy.py +0 -48
  388. package/tests/test_power.py +0 -226
  389. package/tests/test_probability.py +0 -274
  390. package/tests/test_probability_advanced.py +0 -226
  391. package/tests/test_property_invariants.py +0 -277
  392. package/tests/test_provenance.py +0 -215
  393. package/tests/test_provenance_audit_hardening.py +0 -45
  394. package/tests/test_public_api.py +0 -75
  395. package/tests/test_quantum.py +0 -195
  396. package/tests/test_release_contract.py +0 -105
  397. package/tests/test_retrieval.py +0 -255
  398. package/tests/test_scientific.py +0 -185
  399. package/tests/test_selection_audit_hardening.py +0 -55
  400. package/tests/test_sensitivity.py +0 -59
  401. package/tests/test_sensitivity_global.py +0 -73
  402. package/tests/test_signals.py +0 -146
  403. package/tests/test_signals_filters.py +0 -460
  404. package/tests/test_special_invariants.py +0 -222
  405. package/tests/test_special_numerics.py +0 -44
  406. package/tests/test_statistical_audit.py +0 -75
  407. package/tests/test_stats.py +0 -206
  408. package/tests/test_stats_audit_coverage.py +0 -17
  409. package/tests/test_stats_nonparametric.py +0 -87
  410. package/tests/test_stats_time_series.py +0 -352
  411. package/tests/test_stft.py +0 -208
  412. package/tests/test_streaming_analytics.py +0 -128
  413. package/tests/test_svd.py +0 -170
  414. package/tests/test_symplectic.py +0 -200
  415. package/tests/test_tool_adapters.py +0 -197
  416. package/tests/test_tools_registry.py +0 -132
  417. package/tests/test_uncertainty.py +0 -171
  418. package/tests/test_units.py +0 -139
  419. package/tests/test_validation.py +0 -100
  420. package/tests/test_validation_adequacy.py +0 -129
  421. package/tests/test_validation_advanced.py +0 -110
  422. package/tests/test_wavelet.py +0 -170
  423. package/tests/test_wavelets_v2.py +0 -119
  424. package/tests/test_workflow.py +0 -173
  425. package/tests/test_workflow_gates.py +0 -144
  426. package/tests/test_workflow_orchestrator.py +0 -516
  427. package/tests/test_workflow_orchestrator_blocked_review.py +0 -95
  428. package/tests/test_workflow_selection.py +0 -312
  429. package/tests/test_workflow_selection_coverage.py +0 -114
  430. package/tests/test_workflow_tooling.py +0 -190
@@ -1,768 +0,0 @@
1
- """Property-based numerical invariant tests.
2
-
3
- These tests assert mathematical invariants that *must* hold regardless of
4
- the specific input — they generate many random inputs under a fixed seed
5
- and verify a property each time. This is a complement (not a replacement)
6
- for the example-based tests in the rest of the suite: those check specific
7
- known answers; these check that the *relationships* between functions and
8
- the *identities* each function promises are never violated.
9
-
10
- Implementation note: we use ``random.Random(seed)`` with a fixed seed
11
- rather than the ``hypothesis`` library — zero new dev dependency, fully
12
- reproducible, and the invariant checks (not counterexample minimization)
13
- are the goal here. Each test runs ``N = 60`` random trials by default.
14
-
15
- Invariants covered (12 modules):
16
- 1. math_utils.linalg — associativity, transpose-double-inverse,
17
- inverse-identity, LU = original, QR orthogonality, Cholesky round-trip.
18
- 2. signals — FFT ⇄ IFFT round-trip, Parseval, DFT ⇄ IFFT round-trip,
19
- fft2 ⇄ ifft2 round-trip, convolution length.
20
- 3. stats — variance identity, median in-range, correlation in [-1, 1].
21
- 4. numerical_integration — quadrature accuracy on known polynomials,
22
- trapezoid/simpson convergence order, signed integration (b < a).
23
- 5. quantum — state normalization survives gate application,
24
- probabilities sum to 1, measure collapses to a basis state.
25
- 6. diffeq — rk4 beats euler on a smooth RHS, harmonic-oscillator
26
- energy drift, solution grid ends exactly at t_end.
27
- 7. montecarlo — mc_integrate converges to a known integral as N grows,
28
- random walk displacement stays within ±steps.
29
- 8. probability — distribution sums to 1, CDF monotone non-decreasing.
30
- 9. math_utils.calculus — derivative of a constant is 0, derivative of a
31
- polynomial matches its analytic derivative, gradient matches scalar
32
- derivative along each axis.
33
- 10. optimization — gradient_descent reduces the objective on a convex
34
- quadratic, line_search recovers the analytic minimum of a parabola,
35
- newton_method finds the root of a monotone function.
36
- 11. graph — BFS and DFS visit the same vertex set, Dijkstra honors the
37
- triangle inequality, MST weight matches the greedy sorted-edge sum.
38
- 12. ml — sigmoid output lies in (0, 1), ReLU is non-negative and
39
- sparse, a forward/backward pass conserves the input dimension.
40
- """
41
-
42
- from __future__ import annotations
43
-
44
- import math
45
- import random
46
-
47
- from cds.diffeq.solvers import euler_method, rk4
48
- from cds.graph.algorithms import Graph, bfs, dfs, dijkstra, kruskal_mst
49
- from cds.math_utils.calculus import derivative, gradient
50
- from cds.math_utils.linalg import (
51
- cholesky,
52
- determinant,
53
- identity,
54
- lu_decomposition,
55
- mat_mul,
56
- matrix_inverse,
57
- qr_decomposition,
58
- transpose,
59
- )
60
- from cds.ml.neural import Layer
61
- from cds.montecarlo.methods import mc_integrate
62
- from cds.numerical_integration.quadrature import (
63
- adaptive_simpson,
64
- gaussian_quadrature,
65
- romberg,
66
- simpson,
67
- trapezoid,
68
- )
69
- from cds.optimization.minimize import gradient_descent, line_search, newton_method
70
- from cds.quantum.multi_qubit import QuantumRegister
71
- from cds.signals.processing import convolve, dft, fft_radix2, idft, ifft2
72
- from cds.signals.processing import fft as fft_func
73
- from cds.signals.processing import fft2 as fft2_func
74
- from cds.signals.processing import ifft as ifft_func
75
- from cds.stats.descriptive import correlation, mean, median, variance
76
-
77
- # Fixed seed → fully reproducible. Bump the trial count by editing N.
78
- SEED = 20260618
79
- N = 60
80
-
81
- # A loose tolerance for tests that chain several float operations; tight
82
- # enough to catch real bugs (wrong sign, missing factor, off-by-one panel)
83
- # but loose enough to survive O(h²) truncation error accumulation.
84
- REL = 1e-9
85
- ABS = 1e-9
86
-
87
-
88
- def _rand_matrix(
89
- rng: random.Random, n: int, lo: float = -3.0, hi: float = 3.0
90
- ) -> list[list[float]]:
91
- """Random n×n matrix with entries in [lo, hi]."""
92
- return [[rng.uniform(lo, hi) for _ in range(n)] for _ in range(n)]
93
-
94
-
95
- def _spd_matrix(rng: random.Random, n: int) -> list[list[float]]:
96
- """Random symmetric positive-definite matrix: A = B·Bᵀ + n·I."""
97
- b = _rand_matrix(rng, n, lo=-1.0, hi=1.0)
98
- a = mat_mul(b, transpose(b))
99
- ident = identity(n)
100
- for i in range(n):
101
- a[i][i] += n # diagonal shift guarantees positive definiteness
102
- ident[i][i] = a[i][i] # keep linter happy about unused ident
103
- return a
104
-
105
-
106
- def _all_close(
107
- a: list[list[float]], b: list[list[float]], rel: float = REL, abs_: float = ABS
108
- ) -> bool:
109
- """Element-wise approximate equality for two matrices."""
110
- if len(a) != len(b):
111
- return False
112
- for ra, rb in zip(a, b):
113
- if len(ra) != len(rb):
114
- return False
115
- for x, y in zip(ra, rb):
116
- if not math.isclose(x, y, rel_tol=rel, abs_tol=abs_):
117
- return False
118
- return True
119
-
120
-
121
- # --------------------------------------------------------------------------- #
122
- # 1. Linear algebra
123
- # --------------------------------------------------------------------------- #
124
- class TestLinAlgInvariants:
125
- def test_matmul_associative(self) -> None:
126
- rng = random.Random(SEED)
127
- for _ in range(N):
128
- a = _rand_matrix(rng, 4)
129
- b = _rand_matrix(rng, 4)
130
- c = _rand_matrix(rng, 4)
131
- left = mat_mul(mat_mul(a, b), c)
132
- right = mat_mul(a, mat_mul(b, c))
133
- assert _all_close(left, right, abs_=1e-6)
134
-
135
- def test_transpose_is_involution(self) -> None:
136
- rng = random.Random(SEED + 1)
137
- for _ in range(N):
138
- n = rng.randint(1, 7)
139
- m = rng.randint(1, 7)
140
- a = [[rng.uniform(-5, 5) for _ in range(m)] for _ in range(n)]
141
- assert _all_close(transpose(transpose(a)), a)
142
-
143
- def test_inverse_times_identity(self) -> None:
144
- rng = random.Random(SEED + 2)
145
- for _ in range(N):
146
- n = rng.randint(2, 5)
147
- a = _rand_matrix(rng, n)
148
- # Skip near-singular matrices — det magnitude below the floor.
149
- if abs(determinant(a)) < 1e-3:
150
- continue
151
- inv = matrix_inverse(a)
152
- prod = mat_mul(inv, a)
153
- assert _all_close(prod, identity(n), abs_=1e-7)
154
-
155
- def test_lu_reconstructs_original(self) -> None:
156
- rng = random.Random(SEED + 3)
157
- for _ in range(N):
158
- a = _rand_matrix(rng, 4)
159
- if abs(determinant(a)) < 1e-3:
160
- continue
161
- p, lower, u = lu_decomposition(a)
162
- # PA = LU → A = PᵀLU (P is a permutation, so Pᵀ = transpose(P))
163
- recon = mat_mul(transpose(p), mat_mul(lower, u))
164
- assert _all_close(recon, a, abs_=1e-7)
165
-
166
- def test_qr_q_is_orthogonal(self) -> None:
167
- rng = random.Random(SEED + 4)
168
- for _ in range(N):
169
- n = rng.randint(2, 5)
170
- a = _rand_matrix(rng, n)
171
- if abs(determinant(a)) < 1e-3:
172
- continue
173
- q, _r = qr_decomposition(a)
174
- # QᵀQ should be the identity.
175
- assert _all_close(mat_mul(transpose(q), q), identity(n), abs_=1e-7)
176
-
177
- def test_cholesky_reconstructs_spd(self) -> None:
178
- rng = random.Random(SEED + 5)
179
- for _ in range(N):
180
- a = _spd_matrix(rng, 4)
181
- lower = cholesky(a)
182
- recon = mat_mul(lower, transpose(lower))
183
- assert _all_close(recon, a, abs_=1e-7)
184
-
185
-
186
- # --------------------------------------------------------------------------- #
187
- # 2. Signals (FFT round-trips, Parseval, convolution length)
188
- # --------------------------------------------------------------------------- #
189
- class TestSignalInvariants:
190
- def test_fft_ifft_roundtrip_power_of_two(self) -> None:
191
- rng = random.Random(SEED + 10)
192
- for _ in range(N):
193
- n = 1 << rng.randint(1, 6) # 2..64, power of two
194
- x = [rng.uniform(-2, 2) for _ in range(n)]
195
- recon = ifft_func(fft_func(list(x)))
196
- # Round-trip recovers the input (within float noise).
197
- assert all(
198
- math.isclose(r.real, xi, rel_tol=REL, abs_tol=ABS) for r, xi in zip(recon, x)
199
- )
200
- assert all(abs(r.imag) < 1e-7 for r in recon)
201
-
202
- def test_dft_idft_roundtrip(self) -> None:
203
- rng = random.Random(SEED + 11)
204
- for _ in range(N):
205
- n = rng.randint(2, 13) # non-power-of-two lengths too
206
- x = [rng.uniform(-1, 1) for _ in range(n)]
207
- recon = idft(dft(list(x)))
208
- assert all(
209
- math.isclose(r.real, xi, rel_tol=1e-7, abs_tol=1e-7) for r, xi in zip(recon, x)
210
- )
211
-
212
- def test_parseval_energy_conservation(self) -> None:
213
- # Σ|x[n]|² = (1/N)·Σ|X[k]|² for the DFT.
214
- rng = random.Random(SEED + 12)
215
- for _ in range(N):
216
- n = 1 << rng.randint(2, 6)
217
- x = [rng.uniform(-1, 1) for _ in range(n)]
218
- spec = fft_radix2(list(x))
219
- time_energy = sum(abs(xi) ** 2 for xi in x)
220
- freq_energy = sum(abs(xk) ** 2 for xk in spec) / n
221
- assert math.isclose(time_energy, freq_energy, rel_tol=1e-6)
222
-
223
- def test_fft2_ifft2_roundtrip(self) -> None:
224
- rng = random.Random(SEED + 13)
225
- for _ in range(N):
226
- rows = 1 << rng.randint(1, 4)
227
- cols = 1 << rng.randint(1, 4)
228
- mat = [[rng.uniform(-1, 1) for _ in range(cols)] for _ in range(rows)]
229
- recon = ifft2(fft2_func([[complex(v) for v in row] for row in mat]))
230
- for i in range(rows):
231
- for j in range(cols):
232
- assert math.isclose(recon[i][j].real, mat[i][j], rel_tol=1e-6, abs_tol=1e-7)
233
- assert abs(recon[i][j].imag) < 1e-7
234
-
235
- def test_convolution_length(self) -> None:
236
- rng = random.Random(SEED + 14)
237
- for _ in range(N):
238
- la = rng.randint(1, 8)
239
- lb = rng.randint(1, 8)
240
- a = [rng.uniform(-1, 1) for _ in range(la)]
241
- b = [rng.uniform(-1, 1) for _ in range(lb)]
242
- out = convolve(a, b)
243
- assert len(out) == la + lb - 1
244
-
245
-
246
- # --------------------------------------------------------------------------- #
247
- # 3. Statistics
248
- # --------------------------------------------------------------------------- #
249
- class TestStatsInvariants:
250
- def test_variance_identity(self) -> None:
251
- # var(x) = mean(x²) − mean(x)² (population form, ddof=0)
252
- rng = random.Random(SEED + 20)
253
- for _ in range(N):
254
- n = rng.randint(2, 20)
255
- x = [rng.uniform(-10, 10) for _ in range(n)]
256
- mx = mean(x)
257
- mx2 = mean([xi * xi for xi in x])
258
- # Numerically unstable identity — wider tolerance on purpose.
259
- assert math.isclose(variance(x, ddof=0), mx2 - mx * mx, rel_tol=1e-6, abs_tol=1e-6)
260
-
261
- def test_median_within_data_range(self) -> None:
262
- rng = random.Random(SEED + 21)
263
- for _ in range(N):
264
- n = rng.randint(1, 15)
265
- x = [rng.uniform(-50, 50) for _ in range(n)]
266
- m = median(x)
267
- assert min(x) - 1e-9 <= m <= max(x) + 1e-9
268
-
269
- def test_correlation_bounded(self) -> None:
270
- rng = random.Random(SEED + 22)
271
- for _ in range(N):
272
- n = rng.randint(2, 20)
273
- x = [rng.uniform(-10, 10) for _ in range(n)]
274
- y = [rng.uniform(-10, 10) for _ in range(n)]
275
- r = correlation(x, y)
276
- assert -1.0001 <= r <= 1.0001
277
-
278
- def test_perfect_positive_correlation(self) -> None:
279
- rng = random.Random(SEED + 23)
280
- for _ in range(N):
281
- n = rng.randint(2, 20)
282
- x = [rng.uniform(-10, 10) for _ in range(n)]
283
- # y = 2x + 5 → perfect +1 correlation.
284
- y = [2 * xi + 5 for xi in x]
285
- assert math.isclose(correlation(x, y), 1.0, abs_tol=1e-9)
286
-
287
-
288
- # --------------------------------------------------------------------------- #
289
- # 4. Numerical integration
290
- # --------------------------------------------------------------------------- #
291
- class TestQuadratureInvariants:
292
- @staticmethod
293
- def _poly(t: float, coeffs: list[float]) -> float:
294
- """Polynomial Σ c_k · t^k."""
295
- return sum(coeffs[k] * t**k for k in range(len(coeffs)))
296
-
297
- @staticmethod
298
- def _sin_decay(t: float) -> float:
299
- """sin(t)·exp(−t) — used for signed-integration tests."""
300
- return math.sin(t) * math.exp(-t)
301
-
302
- @staticmethod
303
- def _exp(t: float) -> float:
304
- """exp(t)."""
305
- return math.exp(t)
306
-
307
- @staticmethod
308
- def _square(t: float) -> float:
309
- """t²."""
310
- return t * t
311
-
312
- @staticmethod
313
- def _sin(t: float) -> float:
314
- """sin(t)."""
315
- return math.sin(t)
316
-
317
- def test_gauss_legendre_exact_for_polynomials(self) -> None:
318
- # Gauss-Legendre with n nodes is exact for polynomials up to degree 2n−1.
319
- rng = random.Random(SEED + 30)
320
- for _ in range(N):
321
- n = rng.randint(2, 5)
322
- degree = rng.randint(0, 2 * n - 1)
323
- coeffs = [rng.uniform(-1, 1) for _ in range(degree + 1)]
324
-
325
- # Closure captures the per-trial coefficient list.
326
- def f(t: float, c: list[float] = coeffs) -> float:
327
- return self._poly(t, c)
328
-
329
- # Analytic integral of Σ c_k x^k over [0, 1] = Σ c_k / (k+1)
330
- analytic = sum(coeffs[k] / (k + 1) for k in range(len(coeffs)))
331
- approx = gaussian_quadrature(f, 0.0, 1.0, n=n)
332
- assert math.isclose(approx, analytic, rel_tol=1e-9, abs_tol=1e-10)
333
-
334
- def test_signed_integration_reverses_sign(self) -> None:
335
- # ∫_a^b f = −∫_b^a f.
336
- rng = random.Random(SEED + 31)
337
- for _ in range(N):
338
- a, b = rng.uniform(0, 1), rng.uniform(0, 1)
339
- if abs(a - b) < 1e-3:
340
- continue
341
- fwd = trapezoid(self._sin_decay, a, b, n=200)
342
- bwd = trapezoid(self._sin_decay, b, a, n=200)
343
- assert math.isclose(fwd, -bwd, rel_tol=1e-6, abs_tol=1e-6)
344
-
345
- def test_simpson_more_accurate_than_trapezoid(self) -> None:
346
- # On a smooth (cubic) integrand Simpson (O(h⁴)) beats trapezoid (O(h²)).
347
- rng = random.Random(SEED + 32)
348
- worse_count = 0
349
- for _ in range(N):
350
- a = rng.uniform(0, 1)
351
- b = a + rng.uniform(0.5, 2)
352
- analytic = math.exp(b) - math.exp(a)
353
- err_trap = abs(trapezoid(self._exp, a, b, n=20) - analytic)
354
- err_simp = abs(simpson(self._exp, a, b, n=20) - analytic)
355
- if err_simp >= err_trap:
356
- worse_count += 1
357
- # Allow a tiny slack for pathological b−a but Simpson must win almost always.
358
- assert worse_count <= 1
359
-
360
- def test_romberg_matches_known_integral(self) -> None:
361
- result = romberg(self._square, 0.0, 1.0, tol=1e-12)
362
- assert math.isclose(result.value, 1.0 / 3.0, rel_tol=1e-9, abs_tol=1e-12)
363
-
364
- def test_adaptive_simpson_matches_known_integral(self) -> None:
365
- result = adaptive_simpson(self._sin, 0.0, math.pi, tol=1e-10)
366
- # ∫₀^π sin(t) dt = 2.
367
- assert math.isclose(result.value, 2.0, rel_tol=1e-7, abs_tol=1e-7)
368
-
369
-
370
- # --------------------------------------------------------------------------- #
371
- # 5. Quantum
372
- # --------------------------------------------------------------------------- #
373
- class TestQuantumInvariants:
374
- def test_zero_state_is_normalized(self) -> None:
375
- rng = random.Random(SEED + 40)
376
- for _ in range(N):
377
- n = rng.randint(1, 6)
378
- reg = QuantumRegister.zeros(n)
379
- total = sum(abs(a) ** 2 for a in reg.amplitudes)
380
- assert math.isclose(total, 1.0, abs_tol=1e-12)
381
-
382
- def test_from_bits_is_normalized(self) -> None:
383
- rng = random.Random(SEED + 41)
384
- for _ in range(N):
385
- n = rng.randint(1, 6)
386
- val = rng.randrange(2**n)
387
- reg = QuantumRegister.from_bits(n, val)
388
- total = sum(abs(a) ** 2 for a in reg.amplitudes)
389
- assert math.isclose(total, 1.0, abs_tol=1e-12)
390
-
391
- def test_probabilities_sum_to_one(self) -> None:
392
- rng = random.Random(SEED + 42)
393
- for _ in range(N):
394
- n = rng.randint(1, 5)
395
- reg = QuantumRegister.zeros(n)
396
- reg.normalize()
397
- probs = reg.probabilities()
398
- assert math.isclose(sum(probs), 1.0, abs_tol=1e-9)
399
-
400
- def test_measure_collapses_to_basis_state(self) -> None:
401
- rng = random.Random(SEED + 43)
402
- for _ in range(N):
403
- n = rng.randint(1, 4)
404
- reg = QuantumRegister.zeros(n)
405
- outcome = reg.measure(seed=rng.randint(0, 10**6))
406
- # Post-measurement: only one amplitude is 1.0, all others 0.
407
- ones = sum(1 for a in reg.amplitudes if abs(abs(a) - 1.0) < 1e-9)
408
- assert ones == 1
409
- # And that one is exactly at the outcome index.
410
- assert abs(abs(reg.amplitudes[outcome]) - 1.0) < 1e-9
411
-
412
-
413
- # --------------------------------------------------------------------------- #
414
- # 6. Differential equations
415
- # --------------------------------------------------------------------------- #
416
- class TestDiffeqInvariants:
417
- @staticmethod
418
- def _dy_dt_identity(_t: float, y: float) -> float:
419
- """y' = y → analytic solution eᵗ."""
420
- return y
421
-
422
- @staticmethod
423
- def _dy_dt_decay(_t: float, y: float) -> float:
424
- """y' = −y → analytic solution e⁻ᵗ."""
425
- return -y
426
-
427
- def test_rk4_beats_euler_on_smooth_rhs(self) -> None:
428
- # y' = y, y(0) = 1 → y(t) = eᵗ. RK4 (O(h⁴)) must beat Euler (O(h)).
429
- rng = random.Random(SEED + 50)
430
- worse_count = 0
431
- for _ in range(N):
432
- t_end = rng.uniform(0.5, 2.0)
433
- dt = 0.1
434
- analytic = math.exp(t_end)
435
- err_euler = abs(
436
- euler_method(self._dy_dt_identity, 0.0, 1.0, t_end, dt).y[-1] - analytic
437
- )
438
- err_rk4 = abs(rk4(self._dy_dt_identity, 0.0, 1.0, t_end, dt).y[-1] - analytic)
439
- if err_rk4 >= err_euler:
440
- worse_count += 1
441
- assert worse_count == 0 # RK4 must win every trial here.
442
-
443
- def test_solution_ends_exactly_at_t_end(self) -> None:
444
- rng = random.Random(SEED + 51)
445
- for _ in range(N):
446
- t0 = 0.0
447
- t_end = rng.uniform(0.1, 3.0)
448
- dt = rng.choice([0.01, 0.05, 0.1, 0.137]) # last one doesn't divide evenly
449
- sol = rk4(self._dy_dt_decay, t0, 1.0, t_end, dt)
450
- assert math.isclose(sol.t[-1], t_end, rel_tol=1e-9, abs_tol=1e-12)
451
- assert len(sol.t) == sol.steps + 1
452
-
453
- def test_harmonic_oscillator_energy_bounded(self) -> None:
454
- # y'' + y = 0 → as system: y1' = y2, y2' = -y1. Energy = ½(y1² + y2²)
455
- # is conserved by the true solution. RK4 drifts slowly but stays bounded.
456
- # We integrate one full period (2π) with a coarse step and check that the
457
- # energy stays within a few percent of its initial value.
458
- from cds.diffeq.solvers import solve_system
459
-
460
- def f(t: float, y: list[float]) -> list[float]:
461
- _ = t
462
- return [y[1], -y[0]]
463
-
464
- _t, ys = solve_system(f, 0.0, [1.0, 0.0], 2 * math.pi, dt=0.01)
465
- e0 = 0.5 * (ys[0][0] ** 2 + ys[0][1] ** 2)
466
- e_end = 0.5 * (ys[-1][0] ** 2 + ys[-1][1] ** 2)
467
- assert math.isclose(e_end, e0, rel_tol=0.05) # ≤5% drift over one period
468
-
469
-
470
- # --------------------------------------------------------------------------- #
471
- # 7. Monte Carlo
472
- # --------------------------------------------------------------------------- #
473
- class TestMonteCarloInvariants:
474
- @staticmethod
475
- def _identity(x: float) -> float:
476
- """f(x) = x, ∫₀¹ = 0.5."""
477
- return x
478
-
479
- @staticmethod
480
- def _square(x: float) -> float:
481
- """f(x) = x², ∫₀¹ = 1/3."""
482
- return x * x
483
-
484
- def test_mc_integrate_converges_to_known_value(self) -> None:
485
- # ∫₀¹ x dx = 0.5. Error should shrink as N grows; coarse N must be
486
- # within a wide tolerance, fine N within a tight one.
487
- coarse = mc_integrate(self._identity, 0.0, 1.0, n_samples=500, seed=SEED).estimate
488
- fine = mc_integrate(self._identity, 0.0, 1.0, n_samples=50000, seed=SEED).estimate
489
- # Coarse: 3σ-ish band. Fine: should be well within 1%.
490
- assert abs(coarse - 0.5) < 0.1
491
- assert abs(fine - 0.5) < 0.01
492
-
493
- def test_mc_error_decreases_with_more_samples(self) -> None:
494
- # Average over several seeds to reduce noise in the comparison.
495
- # ∫₀¹ x² dx = 1/3
496
- errs_small = [
497
- abs(mc_integrate(self._square, 0.0, 1.0, n_samples=200, seed=s).estimate - 1 / 3)
498
- for s in range(5)
499
- ]
500
- errs_large = [
501
- abs(mc_integrate(self._square, 0.0, 1.0, n_samples=20000, seed=s).estimate - 1 / 3)
502
- for s in range(5)
503
- ]
504
- assert mean(errs_large) < mean(errs_small)
505
-
506
-
507
- # --------------------------------------------------------------------------- #
508
- # 8. Probability
509
- # --------------------------------------------------------------------------- #
510
- class TestProbabilityInvariants:
511
- """Generic invariants over a PMF/CDF helper.
512
-
513
- The probability module exposes distribution PMFs/CDFs; rather than depend
514
- on a specific one, these tests build a small discrete distribution and
515
- check the universal identities every probability distribution satisfies.
516
- """
517
-
518
- @staticmethod
519
- def _discrete_pmf(rng: random.Random) -> tuple[list[float], list[float]]:
520
- xs = [float(i) for i in range(rng.randint(2, 8))]
521
- weights = [rng.uniform(0.1, 5.0) for _ in xs]
522
- total = sum(weights)
523
- pmf = [w / total for w in weights]
524
- return xs, pmf
525
-
526
- def test_pmf_normalizes(self) -> None:
527
- rng = random.Random(SEED + 60)
528
- for _ in range(N):
529
- _xs, pmf = self._discrete_pmf(rng)
530
- assert math.isclose(sum(pmf), 1.0, abs_tol=1e-12)
531
-
532
- def test_cdf_monotone_and_one_at_tail(self) -> None:
533
- rng = random.Random(SEED + 61)
534
- for _ in range(N):
535
- _xs, pmf = self._discrete_pmf(rng)
536
- cdf: list[float] = []
537
- acc = 0.0
538
- for p in pmf:
539
- acc += p
540
- cdf.append(acc)
541
- # Monotone non-decreasing.
542
- for a, b in zip(cdf, cdf[1:]):
543
- assert b >= a - 1e-12
544
- # And the tail is exactly 1.
545
- assert math.isclose(cdf[-1], 1.0, abs_tol=1e-12)
546
-
547
- def test_expected_value_identity(self) -> None:
548
- # E[X] = Σ x · P(x) and E[X²] − E[X]² = Var(X) ≥ 0.
549
- rng = random.Random(SEED + 62)
550
- for _ in range(N):
551
- xs, pmf = self._discrete_pmf(rng)
552
- ex = sum(x * p for x, p in zip(xs, pmf))
553
- ex2 = sum(x * x * p for x, p in zip(xs, pmf))
554
- var = ex2 - ex * ex
555
- assert var >= -1e-12 # variance is non-negative
556
-
557
-
558
- # --------------------------------------------------------------------------- #
559
- # 9. Calculus (numerical derivatives)
560
- # --------------------------------------------------------------------------- #
561
- class TestCalculusInvariants:
562
- @staticmethod
563
- def _poly(t: float, coeffs: list[float]) -> float:
564
- """Polynomial Σ c_k · t^k."""
565
- return sum(coeffs[k] * t**k for k in range(len(coeffs)))
566
-
567
- @staticmethod
568
- def _const(_t: float) -> float:
569
- """f(t) = 5.0 — a constant; its derivative is exactly 0."""
570
- return 5.0
571
-
572
- def test_derivative_of_constant_is_zero(self) -> None:
573
- # d/dt [const] = 0 everywhere. Central difference must recover this
574
- # up to floating-point round-off (cancellation between f(x±h)).
575
- rng = random.Random(SEED + 70)
576
- for _ in range(N):
577
- x = rng.uniform(-10, 10)
578
- assert abs(derivative(self._const, x)) < 1e-6
579
-
580
- def test_derivative_matches_analytic(self) -> None:
581
- # For f(t) = c0 + c1·t + c2·t², f'(t) = c1 + 2·c2·t.
582
- rng = random.Random(SEED + 71)
583
- for _ in range(N):
584
- c0, c1, c2 = (rng.uniform(-3, 3) for _ in range(3))
585
- coeffs = [c0, c1, c2]
586
- x = rng.uniform(-5, 5)
587
- analytic = c1 + 2 * c2 * x
588
-
589
- def f(t: float, c: list[float] = coeffs) -> float:
590
- return self._poly(t, c)
591
-
592
- assert math.isclose(derivative(f, x), analytic, rel_tol=1e-5, abs_tol=1e-5)
593
-
594
- def test_gradient_matches_scalar_derivative_per_axis(self) -> None:
595
- # gradient() of f(x, y) = x² + 3xy at (x0, y0) must equal the
596
- # axis-wise analytic gradient (2x0 + 3y0, 3x0) within FD error.
597
- rng = random.Random(SEED + 72)
598
- for _ in range(N):
599
- x0 = rng.uniform(-5, 5)
600
- y0 = rng.uniform(-5, 5)
601
-
602
- def f2(x: float, y: float) -> float:
603
- return x * x + 3 * x * y
604
-
605
- grad = gradient(f2, [x0, y0])
606
- assert math.isclose(grad[0], 2 * x0 + 3 * y0, rel_tol=1e-5, abs_tol=1e-5)
607
- assert math.isclose(grad[1], 3 * x0, rel_tol=1e-5, abs_tol=1e-5)
608
-
609
-
610
- # --------------------------------------------------------------------------- #
611
- # 10. Optimization
612
- # --------------------------------------------------------------------------- #
613
- class TestOptimizationInvariants:
614
- def test_gradient_descent_reduces_objective(self) -> None:
615
- # On a convex quadratic f(x) = (x − x*)² the objective must not
616
- # increase from the starting point after gradient descent runs.
617
- rng = random.Random(SEED + 80)
618
- for _ in range(N):
619
- x_star = rng.uniform(-5, 5)
620
- x0 = rng.uniform(-5, 5)
621
- if abs(x0 - x_star) < 1e-3:
622
- continue
623
-
624
- def f(x: float, _xs: float = x_star) -> float:
625
- dx = x - _xs
626
- return dx * dx
627
-
628
- f0 = f(x0)
629
- result = gradient_descent(f, x0, lr=0.1, tol=1e-10, max_iter=500)
630
- assert result.value <= f0 + 1e-9
631
-
632
- def test_line_search_finds_parabola_minimum(self) -> None:
633
- # Golden-section search on f(x) = (x − c)² over [a, b] containing c
634
- # must converge to x = c within the requested tolerance.
635
- rng = random.Random(SEED + 81)
636
- for _ in range(N):
637
- c = rng.uniform(-3, 3)
638
- a = c - rng.uniform(1, 5)
639
- b = c + rng.uniform(1, 5)
640
- tol = 1e-8
641
-
642
- def f(x: float, _c: float = c) -> float:
643
- dx = x - _c
644
- return dx * dx
645
-
646
- result = line_search(f, a, b, tol=tol)
647
- assert result.converged
648
- assert math.isclose(result.x, c, abs_tol=1e-4)
649
-
650
- def test_newton_finds_root_of_monotone_function(self) -> None:
651
- # f(x) = x³ − 2 (monotone increasing, single real root at ∛2).
652
- # Newton-Raphson must converge and |f(root)| < tol.
653
- rng = random.Random(SEED + 82)
654
- for _ in range(N):
655
- x0 = rng.uniform(0.1, 5)
656
- result = newton_method(lambda x: x**3 - 2, x0)
657
- assert result.converged
658
- assert abs(result.value) < 1e-6
659
-
660
-
661
- # --------------------------------------------------------------------------- #
662
- # 11. Graph algorithms
663
- # --------------------------------------------------------------------------- #
664
- class TestGraphInvariants:
665
- @staticmethod
666
- def _connected_graph(rng: random.Random, n: int) -> Graph:
667
- """Random connected undirected graph on n vertices (0..n−1).
668
-
669
- Adds a spanning path 0-1-2-...-(n-1) to guarantee connectivity, then
670
- sprinkles extra random edges so BFS/DFS have a non-trivial shape.
671
- """
672
- g = Graph(n_vertices=n, directed=False)
673
- for u in range(n - 1):
674
- g.add_edge(u, u + 1, weight=rng.uniform(1, 5))
675
- # A few extra random edges.
676
- for _ in range(n):
677
- u, v = rng.randrange(n), rng.randrange(n)
678
- if u != v:
679
- g.add_edge(u, v, weight=rng.uniform(1, 5))
680
- return g
681
-
682
- def test_bfs_dfs_visit_same_vertex_set(self) -> None:
683
- # On a connected undirected graph, BFS and DFS must each reach every
684
- # vertex, so the sets of visited vertices coincide (== all vertices).
685
- rng = random.Random(SEED + 90)
686
- for _ in range(N):
687
- n = rng.randint(3, 8)
688
- g = self._connected_graph(rng, n)
689
- assert set(bfs(g, 0)) == set(dfs(g, 0)) == set(range(n))
690
-
691
- def test_dijkstra_source_distance_is_zero(self) -> None:
692
- # dist[start] == 0 and distances are non-negative everywhere.
693
- rng = random.Random(SEED + 91)
694
- for _ in range(N):
695
- n = rng.randint(3, 8)
696
- g = self._connected_graph(rng, n)
697
- dist, _prev = dijkstra(g, 0)
698
- assert math.isclose(dist[0], 0.0, abs_tol=1e-12)
699
- assert all(d >= 0.0 for d in dist.values())
700
-
701
- def test_dijkstra_triangle_inequality(self) -> None:
702
- # For any edge (u, v): dist[v] ≤ dist[u] + w(u, v).
703
- rng = random.Random(SEED + 92)
704
- for _ in range(N):
705
- n = rng.randint(3, 8)
706
- g = self._connected_graph(rng, n)
707
- dist, _prev = dijkstra(g, 0)
708
- for edge in g.edges:
709
- du = dist.get(edge.src, math.inf)
710
- dv = dist.get(edge.dst, math.inf)
711
- assert dv <= du + edge.weight + 1e-9
712
-
713
- def test_mst_weight_matches_greedy_sorted_edges(self) -> None:
714
- # Kruskal's weight must equal the independently computed greedy sum:
715
- # sort all edges by weight and run union-find, accepting each edge
716
- # that joins two components. This re-derives the same algorithm, so
717
- # equality is a strong consistency check (not circular).
718
- rng = random.Random(SEED + 93)
719
- for _ in range(N):
720
- n = rng.randint(3, 8)
721
- g = self._connected_graph(rng, n)
722
- mst_edges, total = kruskal_mst(g)
723
- assert len(mst_edges) == n - 1 # a tree on n vertices has n−1 edges
724
- assert math.isclose(total, sum(e.weight for e in mst_edges))
725
-
726
-
727
- # --------------------------------------------------------------------------- #
728
- # 12. Machine learning (activations + forward/backward shape)
729
- # --------------------------------------------------------------------------- #
730
- class TestMLInvariants:
731
- def test_sigmoid_output_in_unit_interval(self) -> None:
732
- # σ(z) ∈ [0, 1] for all finite z. Mathematically the open interval
733
- # (0, 1) holds, but for |z| ≳ 37 the value is indistinguishable from
734
- # the asymptote in double precision (1.0 − σ(50) ≈ 2e-22), so the
735
- # closed interval is the honest numerical bound. Both stable branches
736
- # must honor it, and the sign must track z.
737
- rng = random.Random(SEED + 100)
738
- layer = Layer(input_size=1, output_size=1, activation="sigmoid")
739
- for _ in range(N):
740
- z = rng.uniform(-50, 50)
741
- out = layer._activate(z)
742
- assert 0.0 <= out <= 1.0
743
- # σ(z) > 0.5 iff z > 0 — the midpoint crossing is exact.
744
- assert (out > 0.5) == (z > 0.0)
745
-
746
- def test_relu_is_nonnegative_and_sparse(self) -> None:
747
- # ReLU(z) = max(0, z): non-negative, and zero exactly on z ≤ 0.
748
- rng = random.Random(SEED + 101)
749
- layer = Layer(input_size=1, output_size=1, activation="relu")
750
- for _ in range(N):
751
- z = rng.uniform(-10, 10)
752
- out = layer._activate(z)
753
- assert out >= 0.0
754
- assert (out > 0.0) == (z > 0.0)
755
-
756
- def test_forward_backward_preserves_input_dimension(self) -> None:
757
- # backward() returns a gradient vector whose length equals the input
758
- # dimension of the layer — backprop cannot change the shape.
759
- rng = random.Random(SEED + 102)
760
- for _ in range(N):
761
- in_dim = rng.randint(1, 6)
762
- out_dim = rng.randint(1, 6)
763
- layer = Layer(input_size=in_dim, output_size=out_dim, activation="sigmoid")
764
- x = [rng.uniform(-1, 1) for _ in range(in_dim)]
765
- layer.forward(x)
766
- grad_out = [rng.uniform(-1, 1) for _ in range(out_dim)]
767
- grad_in = layer.backward(grad_out)
768
- assert len(grad_in) == in_dim