scientific-computing-system 1.0.0
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.
- package/.binder/postBuild +9 -0
- package/.binder/requirements.txt +10 -0
- package/.gitattributes +35 -0
- package/.github/CODEOWNERS +4 -0
- package/.github/FUNDING.yml +3 -0
- package/.github/ISSUE_TEMPLATE/bug_report.md +50 -0
- package/.github/ISSUE_TEMPLATE/config.yml +8 -0
- package/.github/ISSUE_TEMPLATE/feature_request.md +28 -0
- package/.github/PULL_REQUEST_TEMPLATE.md +29 -0
- package/.github/dependabot.yml +32 -0
- package/.github/labeler.yml +50 -0
- package/.github/workflows/benchmarks.yml +97 -0
- package/.github/workflows/bot-reviewer.yml +58 -0
- package/.github/workflows/changelog.yml +130 -0
- package/.github/workflows/cli-package-smoke.yml +45 -0
- package/.github/workflows/codeql.yml +55 -0
- package/.github/workflows/npm-publish.yml +33 -0
- package/.github/workflows/p08-cancel-noncanonical-runs.yml +41 -0
- package/.github/workflows/pr-automation.yml +78 -0
- package/.github/workflows/public-external-validation-p08-v2-glm.yml +161 -0
- package/.github/workflows/public-external-validation-p08-v2-recovery-merge-gate.yml +72 -0
- package/.github/workflows/public-external-validation-p08-v2-recovery-merge.yml +113 -0
- package/.github/workflows/public-external-validation-p08-v2-run-recovery-anatomy-gate.yml +57 -0
- package/.github/workflows/public-external-validation-p08-v2-run-recovery-merge-gate.yml +63 -0
- package/.github/workflows/public-external-validation-p08-v2-run-recovery-merge.yml +89 -0
- package/.github/workflows/public-external-validation-p08-v2-run-recovery.yml +182 -0
- package/.github/workflows/public-external-validation-p08-v3-glm-gate.yml +67 -0
- package/.github/workflows/public-external-validation-p08-v4-recovery-glm-gate.yml +78 -0
- package/.github/workflows/public-external-validation-p08-v4-recovery-glm.yml +248 -0
- package/.github/workflows/public-external-validation-p08-v5-run-recovery-glm-gate.yml +66 -0
- package/.github/workflows/public-external-validation-p08-v5-run-recovery-glm.yml +218 -0
- package/.github/workflows/pypi-registry-smoke.yml +116 -0
- package/.github/workflows/release.yml +359 -0
- package/.github/workflows/tests.yml +250 -0
- package/.github/workflows/tmp-compassion-raw-acquire.yml +63 -0
- package/.github/workflows/wsl-science-runner-smoke.yml +45 -0
- package/.pre-commit-config.yaml +48 -0
- package/CHANGELOG.md +1139 -0
- package/CITATION.cff +29 -0
- package/CODE_OF_CONDUCT.md +25 -0
- package/CONTRIBUTING.md +275 -0
- package/LICENSE +21 -0
- package/README.md +281 -0
- package/ROADMAP.md +155 -0
- package/SECURITY.md +82 -0
- package/assets/logo.svg +38 -0
- package/assets/social_preview.png +0 -0
- package/benchmarks/results.json +43 -0
- package/benchmarks/robust_runner.py +118 -0
- package/benchmarks/run_benchmarks.py +394 -0
- package/bin/scs.js +2 -0
- package/cliff.toml +100 -0
- package/dashboard/app.py +224 -0
- package/docs/ARCHITECTURE.md +252 -0
- package/docs/CASE_STUDY_HUBBLE.md +78 -0
- package/docs/CASE_STUDY_QUANTUM_ML.md +79 -0
- package/docs/api.md +133 -0
- package/docs/assets/icon.svg +17 -0
- package/docs/assets/logo.svg +38 -0
- package/docs/benchmarks.md +62 -0
- package/docs/cookbook.md +930 -0
- package/docs/getting-started.md +185 -0
- package/docs/index.md +111 -0
- package/docs/maintenance.md +61 -0
- package/docs/ml_reference.md +92 -0
- package/docs/research-workflows.md +82 -0
- package/docs/stylesheets/extra.css +122 -0
- package/docs/tour_of_numerical_methods.md +330 -0
- package/docs/tutorials/core_demo.md +35 -0
- package/docs/tutorials/data_analysis_demo.md +43 -0
- package/docs/tutorials/diffeq_demo.md +48 -0
- package/docs/tutorials/fft2_demo.md +67 -0
- package/docs/tutorials/graph_demo.md +45 -0
- package/docs/tutorials/hypothesis_demo.md +44 -0
- package/docs/tutorials/hypothesis_tests_demo.md +170 -0
- package/docs/tutorials/hypothesis_with_stats_demo.md +80 -0
- package/docs/tutorials/knowledge_demo.md +114 -0
- package/docs/tutorials/linalg_demo.md +103 -0
- package/docs/tutorials/math_utils_demo.md +46 -0
- package/docs/tutorials/ml_advanced_demo.md +96 -0
- package/docs/tutorials/ml_and_viz_demo.md +93 -0
- package/docs/tutorials/ml_demo.md +70 -0
- package/docs/tutorials/modeling_demo.md +82 -0
- package/docs/tutorials/montecarlo_demo.md +42 -0
- package/docs/tutorials/nlp_attention_demo.md +107 -0
- package/docs/tutorials/nlp_bpe_demo.md +103 -0
- package/docs/tutorials/nlp_mini_gpt_demo.md +110 -0
- package/docs/tutorials/nlp_viz.md +76 -0
- package/docs/tutorials/numerical_integration_demo.md +65 -0
- package/docs/tutorials/optimization_demo.md +106 -0
- package/docs/tutorials/pandas_io_demo.md +160 -0
- package/docs/tutorials/pca_demo.md +87 -0
- package/docs/tutorials/probability_demo.md +48 -0
- package/docs/tutorials/quantum_demo.md +31 -0
- package/docs/tutorials/quick_start.md +44 -0
- package/docs/tutorials/scientific_demo.md +46 -0
- package/docs/tutorials/signals_demo.md +167 -0
- package/docs/tutorials/stats_demo.md +94 -0
- package/docs/tutorials/stiff_ode_demo.md +84 -0
- package/docs/tutorials/time_series_demo.md +145 -0
- package/examples/core_demo.py +40 -0
- package/examples/data_analysis_demo.py +60 -0
- package/examples/diffeq_demo.py +34 -0
- package/examples/discovery_pipeline_demo.py +57 -0
- package/examples/ensemble_showcase.py +81 -0
- package/examples/fft2_demo.py +32 -0
- package/examples/graph_demo.py +49 -0
- package/examples/hypothesis_custom_generator.py +121 -0
- package/examples/hypothesis_demo.py +48 -0
- package/examples/hypothesis_tests_demo.py +52 -0
- package/examples/hypothesis_with_stats_demo.py +43 -0
- package/examples/interpolate_demo.py +57 -0
- package/examples/knowledge_demo.py +100 -0
- package/examples/linalg_demo.py +61 -0
- package/examples/math_utils_demo.py +53 -0
- package/examples/ml_and_viz_demo.py +47 -0
- package/examples/modeling_demo.py +110 -0
- package/examples/montecarlo_demo.py +41 -0
- package/examples/nlp_attention_demo.py +168 -0
- package/examples/nlp_bpe_demo.py +79 -0
- package/examples/nlp_mini_gpt_demo.py +76 -0
- package/examples/nlp_viz_demo.py +98 -0
- package/examples/numerical_integration_demo.py +60 -0
- package/examples/optimization_demo.py +34 -0
- package/examples/pca_demo.py +124 -0
- package/examples/pde_demo.py +65 -0
- package/examples/plot_demo.py +84 -0
- package/examples/plotting_notebook.ipynb +87 -0
- package/examples/probability_demo.py +39 -0
- package/examples/quantum_demo.py +42 -0
- package/examples/scientific_demo.py +49 -0
- package/examples/signals_demo.py +86 -0
- package/examples/stats_demo.py +40 -0
- package/examples/tour_of_numerical_methods.ipynb +497 -0
- package/index.js +1 -0
- package/mkdocs.yml +159 -0
- package/package.json +1 -0
- package/pyproject.toml +288 -0
- package/requirements-dev.lock +427 -0
- package/requirements-dev.txt +39 -0
- package/requirements.lock +6 -0
- package/requirements.txt +13 -0
- package/scripts/build_gif.py +111 -0
- package/scripts/build_video.py +214 -0
- package/scripts/cleanup_deployments.py +173 -0
- package/scripts/crop_readme_png.py +40 -0
- package/scripts/make_pi_dashboard.py +316 -0
- package/scripts/make_pi_gif.py +138 -0
- package/scripts/publish.py +203 -0
- package/scripts/render_promo.mjs +93 -0
- package/scripts/render_readme.py +211 -0
- package/scripts/render_readme_sections.py +168 -0
- package/scripts/verify_cli_install.py +99 -0
- package/scripts/verify_cookbook.py +601 -0
- package/scripts/verify_d1_numerics.py +504 -0
- package/scripts/verify_d2_edge_cases.py +442 -0
- package/scripts/verify_d4_hypothesis.py +337 -0
- package/scripts/verify_ml_reference.py +160 -0
- package/scripts/verify_pypi_release.py +97 -0
- package/scripts/verify_release_integrity.py +194 -0
- package/src/cds/__init__.py +132 -0
- package/src/cds/__main__.py +8 -0
- package/src/cds/_version.py +11 -0
- package/src/cds/bayes/__init__.py +25 -0
- package/src/cds/bayes/conjugate.py +560 -0
- package/src/cds/cli/__init__.py +104 -0
- package/src/cds/cli/__main__.py +8 -0
- package/src/cds/cli/_handlers.py +323 -0
- package/src/cds/cli/_parser.py +155 -0
- package/src/cds/cli/_style.py +208 -0
- package/src/cds/cli/_system_info.py +71 -0
- package/src/cds/core/__init__.py +5 -0
- package/src/cds/core/_numeric.py +92 -0
- package/src/cds/core/models.py +166 -0
- package/src/cds/data_analysis/__init__.py +30 -0
- package/src/cds/data_analysis/dataset.py +122 -0
- package/src/cds/data_analysis/loader.py +75 -0
- package/src/cds/data_analysis/pandas_io.py +108 -0
- package/src/cds/data_analysis/transform.py +36 -0
- package/src/cds/data_analysis/viz.py +88 -0
- package/src/cds/data_io/__init__.py +27 -0
- package/src/cds/data_io/streaming.py +314 -0
- package/src/cds/diffeq/__init__.py +37 -0
- package/src/cds/diffeq/_implicit.py +349 -0
- package/src/cds/diffeq/solvers.py +312 -0
- package/src/cds/diffeq/symplectic.py +225 -0
- package/src/cds/fractals/__init__.py +34 -0
- package/src/cds/fractals/sets.py +356 -0
- package/src/cds/genetics/__init__.py +22 -0
- package/src/cds/genetics/sequence.py +199 -0
- package/src/cds/graph/__init__.py +31 -0
- package/src/cds/graph/algorithms.py +399 -0
- package/src/cds/hypothesis/__init__.py +51 -0
- package/src/cds/hypothesis/evaluator.py +311 -0
- package/src/cds/hypothesis/generator.py +275 -0
- package/src/cds/hypothesis/mining.py +314 -0
- package/src/cds/infotheory/__init__.py +25 -0
- package/src/cds/infotheory/measures.py +276 -0
- package/src/cds/interpolate/__init__.py +156 -0
- package/src/cds/knowledge/__init__.py +45 -0
- package/src/cds/knowledge/graph.py +489 -0
- package/src/cds/knowledge/notes.py +231 -0
- package/src/cds/knowledge/retrieval.py +339 -0
- package/src/cds/math_utils/__init__.py +46 -0
- package/src/cds/math_utils/calculus.py +40 -0
- package/src/cds/math_utils/linalg.py +496 -0
- package/src/cds/math_utils/special.py +167 -0
- package/src/cds/math_utils/svd.py +261 -0
- package/src/cds/ml/__init__.py +60 -0
- package/src/cds/ml/boosting.py +304 -0
- package/src/cds/ml/clustering.py +190 -0
- package/src/cds/ml/decomposition.py +172 -0
- package/src/cds/ml/ensemble.py +152 -0
- package/src/cds/ml/linear_models.py +225 -0
- package/src/cds/ml/metrics.py +227 -0
- package/src/cds/ml/model_selection.py +150 -0
- package/src/cds/ml/naive_bayes.py +179 -0
- package/src/cds/ml/neighbors.py +162 -0
- package/src/cds/ml/neural.py +204 -0
- package/src/cds/ml/preprocessing.py +131 -0
- package/src/cds/ml/tree.py +228 -0
- package/src/cds/ml/voting.py +175 -0
- package/src/cds/modeling/__init__.py +44 -0
- package/src/cds/modeling/_base.py +210 -0
- package/src/cds/modeling/_nodes.py +526 -0
- package/src/cds/modeling/expression.py +81 -0
- package/src/cds/modeling/fitting.py +477 -0
- package/src/cds/modeling/model.py +134 -0
- package/src/cds/modeling/solver.py +187 -0
- package/src/cds/montecarlo/__init__.py +24 -0
- package/src/cds/montecarlo/markov.py +112 -0
- package/src/cds/montecarlo/methods.py +294 -0
- package/src/cds/nlp/__init__.py +170 -0
- package/src/cds/nlp/attention.py +285 -0
- package/src/cds/nlp/autograd/__init__.py +70 -0
- package/src/cds/nlp/autograd/_grad.py +120 -0
- package/src/cds/nlp/autograd/ops.py +133 -0
- package/src/cds/nlp/autograd/tensor.py +298 -0
- package/src/cds/nlp/bpe.py +449 -0
- package/src/cds/nlp/data.py +70 -0
- package/src/cds/nlp/embed.py +190 -0
- package/src/cds/nlp/layers.py +259 -0
- package/src/cds/nlp/model.py +456 -0
- package/src/cds/nlp/optim.py +163 -0
- package/src/cds/nlp/training.py +167 -0
- package/src/cds/nlp/viz.py +254 -0
- package/src/cds/numerical_integration/__init__.py +31 -0
- package/src/cds/numerical_integration/quadrature.py +480 -0
- package/src/cds/optimization/__init__.py +26 -0
- package/src/cds/optimization/_metaheuristics.py +287 -0
- package/src/cds/optimization/constrained.py +212 -0
- package/src/cds/optimization/minimize.py +425 -0
- package/src/cds/pde/__init__.py +266 -0
- package/src/cds/plot/__init__.py +49 -0
- package/src/cds/plot/_backend.py +32 -0
- package/src/cds/plot/charts.py +462 -0
- package/src/cds/probability/__init__.py +65 -0
- package/src/cds/probability/_advanced.py +283 -0
- package/src/cds/probability/distributions.py +236 -0
- package/src/cds/probability/extra_distributions.py +199 -0
- package/src/cds/provenance/__init__.py +25 -0
- package/src/cds/provenance/manifest.py +355 -0
- package/src/cds/py.typed +0 -0
- package/src/cds/quantum/__init__.py +51 -0
- package/src/cds/quantum/circuit.py +122 -0
- package/src/cds/quantum/multi_qubit.py +310 -0
- package/src/cds/quantum/simulator.py +53 -0
- package/src/cds/scientific/__init__.py +34 -0
- package/src/cds/scientific/constants.py +35 -0
- package/src/cds/scientific/formulas.py +116 -0
- package/src/cds/sensitivity.py +204 -0
- package/src/cds/signals/__init__.py +59 -0
- package/src/cds/signals/filters.py +449 -0
- package/src/cds/signals/processing.py +224 -0
- package/src/cds/signals/stft.py +177 -0
- package/src/cds/signals/wavelet.py +146 -0
- package/src/cds/stats/__init__.py +99 -0
- package/src/cds/stats/_distributions.py +102 -0
- package/src/cds/stats/bootstrap.py +188 -0
- package/src/cds/stats/descriptive.py +172 -0
- package/src/cds/stats/hypothesis_tests.py +294 -0
- package/src/cds/stats/nonparametric.py +141 -0
- package/src/cds/stats/power.py +290 -0
- package/src/cds/stats/regression.py +51 -0
- package/src/cds/stats/time_series.py +420 -0
- package/src/cds/tools/__init__.py +29 -0
- package/src/cds/tools/adapters.py +218 -0
- package/src/cds/tools/registry.py +181 -0
- package/src/cds/uncertainty/__init__.py +17 -0
- package/src/cds/uncertainty/propagation.py +233 -0
- package/src/cds/units/__init__.py +45 -0
- package/src/cds/units/core.py +199 -0
- package/src/cds/validation/__init__.py +41 -0
- package/src/cds/validation/adequacy.py +157 -0
- package/src/cds/validation/checks.py +485 -0
- package/src/cds/validation/report.py +50 -0
- package/src/cds/wavelets/__init__.py +5 -0
- package/src/cds/wavelets/haar.py +219 -0
- package/src/cds/workflow/__init__.py +77 -0
- package/src/cds/workflow/engine.py +116 -0
- package/src/cds/workflow/gates.py +120 -0
- package/src/cds/workflow/orchestrator.py +431 -0
- package/src/cds/workflow/selection.py +454 -0
- package/src/cds/workflow/tooling.py +155 -0
- package/src/cds/workflow/types.py +107 -0
- package/tests/__init__.py +0 -0
- package/tests/conftest.py +109 -0
- package/tests/test_advanced_fitting.py +247 -0
- package/tests/test_audit_completion_coverage.py +183 -0
- package/tests/test_audit_guard_coverage.py +115 -0
- package/tests/test_audit_hardening.py +138 -0
- package/tests/test_audit_hardening_coverage.py +111 -0
- package/tests/test_bayes_v2.py +208 -0
- package/tests/test_benchmarks.py +111 -0
- package/tests/test_bootstrap.py +135 -0
- package/tests/test_cli.py +51 -0
- package/tests/test_cli_color.py +114 -0
- package/tests/test_cli_extended.py +239 -0
- package/tests/test_cli_system_info.py +36 -0
- package/tests/test_constrained_opt.py +174 -0
- package/tests/test_core.py +273 -0
- package/tests/test_data_analysis.py +146 -0
- package/tests/test_data_analysis_lazy_bridge.py +68 -0
- package/tests/test_data_analysis_pandas_io.py +119 -0
- package/tests/test_data_io.py +149 -0
- package/tests/test_dataset.py +91 -0
- package/tests/test_diffeq.py +186 -0
- package/tests/test_diffeq_implicit.py +173 -0
- package/tests/test_domain_validation.py +66 -0
- package/tests/test_edge_misc_numerical.py +666 -0
- package/tests/test_edge_ml_quantum_linalg.py +191 -0
- package/tests/test_edge_nlp.py +229 -0
- package/tests/test_edge_quantum_evaluator_cli.py +601 -0
- package/tests/test_edge_stats_optimization_signals.py +406 -0
- package/tests/test_extra_distributions.py +206 -0
- package/tests/test_fft2.py +67 -0
- package/tests/test_fitting_bootstrap.py +202 -0
- package/tests/test_fractals.py +387 -0
- package/tests/test_genetics.py +159 -0
- package/tests/test_graph.py +380 -0
- package/tests/test_hardening_privacy_provenance.py +306 -0
- package/tests/test_hypothesis.py +216 -0
- package/tests/test_hypothesis_engine.py +59 -0
- package/tests/test_hypothesis_mining.py +247 -0
- package/tests/test_hypothesis_tests.py +277 -0
- package/tests/test_infotheory.py +302 -0
- package/tests/test_interpolate.py +189 -0
- package/tests/test_knowledge.py +1149 -0
- package/tests/test_layering.py +112 -0
- package/tests/test_linalg_extended.py +179 -0
- package/tests/test_linalg_qr_cholesky.py +68 -0
- package/tests/test_markov.py +155 -0
- package/tests/test_math_utils.py +157 -0
- package/tests/test_ml_boosting.py +148 -0
- package/tests/test_ml_clustering.py +92 -0
- package/tests/test_ml_ensemble.py +103 -0
- package/tests/test_ml_knn.py +95 -0
- package/tests/test_ml_linreg.py +70 -0
- package/tests/test_ml_logreg.py +84 -0
- package/tests/test_ml_metrics.py +125 -0
- package/tests/test_ml_model_selection.py +108 -0
- package/tests/test_ml_naive_bayes.py +183 -0
- package/tests/test_ml_pca.py +98 -0
- package/tests/test_ml_preprocessing.py +104 -0
- package/tests/test_ml_tree.py +89 -0
- package/tests/test_ml_viz.py +58 -0
- package/tests/test_ml_voting.py +219 -0
- package/tests/test_modeling.py +726 -0
- package/tests/test_modeling_fit_validation.py +46 -0
- package/tests/test_montecarlo.py +245 -0
- package/tests/test_multi_qubit.py +466 -0
- package/tests/test_nlp_attention.py +335 -0
- package/tests/test_nlp_autograd.py +435 -0
- package/tests/test_nlp_bpe.py +463 -0
- package/tests/test_nlp_embed.py +240 -0
- package/tests/test_nlp_layers.py +276 -0
- package/tests/test_nlp_model.py +172 -0
- package/tests/test_nlp_training.py +262 -0
- package/tests/test_nlp_viz.py +188 -0
- package/tests/test_numerical_integration.py +374 -0
- package/tests/test_numerical_invariants.py +768 -0
- package/tests/test_numerical_oracles.py +241 -0
- package/tests/test_optimization.py +139 -0
- package/tests/test_optimization_metaheuristics.py +221 -0
- package/tests/test_pde.py +294 -0
- package/tests/test_plot_charts.py +247 -0
- package/tests/test_plot_lazy.py +48 -0
- package/tests/test_power.py +226 -0
- package/tests/test_probability.py +274 -0
- package/tests/test_probability_advanced.py +226 -0
- package/tests/test_property_invariants.py +277 -0
- package/tests/test_provenance.py +215 -0
- package/tests/test_provenance_audit_hardening.py +45 -0
- package/tests/test_public_api.py +75 -0
- package/tests/test_quantum.py +195 -0
- package/tests/test_release_contract.py +105 -0
- package/tests/test_retrieval.py +255 -0
- package/tests/test_scientific.py +185 -0
- package/tests/test_selection_audit_hardening.py +55 -0
- package/tests/test_sensitivity.py +59 -0
- package/tests/test_sensitivity_global.py +73 -0
- package/tests/test_signals.py +146 -0
- package/tests/test_signals_filters.py +460 -0
- package/tests/test_special_invariants.py +222 -0
- package/tests/test_special_numerics.py +44 -0
- package/tests/test_statistical_audit.py +75 -0
- package/tests/test_stats.py +206 -0
- package/tests/test_stats_audit_coverage.py +17 -0
- package/tests/test_stats_nonparametric.py +87 -0
- package/tests/test_stats_time_series.py +352 -0
- package/tests/test_stft.py +208 -0
- package/tests/test_streaming_analytics.py +128 -0
- package/tests/test_svd.py +170 -0
- package/tests/test_symplectic.py +200 -0
- package/tests/test_tool_adapters.py +197 -0
- package/tests/test_tools_registry.py +132 -0
- package/tests/test_uncertainty.py +171 -0
- package/tests/test_units.py +139 -0
- package/tests/test_validation.py +100 -0
- package/tests/test_validation_adequacy.py +129 -0
- package/tests/test_validation_advanced.py +110 -0
- package/tests/test_wavelet.py +170 -0
- package/tests/test_wavelets_v2.py +119 -0
- package/tests/test_workflow.py +173 -0
- package/tests/test_workflow_gates.py +144 -0
- package/tests/test_workflow_orchestrator.py +516 -0
- package/tests/test_workflow_orchestrator_blocked_review.py +95 -0
- package/tests/test_workflow_selection.py +312 -0
- package/tests/test_workflow_selection_coverage.py +114 -0
- package/tests/test_workflow_tooling.py +190 -0
|
@@ -0,0 +1,768 @@
|
|
|
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
|