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.
- package/CHANGELOG.md +365 -0
- package/LICENSE +0 -0
- package/README.md +146 -217
- package/SECURITY.md +32 -6
- package/bin/scs.js +12 -2
- package/index.js +115 -1
- package/package.json +45 -1
- package/.binder/postBuild +0 -9
- package/.binder/requirements.txt +0 -10
- package/.gitattributes +0 -35
- package/.github/CODEOWNERS +0 -4
- package/.github/FUNDING.yml +0 -3
- package/.github/ISSUE_TEMPLATE/bug_report.md +0 -50
- package/.github/ISSUE_TEMPLATE/config.yml +0 -8
- package/.github/ISSUE_TEMPLATE/feature_request.md +0 -28
- package/.github/PULL_REQUEST_TEMPLATE.md +0 -29
- package/.github/dependabot.yml +0 -32
- package/.github/labeler.yml +0 -50
- package/.github/workflows/benchmarks.yml +0 -97
- package/.github/workflows/bot-reviewer.yml +0 -58
- package/.github/workflows/changelog.yml +0 -130
- package/.github/workflows/cli-package-smoke.yml +0 -45
- package/.github/workflows/codeql.yml +0 -55
- package/.github/workflows/npm-publish.yml +0 -33
- package/.github/workflows/p08-cancel-noncanonical-runs.yml +0 -41
- package/.github/workflows/pr-automation.yml +0 -78
- package/.github/workflows/public-external-validation-p08-v2-glm.yml +0 -161
- package/.github/workflows/public-external-validation-p08-v2-recovery-merge-gate.yml +0 -72
- package/.github/workflows/public-external-validation-p08-v2-recovery-merge.yml +0 -113
- package/.github/workflows/public-external-validation-p08-v2-run-recovery-anatomy-gate.yml +0 -57
- package/.github/workflows/public-external-validation-p08-v2-run-recovery-merge-gate.yml +0 -63
- package/.github/workflows/public-external-validation-p08-v2-run-recovery-merge.yml +0 -89
- package/.github/workflows/public-external-validation-p08-v2-run-recovery.yml +0 -182
- package/.github/workflows/public-external-validation-p08-v3-glm-gate.yml +0 -67
- package/.github/workflows/public-external-validation-p08-v4-recovery-glm-gate.yml +0 -78
- package/.github/workflows/public-external-validation-p08-v4-recovery-glm.yml +0 -248
- package/.github/workflows/public-external-validation-p08-v5-run-recovery-glm-gate.yml +0 -66
- package/.github/workflows/public-external-validation-p08-v5-run-recovery-glm.yml +0 -218
- package/.github/workflows/pypi-registry-smoke.yml +0 -116
- package/.github/workflows/release.yml +0 -359
- package/.github/workflows/tests.yml +0 -250
- package/.github/workflows/tmp-compassion-raw-acquire.yml +0 -63
- package/.github/workflows/wsl-science-runner-smoke.yml +0 -45
- package/.pre-commit-config.yaml +0 -48
- package/CITATION.cff +0 -29
- package/CODE_OF_CONDUCT.md +0 -25
- package/CONTRIBUTING.md +0 -275
- package/ROADMAP.md +0 -155
- package/assets/logo.svg +0 -38
- package/assets/social_preview.png +0 -0
- package/benchmarks/results.json +0 -43
- package/benchmarks/robust_runner.py +0 -118
- package/benchmarks/run_benchmarks.py +0 -394
- package/cliff.toml +0 -100
- package/dashboard/app.py +0 -224
- package/docs/ARCHITECTURE.md +0 -252
- package/docs/CASE_STUDY_HUBBLE.md +0 -78
- package/docs/CASE_STUDY_QUANTUM_ML.md +0 -79
- package/docs/api.md +0 -133
- package/docs/assets/icon.svg +0 -17
- package/docs/assets/logo.svg +0 -38
- package/docs/benchmarks.md +0 -62
- package/docs/cookbook.md +0 -930
- package/docs/getting-started.md +0 -185
- package/docs/index.md +0 -111
- package/docs/maintenance.md +0 -61
- package/docs/ml_reference.md +0 -92
- package/docs/research-workflows.md +0 -82
- package/docs/stylesheets/extra.css +0 -122
- package/docs/tour_of_numerical_methods.md +0 -330
- package/docs/tutorials/core_demo.md +0 -35
- package/docs/tutorials/data_analysis_demo.md +0 -43
- package/docs/tutorials/diffeq_demo.md +0 -48
- package/docs/tutorials/fft2_demo.md +0 -67
- package/docs/tutorials/graph_demo.md +0 -45
- package/docs/tutorials/hypothesis_demo.md +0 -44
- package/docs/tutorials/hypothesis_tests_demo.md +0 -170
- package/docs/tutorials/hypothesis_with_stats_demo.md +0 -80
- package/docs/tutorials/knowledge_demo.md +0 -114
- package/docs/tutorials/linalg_demo.md +0 -103
- package/docs/tutorials/math_utils_demo.md +0 -46
- package/docs/tutorials/ml_advanced_demo.md +0 -96
- package/docs/tutorials/ml_and_viz_demo.md +0 -93
- package/docs/tutorials/ml_demo.md +0 -70
- package/docs/tutorials/modeling_demo.md +0 -82
- package/docs/tutorials/montecarlo_demo.md +0 -42
- package/docs/tutorials/nlp_attention_demo.md +0 -107
- package/docs/tutorials/nlp_bpe_demo.md +0 -103
- package/docs/tutorials/nlp_mini_gpt_demo.md +0 -110
- package/docs/tutorials/nlp_viz.md +0 -76
- package/docs/tutorials/numerical_integration_demo.md +0 -65
- package/docs/tutorials/optimization_demo.md +0 -106
- package/docs/tutorials/pandas_io_demo.md +0 -160
- package/docs/tutorials/pca_demo.md +0 -87
- package/docs/tutorials/probability_demo.md +0 -48
- package/docs/tutorials/quantum_demo.md +0 -31
- package/docs/tutorials/quick_start.md +0 -44
- package/docs/tutorials/scientific_demo.md +0 -46
- package/docs/tutorials/signals_demo.md +0 -167
- package/docs/tutorials/stats_demo.md +0 -94
- package/docs/tutorials/stiff_ode_demo.md +0 -84
- package/docs/tutorials/time_series_demo.md +0 -145
- package/examples/core_demo.py +0 -40
- package/examples/data_analysis_demo.py +0 -60
- package/examples/diffeq_demo.py +0 -34
- package/examples/discovery_pipeline_demo.py +0 -57
- package/examples/ensemble_showcase.py +0 -81
- package/examples/fft2_demo.py +0 -32
- package/examples/graph_demo.py +0 -49
- package/examples/hypothesis_custom_generator.py +0 -121
- package/examples/hypothesis_demo.py +0 -48
- package/examples/hypothesis_tests_demo.py +0 -52
- package/examples/hypothesis_with_stats_demo.py +0 -43
- package/examples/interpolate_demo.py +0 -57
- package/examples/knowledge_demo.py +0 -100
- package/examples/linalg_demo.py +0 -61
- package/examples/math_utils_demo.py +0 -53
- package/examples/ml_and_viz_demo.py +0 -47
- package/examples/modeling_demo.py +0 -110
- package/examples/montecarlo_demo.py +0 -41
- package/examples/nlp_attention_demo.py +0 -168
- package/examples/nlp_bpe_demo.py +0 -79
- package/examples/nlp_mini_gpt_demo.py +0 -76
- package/examples/nlp_viz_demo.py +0 -98
- package/examples/numerical_integration_demo.py +0 -60
- package/examples/optimization_demo.py +0 -34
- package/examples/pca_demo.py +0 -124
- package/examples/pde_demo.py +0 -65
- package/examples/plot_demo.py +0 -84
- package/examples/plotting_notebook.ipynb +0 -87
- package/examples/probability_demo.py +0 -39
- package/examples/quantum_demo.py +0 -42
- package/examples/scientific_demo.py +0 -49
- package/examples/signals_demo.py +0 -86
- package/examples/stats_demo.py +0 -40
- package/examples/tour_of_numerical_methods.ipynb +0 -497
- package/mkdocs.yml +0 -159
- package/pyproject.toml +0 -288
- package/requirements-dev.lock +0 -427
- package/requirements-dev.txt +0 -39
- package/requirements.lock +0 -6
- package/requirements.txt +0 -13
- package/scripts/build_gif.py +0 -111
- package/scripts/build_video.py +0 -214
- package/scripts/cleanup_deployments.py +0 -173
- package/scripts/crop_readme_png.py +0 -40
- package/scripts/make_pi_dashboard.py +0 -316
- package/scripts/make_pi_gif.py +0 -138
- package/scripts/publish.py +0 -203
- package/scripts/render_promo.mjs +0 -93
- package/scripts/render_readme.py +0 -211
- package/scripts/render_readme_sections.py +0 -168
- package/scripts/verify_cli_install.py +0 -99
- package/scripts/verify_cookbook.py +0 -601
- package/scripts/verify_d1_numerics.py +0 -504
- package/scripts/verify_d2_edge_cases.py +0 -442
- package/scripts/verify_d4_hypothesis.py +0 -337
- package/scripts/verify_ml_reference.py +0 -160
- package/scripts/verify_pypi_release.py +0 -97
- package/scripts/verify_release_integrity.py +0 -194
- package/src/cds/__init__.py +0 -132
- package/src/cds/__main__.py +0 -8
- package/src/cds/_version.py +0 -11
- package/src/cds/bayes/__init__.py +0 -25
- package/src/cds/bayes/conjugate.py +0 -560
- package/src/cds/cli/__init__.py +0 -104
- package/src/cds/cli/__main__.py +0 -8
- package/src/cds/cli/_handlers.py +0 -323
- package/src/cds/cli/_parser.py +0 -155
- package/src/cds/cli/_style.py +0 -208
- package/src/cds/cli/_system_info.py +0 -71
- package/src/cds/core/__init__.py +0 -5
- package/src/cds/core/_numeric.py +0 -92
- package/src/cds/core/models.py +0 -166
- package/src/cds/data_analysis/__init__.py +0 -30
- package/src/cds/data_analysis/dataset.py +0 -122
- package/src/cds/data_analysis/loader.py +0 -75
- package/src/cds/data_analysis/pandas_io.py +0 -108
- package/src/cds/data_analysis/transform.py +0 -36
- package/src/cds/data_analysis/viz.py +0 -88
- package/src/cds/data_io/__init__.py +0 -27
- package/src/cds/data_io/streaming.py +0 -314
- package/src/cds/diffeq/__init__.py +0 -37
- package/src/cds/diffeq/_implicit.py +0 -349
- package/src/cds/diffeq/solvers.py +0 -312
- package/src/cds/diffeq/symplectic.py +0 -225
- package/src/cds/fractals/__init__.py +0 -34
- package/src/cds/fractals/sets.py +0 -356
- package/src/cds/genetics/__init__.py +0 -22
- package/src/cds/genetics/sequence.py +0 -199
- package/src/cds/graph/__init__.py +0 -31
- package/src/cds/graph/algorithms.py +0 -399
- package/src/cds/hypothesis/__init__.py +0 -51
- package/src/cds/hypothesis/evaluator.py +0 -311
- package/src/cds/hypothesis/generator.py +0 -275
- package/src/cds/hypothesis/mining.py +0 -314
- package/src/cds/infotheory/__init__.py +0 -25
- package/src/cds/infotheory/measures.py +0 -276
- package/src/cds/interpolate/__init__.py +0 -156
- package/src/cds/knowledge/__init__.py +0 -45
- package/src/cds/knowledge/graph.py +0 -489
- package/src/cds/knowledge/notes.py +0 -231
- package/src/cds/knowledge/retrieval.py +0 -339
- package/src/cds/math_utils/__init__.py +0 -46
- package/src/cds/math_utils/calculus.py +0 -40
- package/src/cds/math_utils/linalg.py +0 -496
- package/src/cds/math_utils/special.py +0 -167
- package/src/cds/math_utils/svd.py +0 -261
- package/src/cds/ml/__init__.py +0 -60
- package/src/cds/ml/boosting.py +0 -304
- package/src/cds/ml/clustering.py +0 -190
- package/src/cds/ml/decomposition.py +0 -172
- package/src/cds/ml/ensemble.py +0 -152
- package/src/cds/ml/linear_models.py +0 -225
- package/src/cds/ml/metrics.py +0 -227
- package/src/cds/ml/model_selection.py +0 -150
- package/src/cds/ml/naive_bayes.py +0 -179
- package/src/cds/ml/neighbors.py +0 -162
- package/src/cds/ml/neural.py +0 -204
- package/src/cds/ml/preprocessing.py +0 -131
- package/src/cds/ml/tree.py +0 -228
- package/src/cds/ml/voting.py +0 -175
- package/src/cds/modeling/__init__.py +0 -44
- package/src/cds/modeling/_base.py +0 -210
- package/src/cds/modeling/_nodes.py +0 -526
- package/src/cds/modeling/expression.py +0 -81
- package/src/cds/modeling/fitting.py +0 -477
- package/src/cds/modeling/model.py +0 -134
- package/src/cds/modeling/solver.py +0 -187
- package/src/cds/montecarlo/__init__.py +0 -24
- package/src/cds/montecarlo/markov.py +0 -112
- package/src/cds/montecarlo/methods.py +0 -294
- package/src/cds/nlp/__init__.py +0 -170
- package/src/cds/nlp/attention.py +0 -285
- package/src/cds/nlp/autograd/__init__.py +0 -70
- package/src/cds/nlp/autograd/_grad.py +0 -120
- package/src/cds/nlp/autograd/ops.py +0 -133
- package/src/cds/nlp/autograd/tensor.py +0 -298
- package/src/cds/nlp/bpe.py +0 -449
- package/src/cds/nlp/data.py +0 -70
- package/src/cds/nlp/embed.py +0 -190
- package/src/cds/nlp/layers.py +0 -259
- package/src/cds/nlp/model.py +0 -456
- package/src/cds/nlp/optim.py +0 -163
- package/src/cds/nlp/training.py +0 -167
- package/src/cds/nlp/viz.py +0 -254
- package/src/cds/numerical_integration/__init__.py +0 -31
- package/src/cds/numerical_integration/quadrature.py +0 -480
- package/src/cds/optimization/__init__.py +0 -26
- package/src/cds/optimization/_metaheuristics.py +0 -287
- package/src/cds/optimization/constrained.py +0 -212
- package/src/cds/optimization/minimize.py +0 -425
- package/src/cds/pde/__init__.py +0 -266
- package/src/cds/plot/__init__.py +0 -49
- package/src/cds/plot/_backend.py +0 -32
- package/src/cds/plot/charts.py +0 -462
- package/src/cds/probability/__init__.py +0 -65
- package/src/cds/probability/_advanced.py +0 -283
- package/src/cds/probability/distributions.py +0 -236
- package/src/cds/probability/extra_distributions.py +0 -199
- package/src/cds/provenance/__init__.py +0 -25
- package/src/cds/provenance/manifest.py +0 -355
- package/src/cds/py.typed +0 -0
- package/src/cds/quantum/__init__.py +0 -51
- package/src/cds/quantum/circuit.py +0 -122
- package/src/cds/quantum/multi_qubit.py +0 -310
- package/src/cds/quantum/simulator.py +0 -53
- package/src/cds/scientific/__init__.py +0 -34
- package/src/cds/scientific/constants.py +0 -35
- package/src/cds/scientific/formulas.py +0 -116
- package/src/cds/sensitivity.py +0 -204
- package/src/cds/signals/__init__.py +0 -59
- package/src/cds/signals/filters.py +0 -449
- package/src/cds/signals/processing.py +0 -224
- package/src/cds/signals/stft.py +0 -177
- package/src/cds/signals/wavelet.py +0 -146
- package/src/cds/stats/__init__.py +0 -99
- package/src/cds/stats/_distributions.py +0 -102
- package/src/cds/stats/bootstrap.py +0 -188
- package/src/cds/stats/descriptive.py +0 -172
- package/src/cds/stats/hypothesis_tests.py +0 -294
- package/src/cds/stats/nonparametric.py +0 -141
- package/src/cds/stats/power.py +0 -290
- package/src/cds/stats/regression.py +0 -51
- package/src/cds/stats/time_series.py +0 -420
- package/src/cds/tools/__init__.py +0 -29
- package/src/cds/tools/adapters.py +0 -218
- package/src/cds/tools/registry.py +0 -181
- package/src/cds/uncertainty/__init__.py +0 -17
- package/src/cds/uncertainty/propagation.py +0 -233
- package/src/cds/units/__init__.py +0 -45
- package/src/cds/units/core.py +0 -199
- package/src/cds/validation/__init__.py +0 -41
- package/src/cds/validation/adequacy.py +0 -157
- package/src/cds/validation/checks.py +0 -485
- package/src/cds/validation/report.py +0 -50
- package/src/cds/wavelets/__init__.py +0 -5
- package/src/cds/wavelets/haar.py +0 -219
- package/src/cds/workflow/__init__.py +0 -77
- package/src/cds/workflow/engine.py +0 -116
- package/src/cds/workflow/gates.py +0 -120
- package/src/cds/workflow/orchestrator.py +0 -431
- package/src/cds/workflow/selection.py +0 -454
- package/src/cds/workflow/tooling.py +0 -155
- package/src/cds/workflow/types.py +0 -107
- package/tests/__init__.py +0 -0
- package/tests/conftest.py +0 -109
- package/tests/test_advanced_fitting.py +0 -247
- package/tests/test_audit_completion_coverage.py +0 -183
- package/tests/test_audit_guard_coverage.py +0 -115
- package/tests/test_audit_hardening.py +0 -138
- package/tests/test_audit_hardening_coverage.py +0 -111
- package/tests/test_bayes_v2.py +0 -208
- package/tests/test_benchmarks.py +0 -111
- package/tests/test_bootstrap.py +0 -135
- package/tests/test_cli.py +0 -51
- package/tests/test_cli_color.py +0 -114
- package/tests/test_cli_extended.py +0 -239
- package/tests/test_cli_system_info.py +0 -36
- package/tests/test_constrained_opt.py +0 -174
- package/tests/test_core.py +0 -273
- package/tests/test_data_analysis.py +0 -146
- package/tests/test_data_analysis_lazy_bridge.py +0 -68
- package/tests/test_data_analysis_pandas_io.py +0 -119
- package/tests/test_data_io.py +0 -149
- package/tests/test_dataset.py +0 -91
- package/tests/test_diffeq.py +0 -186
- package/tests/test_diffeq_implicit.py +0 -173
- package/tests/test_domain_validation.py +0 -66
- package/tests/test_edge_misc_numerical.py +0 -666
- package/tests/test_edge_ml_quantum_linalg.py +0 -191
- package/tests/test_edge_nlp.py +0 -229
- package/tests/test_edge_quantum_evaluator_cli.py +0 -601
- package/tests/test_edge_stats_optimization_signals.py +0 -406
- package/tests/test_extra_distributions.py +0 -206
- package/tests/test_fft2.py +0 -67
- package/tests/test_fitting_bootstrap.py +0 -202
- package/tests/test_fractals.py +0 -387
- package/tests/test_genetics.py +0 -159
- package/tests/test_graph.py +0 -380
- package/tests/test_hardening_privacy_provenance.py +0 -306
- package/tests/test_hypothesis.py +0 -216
- package/tests/test_hypothesis_engine.py +0 -59
- package/tests/test_hypothesis_mining.py +0 -247
- package/tests/test_hypothesis_tests.py +0 -277
- package/tests/test_infotheory.py +0 -302
- package/tests/test_interpolate.py +0 -189
- package/tests/test_knowledge.py +0 -1149
- package/tests/test_layering.py +0 -112
- package/tests/test_linalg_extended.py +0 -179
- package/tests/test_linalg_qr_cholesky.py +0 -68
- package/tests/test_markov.py +0 -155
- package/tests/test_math_utils.py +0 -157
- package/tests/test_ml_boosting.py +0 -148
- package/tests/test_ml_clustering.py +0 -92
- package/tests/test_ml_ensemble.py +0 -103
- package/tests/test_ml_knn.py +0 -95
- package/tests/test_ml_linreg.py +0 -70
- package/tests/test_ml_logreg.py +0 -84
- package/tests/test_ml_metrics.py +0 -125
- package/tests/test_ml_model_selection.py +0 -108
- package/tests/test_ml_naive_bayes.py +0 -183
- package/tests/test_ml_pca.py +0 -98
- package/tests/test_ml_preprocessing.py +0 -104
- package/tests/test_ml_tree.py +0 -89
- package/tests/test_ml_viz.py +0 -58
- package/tests/test_ml_voting.py +0 -219
- package/tests/test_modeling.py +0 -726
- package/tests/test_modeling_fit_validation.py +0 -46
- package/tests/test_montecarlo.py +0 -245
- package/tests/test_multi_qubit.py +0 -466
- package/tests/test_nlp_attention.py +0 -335
- package/tests/test_nlp_autograd.py +0 -435
- package/tests/test_nlp_bpe.py +0 -463
- package/tests/test_nlp_embed.py +0 -240
- package/tests/test_nlp_layers.py +0 -276
- package/tests/test_nlp_model.py +0 -172
- package/tests/test_nlp_training.py +0 -262
- package/tests/test_nlp_viz.py +0 -188
- package/tests/test_numerical_integration.py +0 -374
- package/tests/test_numerical_invariants.py +0 -768
- package/tests/test_numerical_oracles.py +0 -241
- package/tests/test_optimization.py +0 -139
- package/tests/test_optimization_metaheuristics.py +0 -221
- package/tests/test_pde.py +0 -294
- package/tests/test_plot_charts.py +0 -247
- package/tests/test_plot_lazy.py +0 -48
- package/tests/test_power.py +0 -226
- package/tests/test_probability.py +0 -274
- package/tests/test_probability_advanced.py +0 -226
- package/tests/test_property_invariants.py +0 -277
- package/tests/test_provenance.py +0 -215
- package/tests/test_provenance_audit_hardening.py +0 -45
- package/tests/test_public_api.py +0 -75
- package/tests/test_quantum.py +0 -195
- package/tests/test_release_contract.py +0 -105
- package/tests/test_retrieval.py +0 -255
- package/tests/test_scientific.py +0 -185
- package/tests/test_selection_audit_hardening.py +0 -55
- package/tests/test_sensitivity.py +0 -59
- package/tests/test_sensitivity_global.py +0 -73
- package/tests/test_signals.py +0 -146
- package/tests/test_signals_filters.py +0 -460
- package/tests/test_special_invariants.py +0 -222
- package/tests/test_special_numerics.py +0 -44
- package/tests/test_statistical_audit.py +0 -75
- package/tests/test_stats.py +0 -206
- package/tests/test_stats_audit_coverage.py +0 -17
- package/tests/test_stats_nonparametric.py +0 -87
- package/tests/test_stats_time_series.py +0 -352
- package/tests/test_stft.py +0 -208
- package/tests/test_streaming_analytics.py +0 -128
- package/tests/test_svd.py +0 -170
- package/tests/test_symplectic.py +0 -200
- package/tests/test_tool_adapters.py +0 -197
- package/tests/test_tools_registry.py +0 -132
- package/tests/test_uncertainty.py +0 -171
- package/tests/test_units.py +0 -139
- package/tests/test_validation.py +0 -100
- package/tests/test_validation_adequacy.py +0 -129
- package/tests/test_validation_advanced.py +0 -110
- package/tests/test_wavelet.py +0 -170
- package/tests/test_wavelets_v2.py +0 -119
- package/tests/test_workflow.py +0 -173
- package/tests/test_workflow_gates.py +0 -144
- package/tests/test_workflow_orchestrator.py +0 -516
- package/tests/test_workflow_orchestrator_blocked_review.py +0 -95
- package/tests/test_workflow_selection.py +0 -312
- package/tests/test_workflow_selection_coverage.py +0 -114
- package/tests/test_workflow_tooling.py +0 -190
|
@@ -1,314 +0,0 @@
|
|
|
1
|
-
"""Correlation-driven hypothesis mining over tabular numeric data.
|
|
2
|
-
|
|
3
|
-
This module is the hypothesis-mining engine of CDS: given a plain
|
|
4
|
-
``dict[str, list[float]]`` dataset it scans every pairwise combination of
|
|
5
|
-
numeric columns, computes the Pearson correlation coefficient, judges its
|
|
6
|
-
statistical significance, and emits :class:`MinedHypothesis` records whose
|
|
7
|
-
embedded :class:`~cds.core.models.Hypothesis` objects plug directly into the
|
|
8
|
-
existing evaluator/statistics pipeline
|
|
9
|
-
(:class:`~cds.hypothesis.evaluator.HypothesisEvaluator`).
|
|
10
|
-
|
|
11
|
-
Strength tiers (Cohen-style conventions applied to ``|r|``):
|
|
12
|
-
|
|
13
|
-
- ``"weak"`` -- ``|r| < 0.2``
|
|
14
|
-
- ``"moderate"`` -- ``0.2 <= |r| < 0.5``
|
|
15
|
-
- ``"strong"`` -- ``|r| >= 0.5``
|
|
16
|
-
|
|
17
|
-
Boundary values belong to the higher tier: ``|r| = 0.2`` classifies as
|
|
18
|
-
``"moderate"`` and ``|r| = 0.5`` classifies as ``"strong"``.
|
|
19
|
-
|
|
20
|
-
Significance follows the standard Student-t transformation of Pearson's
|
|
21
|
-
coefficient, ``t = r * sqrt((n - 2) / (1 - r^2))`` with ``n - 2`` degrees
|
|
22
|
-
of freedom and a two-sided p-value obtained from the existing survival
|
|
23
|
-
function :func:`cds.stats.hypothesis_tests.t_sf`. A perfect sample
|
|
24
|
-
correlation (``|r| = 1``) short-circuits to ``p = 0.0`` because the t
|
|
25
|
-
statistic diverges.
|
|
26
|
-
|
|
27
|
-
Constant columns (zero variance, detected as every value identical to the
|
|
28
|
-
first) are skipped silently: they cannot enter a meaningful Pearson
|
|
29
|
-
correlation, so they are excluded from consideration before pairing and do
|
|
30
|
-
not raise or otherwise surface to the caller.
|
|
31
|
-
|
|
32
|
-
References:
|
|
33
|
-
- Fisher, R. A. (1921). "On the 'probable error' of a coefficient of
|
|
34
|
-
correlation deduced from a small sample." Metron, 1(4), 3-32.
|
|
35
|
-
(t-transformation of Pearson's r)
|
|
36
|
-
- Student [W. S. Gosset] (1908). Biometrika, 6(1), 1-25.
|
|
37
|
-
(t distribution / two-tailed tail probability)
|
|
38
|
-
"""
|
|
39
|
-
|
|
40
|
-
from __future__ import annotations
|
|
41
|
-
|
|
42
|
-
import math
|
|
43
|
-
from dataclasses import dataclass
|
|
44
|
-
|
|
45
|
-
from cds.core.models import Domain, Hypothesis, HypothesisStatus
|
|
46
|
-
from cds.stats.descriptive import correlation
|
|
47
|
-
from cds.stats.hypothesis_tests import t_sf
|
|
48
|
-
|
|
49
|
-
__all__ = ["MinedHypothesis", "mine_correlations"]
|
|
50
|
-
|
|
51
|
-
WEAK_THRESHOLD = 0.2
|
|
52
|
-
"""Lower bound of the "moderate" tier; below it a correlation is "weak"."""
|
|
53
|
-
|
|
54
|
-
STRONG_THRESHOLD = 0.5
|
|
55
|
-
"""Lower bound of the "strong" tier (inclusive)."""
|
|
56
|
-
|
|
57
|
-
_STRENGTH_CONFIDENCE: dict[str, float] = {"weak": 0.4, "moderate": 0.6, "strong": 0.85}
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
@dataclass
|
|
61
|
-
class MinedHypothesis:
|
|
62
|
-
"""A statistically significant pairwise association surfaced by mining.
|
|
63
|
-
|
|
64
|
-
Attributes:
|
|
65
|
-
feature_a: Name of the first numeric column.
|
|
66
|
-
feature_b: Name of the second numeric column.
|
|
67
|
-
correlation: Sample Pearson correlation coefficient in ``[-1.0, 1.0]``.
|
|
68
|
-
p_value: Two-sided p-value testing H0: population correlation is zero.
|
|
69
|
-
strength: Qualitative effect-size tier — one of ``"weak"``,
|
|
70
|
-
``"moderate"``, ``"strong"`` (thresholds 0.2 / 0.5 on ``|r|``,
|
|
71
|
-
boundaries included in the higher tier).
|
|
72
|
-
hypothesis: Fully populated :class:`~cds.core.models.Hypothesis`
|
|
73
|
-
carrying statement, rationale, assumptions and predictions derived
|
|
74
|
-
from the observed numbers, ready for the evaluator pipeline.
|
|
75
|
-
"""
|
|
76
|
-
|
|
77
|
-
feature_a: str
|
|
78
|
-
feature_b: str
|
|
79
|
-
correlation: float
|
|
80
|
-
p_value: float
|
|
81
|
-
strength: str
|
|
82
|
-
hypothesis: Hypothesis
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
def _classify_strength(abs_r: float) -> str:
|
|
86
|
-
"""Map an absolute correlation onto its documented qualitative tier.
|
|
87
|
-
|
|
88
|
-
Args:
|
|
89
|
-
abs_r: Absolute value of a Pearson correlation coefficient.
|
|
90
|
-
|
|
91
|
-
Returns:
|
|
92
|
-
``"strong"`` when ``abs_r >= 0.5``, ``"moderate"`` when
|
|
93
|
-
``abs_r >= 0.2``, and ``"weak"`` otherwise. Boundary values join the
|
|
94
|
-
higher tier.
|
|
95
|
-
"""
|
|
96
|
-
if abs_r >= STRONG_THRESHOLD:
|
|
97
|
-
return "strong"
|
|
98
|
-
if abs_r >= WEAK_THRESHOLD:
|
|
99
|
-
return "moderate"
|
|
100
|
-
return "weak"
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
def _is_constant(values: list[float]) -> bool:
|
|
104
|
-
"""Return whether every entry equals the first (a zero-variance column).
|
|
105
|
-
|
|
106
|
-
Args:
|
|
107
|
-
values: Column values (guaranteed non-empty by upstream validation).
|
|
108
|
-
|
|
109
|
-
Returns:
|
|
110
|
-
True if the column is constant and therefore unusable for Pearson
|
|
111
|
-
correlation.
|
|
112
|
-
"""
|
|
113
|
-
return all(value == values[0] for value in values)
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
def _pearson_p_value(r: float, n: int) -> float:
|
|
117
|
-
"""Two-sided p-value for H0: the population Pearson correlation is zero.
|
|
118
|
-
|
|
119
|
-
Uses the classical transformation ``t = |r| * sqrt((n - 2) / (1 - r^2))``
|
|
120
|
-
on ``n - 2`` degrees of freedom evaluated with the existing
|
|
121
|
-
:func:`cds.stats.hypothesis_tests.t_sf` survival function.
|
|
122
|
-
|
|
123
|
-
Args:
|
|
124
|
-
r: Sample Pearson correlation coefficient.
|
|
125
|
-
n: Number of paired observations (must be at least 3).
|
|
126
|
-
|
|
127
|
-
Returns:
|
|
128
|
-
Two-sided p-value in ``[0.0, 1.0]``; exactly ``0.0`` when the sample
|
|
129
|
-
correlation is perfect (``|r| = 1``), where the t statistic diverges.
|
|
130
|
-
"""
|
|
131
|
-
denominator = max(0.0, 1.0 - r * r)
|
|
132
|
-
if denominator == 0.0:
|
|
133
|
-
return 0.0
|
|
134
|
-
df = float(n - 2)
|
|
135
|
-
t_stat = abs(r) * math.sqrt((n - 2) / denominator)
|
|
136
|
-
return t_sf(t_stat, df)
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
def _build_hypothesis(
|
|
140
|
-
*,
|
|
141
|
-
feature_a: str,
|
|
142
|
-
feature_b: str,
|
|
143
|
-
r: float,
|
|
144
|
-
p_value: float,
|
|
145
|
-
n: int,
|
|
146
|
-
strength: str,
|
|
147
|
-
alpha: float,
|
|
148
|
-
min_abs_r: float,
|
|
149
|
-
) -> Hypothesis:
|
|
150
|
-
"""Assemble a fully populated :class:`~cds.core.models.Hypothesis`.
|
|
151
|
-
|
|
152
|
-
Every text field is derived from the observed statistics so the emitted
|
|
153
|
-
object is self-describing and falsifiable: the statement quotes ``r``,
|
|
154
|
-
``p`` and ``n``; assumptions state the preconditions of Pearson's
|
|
155
|
-
coefficient; predictions commit to sign, tier and threshold so future
|
|
156
|
-
data can refute them. Confidence follows a fixed per-tier mapping
|
|
157
|
-
(weak 0.4 / moderate 0.6 / strong 0.85).
|
|
158
|
-
|
|
159
|
-
Args:
|
|
160
|
-
feature_a: First column name.
|
|
161
|
-
feature_b: Second column name.
|
|
162
|
-
r: Observed Pearson correlation coefficient.
|
|
163
|
-
p_value: Two-sided p-value for the association.
|
|
164
|
-
n: Number of paired observations.
|
|
165
|
-
strength: Classified effect-size tier.
|
|
166
|
-
alpha: Significance level used during mining.
|
|
167
|
-
min_abs_r: Minimum absolute-correlation threshold used during mining.
|
|
168
|
-
|
|
169
|
-
Returns:
|
|
170
|
-
A :class:`~cds.core.models.Hypothesis` in ``TESTABLE`` status with
|
|
171
|
-
deterministic id, tags, sources and string-valued metadata.
|
|
172
|
-
"""
|
|
173
|
-
direction = "positive" if r > 0 else "negative"
|
|
174
|
-
statement = (
|
|
175
|
-
f"{feature_a} shows a {strength} {direction} linear association with "
|
|
176
|
-
f"{feature_b} (Pearson r={r:.4f}, p={p_value:.3e}, n={n})."
|
|
177
|
-
)
|
|
178
|
-
return Hypothesis(
|
|
179
|
-
id=f"CORR-{feature_a}-vs-{feature_b}",
|
|
180
|
-
statement=statement,
|
|
181
|
-
domain=Domain.GENERAL_SCIENCE,
|
|
182
|
-
research_question=f"Are {feature_a} and {feature_b} linearly associated?",
|
|
183
|
-
rationale=(
|
|
184
|
-
f"Pearson r={r:.4f} over n={n} paired observations "
|
|
185
|
-
f"(two-sided p={p_value:.3e}) clears the pre-registered thresholds "
|
|
186
|
-
f"|r| >= {min_abs_r} and p < {alpha}."
|
|
187
|
-
),
|
|
188
|
-
assumptions=[
|
|
189
|
-
"Paired observations are independent across rows.",
|
|
190
|
-
f"The relationship between {feature_a} and {feature_b} is approximately linear.",
|
|
191
|
-
"Neither variable is truncated to a range that would distort Pearson's r.",
|
|
192
|
-
],
|
|
193
|
-
predictions=[
|
|
194
|
-
f"A fresh comparable sample reproduces a {strength} {direction} "
|
|
195
|
-
f"correlation with |r| >= {min_abs_r}.",
|
|
196
|
-
f"Re-testing at alpha={alpha} again rejects independence between "
|
|
197
|
-
f"{feature_a} and {feature_b}.",
|
|
198
|
-
],
|
|
199
|
-
status=HypothesisStatus.TESTABLE,
|
|
200
|
-
confidence=_STRENGTH_CONFIDENCE[strength],
|
|
201
|
-
tags=["correlation", "mined", strength],
|
|
202
|
-
sources=["cds.hypothesis.mining.mine_correlations"],
|
|
203
|
-
metadata={
|
|
204
|
-
"feature_a": feature_a,
|
|
205
|
-
"feature_b": feature_b,
|
|
206
|
-
"pearson_r": f"{r:.6f}",
|
|
207
|
-
"p_value": f"{p_value:.6e}",
|
|
208
|
-
"sign": direction,
|
|
209
|
-
"n": str(n),
|
|
210
|
-
"degrees_of_freedom": str(n - 2),
|
|
211
|
-
},
|
|
212
|
-
)
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
def mine_correlations(
|
|
216
|
-
data: dict[str, list[float]],
|
|
217
|
-
*,
|
|
218
|
-
alpha: float = 0.05,
|
|
219
|
-
min_abs_r: float = 0.3,
|
|
220
|
-
max_features: int = 8,
|
|
221
|
-
) -> list[MinedHypothesis]:
|
|
222
|
-
"""Mine pairwise Pearson-correlation hypotheses from numeric columns.
|
|
223
|
-
|
|
224
|
-
Only the first ``max_features`` columns (in insertion order) are
|
|
225
|
-
considered. Constant columns among them are skipped silently. Each
|
|
226
|
-
surviving pair yields a candidate only if ``abs(r) >= min_abs_r`` and
|
|
227
|
-
the two-sided significance test gives ``p < alpha``; results are sorted
|
|
228
|
-
by ``|r|`` descending (ties keep deterministic feature-name order).
|
|
229
|
-
|
|
230
|
-
Strength tiers follow the documented 0.2 / 0.5 thresholds on ``|r|``
|
|
231
|
-
with boundaries assigned to the higher tier (see module docstring).
|
|
232
|
-
|
|
233
|
-
Args:
|
|
234
|
-
data: Mapping of column names to equal-length numeric columns.
|
|
235
|
-
alpha: Significance level in the open interval ``(0.0, 1.0)``.
|
|
236
|
-
min_abs_r: Inclusive lower bound on ``abs(r)``, within ``[0.0, 1.0)``.
|
|
237
|
-
max_features: Maximum number of leading columns to consider.
|
|
238
|
-
|
|
239
|
-
Returns:
|
|
240
|
-
One :class:`MinedHypothesis` per qualifying pair, strongest first.
|
|
241
|
-
|
|
242
|
-
Raises:
|
|
243
|
-
ValueError: If fewer than two columns are provided after filtering
|
|
244
|
-
out constant columns, any column holds fewer than 3 observations,
|
|
245
|
-
column lengths are mismatched, ``alpha`` falls outside
|
|
246
|
-
``(0.0, 1.0)``, or ``min_abs_r`` falls outside ``[0.0, 1.0)``.
|
|
247
|
-
"""
|
|
248
|
-
if not data:
|
|
249
|
-
raise ValueError("correlation mining needs at least 2 numeric columns, got none")
|
|
250
|
-
if not 0.0 < alpha < 1.0:
|
|
251
|
-
raise ValueError(f"alpha must be strictly between 0.0 and 1.0, got {alpha}")
|
|
252
|
-
if not 0.0 <= min_abs_r < 1.0:
|
|
253
|
-
raise ValueError(
|
|
254
|
-
f"min_abs_r must lie between 0.0 inclusive and 1.0 exclusive, got {min_abs_r}"
|
|
255
|
-
)
|
|
256
|
-
|
|
257
|
-
expected_length: int | None = None
|
|
258
|
-
for name, values in data.items():
|
|
259
|
-
if len(values) < 3:
|
|
260
|
-
message = f"column '{name}' needs at least 3 observations, got {len(values)}"
|
|
261
|
-
raise ValueError(message)
|
|
262
|
-
if expected_length is None:
|
|
263
|
-
expected_length = len(values)
|
|
264
|
-
elif len(values) != expected_length:
|
|
265
|
-
raise ValueError(
|
|
266
|
-
f"columns must share one length: '{name}' has "
|
|
267
|
-
f"{len(values)}, expected {expected_length}"
|
|
268
|
-
)
|
|
269
|
-
|
|
270
|
-
columns = list(data.items())[:max_features]
|
|
271
|
-
usable: list[tuple[str, list[float]]] = []
|
|
272
|
-
for name, values in columns:
|
|
273
|
-
if not _is_constant(values):
|
|
274
|
-
usable.append((name, values))
|
|
275
|
-
if len(usable) < 2:
|
|
276
|
-
raise ValueError(
|
|
277
|
-
f"correlation mining needs at least 2 non-constant columns, got {len(usable)}"
|
|
278
|
-
)
|
|
279
|
-
|
|
280
|
-
sample_size = len(next(iter(data.values())))
|
|
281
|
-
mined: list[MinedHypothesis] = []
|
|
282
|
-
for i in range(len(usable)):
|
|
283
|
-
name_a, values_a = usable[i]
|
|
284
|
-
for j in range(i + 1, len(usable)):
|
|
285
|
-
name_b, values_b = usable[j]
|
|
286
|
-
r = correlation(values_a, values_b)
|
|
287
|
-
if abs(r) < min_abs_r:
|
|
288
|
-
continue
|
|
289
|
-
p_value = _pearson_p_value(r, sample_size)
|
|
290
|
-
if p_value >= alpha:
|
|
291
|
-
continue
|
|
292
|
-
strength = _classify_strength(abs(r))
|
|
293
|
-
mined.append(
|
|
294
|
-
MinedHypothesis(
|
|
295
|
-
feature_a=name_a,
|
|
296
|
-
feature_b=name_b,
|
|
297
|
-
correlation=r,
|
|
298
|
-
p_value=p_value,
|
|
299
|
-
strength=strength,
|
|
300
|
-
hypothesis=_build_hypothesis(
|
|
301
|
-
feature_a=name_a,
|
|
302
|
-
feature_b=name_b,
|
|
303
|
-
r=r,
|
|
304
|
-
p_value=p_value,
|
|
305
|
-
n=sample_size,
|
|
306
|
-
strength=strength,
|
|
307
|
-
alpha=alpha,
|
|
308
|
-
min_abs_r=min_abs_r,
|
|
309
|
-
),
|
|
310
|
-
)
|
|
311
|
-
)
|
|
312
|
-
|
|
313
|
-
mined.sort(key=lambda hit: (-abs(hit.correlation), hit.feature_a, hit.feature_b))
|
|
314
|
-
return mined
|
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
"""Information-theory measures — entropy, divergence and dependence.
|
|
2
|
-
|
|
3
|
-
Re-exports the pure-Python Shannon measures from :mod:`cds.infotheory.measures`.
|
|
4
|
-
|
|
5
|
-
References:
|
|
6
|
-
Shannon, C. E. (1948). A Mathematical Theory of Communication.
|
|
7
|
-
"""
|
|
8
|
-
|
|
9
|
-
from __future__ import annotations
|
|
10
|
-
|
|
11
|
-
from cds.infotheory.measures import (
|
|
12
|
-
cross_entropy,
|
|
13
|
-
entropy,
|
|
14
|
-
js_divergence,
|
|
15
|
-
kl_divergence,
|
|
16
|
-
mutual_information,
|
|
17
|
-
)
|
|
18
|
-
|
|
19
|
-
__all__ = [
|
|
20
|
-
"cross_entropy",
|
|
21
|
-
"entropy",
|
|
22
|
-
"js_divergence",
|
|
23
|
-
"kl_divergence",
|
|
24
|
-
"mutual_information",
|
|
25
|
-
]
|
|
@@ -1,276 +0,0 @@
|
|
|
1
|
-
"""Information-theory measures — entropy, divergence and mutual information.
|
|
2
|
-
|
|
3
|
-
Pure-Python, zero-dependency implementation of Shannon information measures
|
|
4
|
-
using only :mod:`math`. All logarithms are computed via :func:`math.log`
|
|
5
|
-
with an explicit change-of-base, so no ``numpy`` is required.
|
|
6
|
-
|
|
7
|
-
References:
|
|
8
|
-
Shannon, C. E. (1948). A Mathematical Theory of Communication.
|
|
9
|
-
Bell System Technical Journal, 27, 379–423, 623–656.
|
|
10
|
-
"""
|
|
11
|
-
|
|
12
|
-
from __future__ import annotations
|
|
13
|
-
|
|
14
|
-
import math
|
|
15
|
-
|
|
16
|
-
__all__ = [
|
|
17
|
-
"cross_entropy",
|
|
18
|
-
"entropy",
|
|
19
|
-
"js_divergence",
|
|
20
|
-
"kl_divergence",
|
|
21
|
-
"mutual_information",
|
|
22
|
-
]
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
def _validate_base(base: float) -> None:
|
|
26
|
-
"""Validate that ``base`` is positive and not equal to 1.
|
|
27
|
-
|
|
28
|
-
Raises:
|
|
29
|
-
ValueError: if ``base <= 0`` or ``base == 1`` (within floating tolerance).
|
|
30
|
-
"""
|
|
31
|
-
if base <= 0 or math.isclose(base, 1.0):
|
|
32
|
-
raise ValueError("base must be positive and not equal to 1")
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
def _validate_distribution(probabilities: list[float]) -> None:
|
|
36
|
-
"""Validate a discrete probability distribution.
|
|
37
|
-
|
|
38
|
-
Checks that ``probabilities`` is non-empty, all entries are non-negative,
|
|
39
|
-
and the entries sum to 1 within ``abs_tol=1e-9``.
|
|
40
|
-
|
|
41
|
-
Raises:
|
|
42
|
-
ValueError: if any check fails. Messages contain ``empty``,
|
|
43
|
-
``non-negative`` or ``sum to 1`` so callers can match on substrings.
|
|
44
|
-
"""
|
|
45
|
-
if not probabilities:
|
|
46
|
-
raise ValueError("probabilities must be non-empty")
|
|
47
|
-
for p in probabilities:
|
|
48
|
-
if p < 0:
|
|
49
|
-
raise ValueError("probabilities must be non-negative and sum to 1")
|
|
50
|
-
if not math.isfinite(p):
|
|
51
|
-
raise ValueError("probabilities must be non-negative and sum to 1")
|
|
52
|
-
if not math.isclose(sum(probabilities), 1.0, abs_tol=1e-9):
|
|
53
|
-
raise ValueError("probabilities must be non-negative and sum to 1")
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
def _validate_joint(joint: list[list[float]]) -> None:
|
|
57
|
-
"""Validate a joint probability table.
|
|
58
|
-
|
|
59
|
-
Checks that ``joint`` is a non-empty rectangular 2-D table with
|
|
60
|
-
non-negative finite entries summing to 1 within ``abs_tol=1e-9``.
|
|
61
|
-
|
|
62
|
-
Raises:
|
|
63
|
-
ValueError: if any check fails. Messages contain ``2-D``,
|
|
64
|
-
``non-empty``, ``non-negative`` or ``sum to 1``.
|
|
65
|
-
"""
|
|
66
|
-
if not joint or not joint[0]:
|
|
67
|
-
raise ValueError("joint distribution must be a non-empty 2-D table")
|
|
68
|
-
n_cols = len(joint[0])
|
|
69
|
-
for row in joint:
|
|
70
|
-
if len(row) != n_cols:
|
|
71
|
-
raise ValueError("joint distribution must be a non-empty 2-D table")
|
|
72
|
-
flat: list[float] = []
|
|
73
|
-
for row in joint:
|
|
74
|
-
for v in row:
|
|
75
|
-
if v < 0 or not math.isfinite(v):
|
|
76
|
-
raise ValueError("joint probabilities must be non-negative and sum to 1")
|
|
77
|
-
flat.append(v)
|
|
78
|
-
if not math.isclose(sum(flat), 1.0, abs_tol=1e-9):
|
|
79
|
-
raise ValueError("joint probabilities must sum to 1")
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
def entropy(probabilities: list[float], base: float = 2.0) -> float:
|
|
83
|
-
"""Shannon entropy ``H(P) = -sum p log_b p`` (Shannon 1948).
|
|
84
|
-
|
|
85
|
-
Uses the convention ``0 log 0 := 0`` so zero-probability events contribute
|
|
86
|
-
nothing. Units are determined by ``base`` (``2`` → bits, ``e`` → nats).
|
|
87
|
-
|
|
88
|
-
Args:
|
|
89
|
-
probabilities: discrete distribution (non-negative, sums to 1 within 1e-9).
|
|
90
|
-
base: logarithm base, must be positive and not equal to 1.
|
|
91
|
-
|
|
92
|
-
Returns:
|
|
93
|
-
Entropy ``H(P)`` in units of ``base``.
|
|
94
|
-
|
|
95
|
-
Raises:
|
|
96
|
-
ValueError: if ``probabilities`` is empty, contains a negative value,
|
|
97
|
-
does not sum to 1, or ``base`` is invalid.
|
|
98
|
-
|
|
99
|
-
References:
|
|
100
|
-
Shannon, C. E. (1948). A Mathematical Theory of Communication.
|
|
101
|
-
"""
|
|
102
|
-
_validate_base(base)
|
|
103
|
-
_validate_distribution(probabilities)
|
|
104
|
-
log_base = math.log(base)
|
|
105
|
-
total = 0.0
|
|
106
|
-
for p in probabilities:
|
|
107
|
-
if p > 0:
|
|
108
|
-
total -= p * math.log(p) / log_base
|
|
109
|
-
return total
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
def kl_divergence(p: list[float], q: list[float], base: float = 2.0) -> float:
|
|
113
|
-
"""Kullback-Leibler divergence ``D_KL(P || Q)`` (Shannon 1948).
|
|
114
|
-
|
|
115
|
-
``D_KL(P || Q) = sum p log_b(p/q)`` with ``0 log 0 := 0``. The divergence
|
|
116
|
-
is non-negative and zero iff ``P == Q``.
|
|
117
|
-
|
|
118
|
-
Args:
|
|
119
|
-
p: first distribution (non-negative, sums to 1).
|
|
120
|
-
q: second distribution (non-negative, sums to 1, same length as ``p``).
|
|
121
|
-
base: logarithm base, must be positive and not equal to 1.
|
|
122
|
-
|
|
123
|
-
Returns:
|
|
124
|
-
KL divergence in units of ``base``. Returns ``float('inf')`` when
|
|
125
|
-
``q`` assigns zero mass where ``p`` is positive.
|
|
126
|
-
|
|
127
|
-
Raises:
|
|
128
|
-
ValueError: if either distribution is empty, contains a negative value,
|
|
129
|
-
does not sum to 1, lengths differ, or ``base`` is invalid.
|
|
130
|
-
|
|
131
|
-
References:
|
|
132
|
-
Shannon, C. E. (1948). A Mathematical Theory of Communication.
|
|
133
|
-
"""
|
|
134
|
-
_validate_base(base)
|
|
135
|
-
_validate_distribution(p)
|
|
136
|
-
_validate_distribution(q)
|
|
137
|
-
if len(p) != len(q):
|
|
138
|
-
raise ValueError("p and q must have the same length")
|
|
139
|
-
log_base = math.log(base)
|
|
140
|
-
total = 0.0
|
|
141
|
-
for pi, qi in zip(p, q):
|
|
142
|
-
if pi == 0:
|
|
143
|
-
continue
|
|
144
|
-
if qi == 0:
|
|
145
|
-
return float("inf")
|
|
146
|
-
total += pi * (math.log(pi) - math.log(qi)) / log_base
|
|
147
|
-
return total
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
def cross_entropy(p: list[float], q: list[float], base: float = 2.0) -> float:
|
|
151
|
-
"""Cross-entropy ``H(P, Q) = -sum p log_b q`` (Shannon 1948).
|
|
152
|
-
|
|
153
|
-
Satisfies ``H(P, Q) = H(P) + D_KL(P || Q)``. Uses ``0 log q := 0`` when
|
|
154
|
-
``p == 0`` regardless of ``q``.
|
|
155
|
-
|
|
156
|
-
Args:
|
|
157
|
-
p: true distribution (non-negative, sums to 1).
|
|
158
|
-
q: predicted distribution (non-negative, sums to 1, same length as ``p``).
|
|
159
|
-
base: logarithm base, must be positive and not equal to 1.
|
|
160
|
-
|
|
161
|
-
Returns:
|
|
162
|
-
Cross-entropy in units of ``base``. Returns ``float('inf')`` when
|
|
163
|
-
``q`` assigns zero mass where ``p`` is positive.
|
|
164
|
-
|
|
165
|
-
Raises:
|
|
166
|
-
ValueError: if either distribution is empty, contains a negative value,
|
|
167
|
-
does not sum to 1, lengths differ, or ``base`` is invalid.
|
|
168
|
-
|
|
169
|
-
References:
|
|
170
|
-
Shannon, C. E. (1948). A Mathematical Theory of Communication.
|
|
171
|
-
"""
|
|
172
|
-
_validate_base(base)
|
|
173
|
-
_validate_distribution(p)
|
|
174
|
-
_validate_distribution(q)
|
|
175
|
-
if len(p) != len(q):
|
|
176
|
-
raise ValueError("p and q must have the same length")
|
|
177
|
-
log_base = math.log(base)
|
|
178
|
-
total = 0.0
|
|
179
|
-
for pi, qi in zip(p, q):
|
|
180
|
-
if pi == 0:
|
|
181
|
-
continue
|
|
182
|
-
if qi == 0:
|
|
183
|
-
return float("inf")
|
|
184
|
-
total -= pi * math.log(qi) / log_base
|
|
185
|
-
return total
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
def js_divergence(p: list[float], q: list[float], base: float = 2.0) -> float:
|
|
189
|
-
"""Jensen-Shannon divergence (symmetric, bounded) (Shannon 1948).
|
|
190
|
-
|
|
191
|
-
``JSD(P || Q) = 0.5 D_KL(P || M) + 0.5 D_KL(Q || M)`` where ``M = (P+Q)/2``.
|
|
192
|
-
Unlike KL, it is symmetric and bounded in ``[0, log_b 2]`` (``[0, 1]`` for
|
|
193
|
-
``base=2``).
|
|
194
|
-
|
|
195
|
-
Args:
|
|
196
|
-
p: first distribution (non-negative, sums to 1).
|
|
197
|
-
q: second distribution (non-negative, sums to 1, same length as ``p``).
|
|
198
|
-
base: logarithm base, must be positive and not equal to 1.
|
|
199
|
-
|
|
200
|
-
Returns:
|
|
201
|
-
Jensen-Shannon divergence in units of ``base``.
|
|
202
|
-
|
|
203
|
-
Raises:
|
|
204
|
-
ValueError: if either distribution is empty, contains a negative value,
|
|
205
|
-
does not sum to 1, lengths differ, or ``base`` is invalid.
|
|
206
|
-
|
|
207
|
-
References:
|
|
208
|
-
Shannon, C. E. (1948). A Mathematical Theory of Communication.
|
|
209
|
-
"""
|
|
210
|
-
_validate_base(base)
|
|
211
|
-
_validate_distribution(p)
|
|
212
|
-
_validate_distribution(q)
|
|
213
|
-
if len(p) != len(q):
|
|
214
|
-
raise ValueError("p and q must have the same length")
|
|
215
|
-
mixture: list[float] = [(pi + qi) * 0.5 for pi, qi in zip(p, q)]
|
|
216
|
-
# Mixture is guaranteed valid (non-negative, sums to 1) so KL will not hit
|
|
217
|
-
# the infinite case; inline the raw sum to avoid double-validation.
|
|
218
|
-
log_base = math.log(base)
|
|
219
|
-
kl_pm = 0.0
|
|
220
|
-
kl_qm = 0.0
|
|
221
|
-
for pi, mi in zip(p, mixture):
|
|
222
|
-
if pi == 0:
|
|
223
|
-
continue
|
|
224
|
-
# mi > 0 whenever pi > 0 because mi = (pi+qi)/2 >= pi/2
|
|
225
|
-
kl_pm += pi * (math.log(pi) - math.log(mi)) / log_base
|
|
226
|
-
for qi, mi in zip(q, mixture):
|
|
227
|
-
if qi == 0:
|
|
228
|
-
continue
|
|
229
|
-
kl_qm += qi * (math.log(qi) - math.log(mi)) / log_base
|
|
230
|
-
return 0.5 * kl_pm + 0.5 * kl_qm
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
def mutual_information(joint: list[list[float]], base: float = 2.0) -> float:
|
|
234
|
-
"""Mutual information ``I(X; Y)`` from a joint table (Shannon 1948).
|
|
235
|
-
|
|
236
|
-
``I(X; Y) = sum_{x,y} p(x,y) log_b(p(x,y) / (p(x) p(y)))`` with
|
|
237
|
-
``0 log 0 := 0``. Zero for independent variables, equal to the entropy
|
|
238
|
-
when the variables are perfectly correlated.
|
|
239
|
-
|
|
240
|
-
Args:
|
|
241
|
-
joint: 2-D joint distribution ``p(x, y)`` where rows index ``X`` and
|
|
242
|
-
columns index ``Y``. Must be rectangular, non-negative and sum to 1
|
|
243
|
-
within 1e-9.
|
|
244
|
-
base: logarithm base, must be positive and not equal to 1.
|
|
245
|
-
|
|
246
|
-
Returns:
|
|
247
|
-
Mutual information in units of ``base``.
|
|
248
|
-
|
|
249
|
-
Raises:
|
|
250
|
-
ValueError: if ``joint`` is empty, ragged, contains a negative value,
|
|
251
|
-
does not sum to 1, or ``base`` is invalid.
|
|
252
|
-
|
|
253
|
-
References:
|
|
254
|
-
Shannon, C. E. (1948). A Mathematical Theory of Communication.
|
|
255
|
-
"""
|
|
256
|
-
_validate_base(base)
|
|
257
|
-
_validate_joint(joint)
|
|
258
|
-
n_rows = len(joint)
|
|
259
|
-
n_cols = len(joint[0])
|
|
260
|
-
row_sums: list[float] = [sum(row) for row in joint]
|
|
261
|
-
col_sums: list[float] = [0.0] * n_cols
|
|
262
|
-
for row in joint:
|
|
263
|
-
for j, v in enumerate(row):
|
|
264
|
-
col_sums[j] += v
|
|
265
|
-
log_base = math.log(base)
|
|
266
|
-
mi = 0.0
|
|
267
|
-
for i in range(n_rows):
|
|
268
|
-
for j in range(n_cols):
|
|
269
|
-
p_xy = joint[i][j]
|
|
270
|
-
if p_xy == 0:
|
|
271
|
-
continue
|
|
272
|
-
p_x = row_sums[i]
|
|
273
|
-
p_y = col_sums[j]
|
|
274
|
-
# p_x and p_y are >0 whenever p_xy>0 (marginals dominate the cell)
|
|
275
|
-
mi += p_xy * math.log(p_xy / (p_x * p_y)) / log_base
|
|
276
|
-
return mi
|