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,477 +0,0 @@
|
|
|
1
|
-
"""Advanced parameter fitting with diagnostics, bounds, robust losses, and multi-start."""
|
|
2
|
-
|
|
3
|
-
from __future__ import annotations
|
|
4
|
-
|
|
5
|
-
import math
|
|
6
|
-
import random
|
|
7
|
-
from collections.abc import Sequence
|
|
8
|
-
from dataclasses import dataclass
|
|
9
|
-
from statistics import NormalDist
|
|
10
|
-
from typing import Literal
|
|
11
|
-
|
|
12
|
-
from cds.core._numeric import DEFAULT_TOLERANCE, GD_DEFAULT_LR
|
|
13
|
-
from cds.modeling.model import MathModel
|
|
14
|
-
from cds.optimization import adam, gradient_descent, nelder_mead, projected_gradient_descent
|
|
15
|
-
|
|
16
|
-
FitLoss = Literal["squared", "absolute", "huber"]
|
|
17
|
-
FitOptimizer = Literal["auto", "gradient_descent", "adam", "nelder_mead", "projected_gradient"]
|
|
18
|
-
FitUncertainty = Literal["auto", "none", "normal", "bootstrap", "both"]
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
@dataclass(frozen=True)
|
|
22
|
-
class FitDiagnostics:
|
|
23
|
-
"""Diagnostics attached to an advanced parameter fit."""
|
|
24
|
-
|
|
25
|
-
residuals: tuple[float, ...]
|
|
26
|
-
rmse: float
|
|
27
|
-
mae: float
|
|
28
|
-
r_squared: float
|
|
29
|
-
standard_errors: dict[str, float] | None
|
|
30
|
-
confidence_intervals: dict[str, tuple[float, float]] | None
|
|
31
|
-
identifiable: bool
|
|
32
|
-
uncertainty_method: str = "none"
|
|
33
|
-
bootstrap_confidence_intervals: dict[str, tuple[float, float]] | None = None
|
|
34
|
-
bootstrap_successes: int = 0
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
@dataclass(frozen=True)
|
|
38
|
-
class AdvancedFitResult:
|
|
39
|
-
"""Rich result from :func:`fit_parameters_advanced`."""
|
|
40
|
-
|
|
41
|
-
parameters: dict[str, float]
|
|
42
|
-
objective: float
|
|
43
|
-
iterations: int
|
|
44
|
-
converged: bool
|
|
45
|
-
optimizer: str
|
|
46
|
-
optimizer_rationale: str
|
|
47
|
-
starts_tried: int
|
|
48
|
-
diagnostics: FitDiagnostics
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
def _loss_value(residual: float, loss: FitLoss, huber_delta: float) -> float:
|
|
52
|
-
if loss == "squared":
|
|
53
|
-
return residual * residual
|
|
54
|
-
if loss == "absolute":
|
|
55
|
-
return abs(residual)
|
|
56
|
-
magnitude = abs(residual)
|
|
57
|
-
if magnitude <= huber_delta:
|
|
58
|
-
return 0.5 * residual * residual
|
|
59
|
-
return huber_delta * (magnitude - 0.5 * huber_delta)
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
def _select_optimizer(
|
|
63
|
-
optimizer: FitOptimizer,
|
|
64
|
-
loss: FitLoss,
|
|
65
|
-
bounds: Sequence[tuple[float, float]] | None,
|
|
66
|
-
) -> tuple[str, str]:
|
|
67
|
-
if optimizer != "auto":
|
|
68
|
-
return optimizer, "explicitly selected by caller"
|
|
69
|
-
if bounds is not None:
|
|
70
|
-
return "projected_gradient", "box bounds require projected updates"
|
|
71
|
-
if loss == "absolute":
|
|
72
|
-
return "nelder_mead", "absolute loss is non-smooth, so derivative-free fitting is safer"
|
|
73
|
-
return "adam", "smooth unconstrained objective; Adam is a robust default for parameter scaling"
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
def _make_starts(
|
|
77
|
-
x0: list[float],
|
|
78
|
-
count: int,
|
|
79
|
-
bounds: Sequence[tuple[float, float]] | None,
|
|
80
|
-
seed: int,
|
|
81
|
-
) -> list[list[float]]:
|
|
82
|
-
starts = [list(x0)]
|
|
83
|
-
rng = random.Random(seed)
|
|
84
|
-
for _ in range(1, count):
|
|
85
|
-
if bounds is not None:
|
|
86
|
-
starts.append([rng.uniform(lower, upper) for lower, upper in bounds])
|
|
87
|
-
else:
|
|
88
|
-
starts.append([value + rng.gauss(0.0, 0.25 * max(1.0, abs(value))) for value in x0])
|
|
89
|
-
return starts
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
def _invert_matrix(matrix: Sequence[Sequence[float]]) -> list[list[float]]:
|
|
93
|
-
"""Invert a small dense matrix with Gauss-Jordan elimination."""
|
|
94
|
-
n = len(matrix)
|
|
95
|
-
if n == 0:
|
|
96
|
-
raise ValueError("matrix must be non-empty")
|
|
97
|
-
if any(len(row) != n for row in matrix):
|
|
98
|
-
raise ValueError("matrix must be square")
|
|
99
|
-
|
|
100
|
-
augmented = [
|
|
101
|
-
[float(value) for value in row] + [1.0 if row_index == col else 0.0 for col in range(n)]
|
|
102
|
-
for row_index, row in enumerate(matrix)
|
|
103
|
-
]
|
|
104
|
-
for col in range(n):
|
|
105
|
-
pivot = max(range(col, n), key=lambda row_index: abs(augmented[row_index][col]))
|
|
106
|
-
if abs(augmented[pivot][col]) <= 1e-15:
|
|
107
|
-
raise ValueError("matrix is singular")
|
|
108
|
-
augmented[col], augmented[pivot] = augmented[pivot], augmented[col]
|
|
109
|
-
pivot_value = augmented[col][col]
|
|
110
|
-
augmented[col] = [value / pivot_value for value in augmented[col]]
|
|
111
|
-
for row_index in range(n):
|
|
112
|
-
if row_index != col:
|
|
113
|
-
factor = augmented[row_index][col]
|
|
114
|
-
augmented[row_index] = [
|
|
115
|
-
value - factor * pivot_component
|
|
116
|
-
for value, pivot_component in zip(augmented[row_index], augmented[col])
|
|
117
|
-
]
|
|
118
|
-
return [row[n:] for row in augmented]
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
def _prediction_residuals(
|
|
122
|
-
model: MathModel,
|
|
123
|
-
observations: Sequence[tuple[dict[str, float], float]],
|
|
124
|
-
names: Sequence[str],
|
|
125
|
-
values: Sequence[float],
|
|
126
|
-
target_label: str,
|
|
127
|
-
) -> list[float]:
|
|
128
|
-
target = model.equation(target_label)
|
|
129
|
-
params = {**model.parameters, **dict(zip(names, values))}
|
|
130
|
-
return [
|
|
131
|
-
target.evaluate({**env, **params}) - observed_value for env, observed_value in observations
|
|
132
|
-
]
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
def _uncertainty(
|
|
136
|
-
model: MathModel,
|
|
137
|
-
observations: Sequence[tuple[dict[str, float], float]],
|
|
138
|
-
names: Sequence[str],
|
|
139
|
-
values: Sequence[float],
|
|
140
|
-
target_label: str,
|
|
141
|
-
residuals: Sequence[float],
|
|
142
|
-
confidence: float,
|
|
143
|
-
) -> tuple[dict[str, float] | None, dict[str, tuple[float, float]] | None, bool]:
|
|
144
|
-
"""Local linearized covariance/normal-approximation uncertainty."""
|
|
145
|
-
n = len(observations)
|
|
146
|
-
p = len(names)
|
|
147
|
-
if n <= p:
|
|
148
|
-
return None, None, False
|
|
149
|
-
|
|
150
|
-
params = {**model.parameters, **dict(zip(names, values))}
|
|
151
|
-
derivatives = [model.gradient(target_label, name) for name in names]
|
|
152
|
-
jacobian = [
|
|
153
|
-
[derivative.evaluate({**env, **params}) for derivative in derivatives]
|
|
154
|
-
for env, _ in observations
|
|
155
|
-
]
|
|
156
|
-
jtj = [[sum(row[i] * row[j] for row in jacobian) for j in range(p)] for i in range(p)]
|
|
157
|
-
try:
|
|
158
|
-
inverse = _invert_matrix(jtj)
|
|
159
|
-
except ValueError:
|
|
160
|
-
return None, None, False
|
|
161
|
-
|
|
162
|
-
rss = sum(residual * residual for residual in residuals)
|
|
163
|
-
sigma2 = rss / (n - p)
|
|
164
|
-
variances = [max(0.0, sigma2 * inverse[i][i]) for i in range(p)]
|
|
165
|
-
standard_errors = {name: math.sqrt(variance) for name, variance in zip(names, variances)}
|
|
166
|
-
z = NormalDist().inv_cdf(0.5 + confidence / 2.0)
|
|
167
|
-
intervals = {
|
|
168
|
-
name: (value - z * standard_errors[name], value + z * standard_errors[name])
|
|
169
|
-
for name, value in zip(names, values)
|
|
170
|
-
}
|
|
171
|
-
return standard_errors, intervals, True
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
def _percentile(values: Sequence[float], probability: float) -> float:
|
|
175
|
-
if not values:
|
|
176
|
-
raise ValueError("percentile requires at least one value")
|
|
177
|
-
if not 0.0 <= probability <= 1.0:
|
|
178
|
-
raise ValueError("probability must lie in [0, 1]")
|
|
179
|
-
ordered = sorted(values)
|
|
180
|
-
position = probability * (len(ordered) - 1)
|
|
181
|
-
lower = int(math.floor(position))
|
|
182
|
-
upper = int(math.ceil(position))
|
|
183
|
-
if lower == upper:
|
|
184
|
-
return ordered[lower]
|
|
185
|
-
weight = position - lower
|
|
186
|
-
return ordered[lower] * (1.0 - weight) + ordered[upper] * weight
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
def _bootstrap_uncertainty(
|
|
190
|
-
model: MathModel,
|
|
191
|
-
observations: Sequence[tuple[dict[str, float], float]],
|
|
192
|
-
names: Sequence[str],
|
|
193
|
-
values: Sequence[float],
|
|
194
|
-
*,
|
|
195
|
-
target_label: str,
|
|
196
|
-
optimizer: FitOptimizer,
|
|
197
|
-
loss: FitLoss,
|
|
198
|
-
bounds: Sequence[tuple[float, float]] | None,
|
|
199
|
-
huber_delta: float,
|
|
200
|
-
confidence: float,
|
|
201
|
-
bootstrap_samples: int,
|
|
202
|
-
bootstrap_seed: int,
|
|
203
|
-
min_success_fraction: float,
|
|
204
|
-
lr: float,
|
|
205
|
-
tol: float,
|
|
206
|
-
max_iter: int,
|
|
207
|
-
) -> tuple[
|
|
208
|
-
dict[str, float] | None,
|
|
209
|
-
dict[str, tuple[float, float]] | None,
|
|
210
|
-
int,
|
|
211
|
-
]:
|
|
212
|
-
"""Nonparametric case-resampling uncertainty for nonlinear/robust fits."""
|
|
213
|
-
rng = random.Random(bootstrap_seed)
|
|
214
|
-
samples_by_name: dict[str, list[float]] = {name: [] for name in names}
|
|
215
|
-
successes = 0
|
|
216
|
-
n = len(observations)
|
|
217
|
-
for _ in range(bootstrap_samples):
|
|
218
|
-
resampled = [observations[rng.randrange(n)] for _ in range(n)]
|
|
219
|
-
try:
|
|
220
|
-
result = fit_parameters_advanced(
|
|
221
|
-
model,
|
|
222
|
-
resampled,
|
|
223
|
-
names,
|
|
224
|
-
x0=values,
|
|
225
|
-
target_label=target_label,
|
|
226
|
-
optimizer=optimizer,
|
|
227
|
-
loss=loss,
|
|
228
|
-
bounds=bounds,
|
|
229
|
-
multi_start=1,
|
|
230
|
-
seed=rng.randrange(2**31),
|
|
231
|
-
huber_delta=huber_delta,
|
|
232
|
-
confidence=confidence,
|
|
233
|
-
uncertainty="none",
|
|
234
|
-
lr=lr,
|
|
235
|
-
tol=tol,
|
|
236
|
-
max_iter=max_iter,
|
|
237
|
-
)
|
|
238
|
-
except (ArithmeticError, ValueError, ZeroDivisionError):
|
|
239
|
-
continue
|
|
240
|
-
candidate = [result.parameters[name] for name in names]
|
|
241
|
-
if any(not math.isfinite(value) for value in candidate):
|
|
242
|
-
continue
|
|
243
|
-
successes += 1
|
|
244
|
-
for name, value in zip(names, candidate):
|
|
245
|
-
samples_by_name[name].append(value)
|
|
246
|
-
|
|
247
|
-
required = max(2, math.ceil(bootstrap_samples * min_success_fraction))
|
|
248
|
-
if successes < required:
|
|
249
|
-
return None, None, successes
|
|
250
|
-
|
|
251
|
-
alpha = (1.0 - confidence) / 2.0
|
|
252
|
-
intervals = {
|
|
253
|
-
name: (_percentile(samples, alpha), _percentile(samples, 1.0 - alpha))
|
|
254
|
-
for name, samples in samples_by_name.items()
|
|
255
|
-
}
|
|
256
|
-
standard_errors = {}
|
|
257
|
-
for name, samples in samples_by_name.items():
|
|
258
|
-
mean = sum(samples) / len(samples)
|
|
259
|
-
variance = sum((sample - mean) ** 2 for sample in samples) / (len(samples) - 1)
|
|
260
|
-
standard_errors[name] = math.sqrt(max(0.0, variance))
|
|
261
|
-
return standard_errors, intervals, successes
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
def fit_parameters_advanced(
|
|
265
|
-
model: MathModel,
|
|
266
|
-
observed: Sequence[tuple[dict[str, float], float]],
|
|
267
|
-
parameter_names: Sequence[str],
|
|
268
|
-
x0: Sequence[float] | None = None,
|
|
269
|
-
*,
|
|
270
|
-
target_label: str | None = None,
|
|
271
|
-
optimizer: FitOptimizer = "auto",
|
|
272
|
-
loss: FitLoss = "squared",
|
|
273
|
-
bounds: Sequence[tuple[float, float]] | None = None,
|
|
274
|
-
multi_start: int = 1,
|
|
275
|
-
seed: int = 0,
|
|
276
|
-
huber_delta: float = 1.0,
|
|
277
|
-
confidence: float = 0.95,
|
|
278
|
-
uncertainty: FitUncertainty = "auto",
|
|
279
|
-
bootstrap_samples: int = 200,
|
|
280
|
-
bootstrap_seed: int | None = None,
|
|
281
|
-
min_bootstrap_success_fraction: float = 0.8,
|
|
282
|
-
lr: float = GD_DEFAULT_LR,
|
|
283
|
-
tol: float = DEFAULT_TOLERANCE,
|
|
284
|
-
max_iter: int = 10000,
|
|
285
|
-
) -> AdvancedFitResult:
|
|
286
|
-
"""Fit model parameters with method selection, diagnostics, and optional bootstrap CIs.
|
|
287
|
-
|
|
288
|
-
``uncertainty='normal'`` preserves the fast local Jacobian approximation for
|
|
289
|
-
squared loss. ``'bootstrap'`` provides nonparametric case-resampling CIs
|
|
290
|
-
that remain meaningful for nonlinear and robust-loss fits, while ``'both'``
|
|
291
|
-
exposes both estimates for cross-checking. ``'auto'`` keeps the historical
|
|
292
|
-
fast behavior (normal for squared loss, none for robust losses).
|
|
293
|
-
"""
|
|
294
|
-
names = list(parameter_names)
|
|
295
|
-
observations = list(observed)
|
|
296
|
-
if not names:
|
|
297
|
-
raise ValueError("parameter_names must list at least one parameter to fit")
|
|
298
|
-
if len(set(names)) != len(names):
|
|
299
|
-
raise ValueError("parameter_names must contain unique names")
|
|
300
|
-
if not model.equations:
|
|
301
|
-
raise ValueError("model must contain at least one equation to fit")
|
|
302
|
-
if not observations:
|
|
303
|
-
raise ValueError("observed must contain at least one (env, value) pair")
|
|
304
|
-
start = list(x0) if x0 is not None else [0.0] * len(names)
|
|
305
|
-
if len(start) != len(names):
|
|
306
|
-
raise ValueError("x0 length must exactly match parameter_names")
|
|
307
|
-
if multi_start < 1:
|
|
308
|
-
raise ValueError("multi_start must be >= 1")
|
|
309
|
-
if huber_delta <= 0:
|
|
310
|
-
raise ValueError("huber_delta must be positive")
|
|
311
|
-
if not 0.0 < confidence < 1.0:
|
|
312
|
-
raise ValueError("confidence must be strictly between 0 and 1")
|
|
313
|
-
if uncertainty not in ("auto", "none", "normal", "bootstrap", "both"):
|
|
314
|
-
raise ValueError("unknown uncertainty method")
|
|
315
|
-
if bootstrap_samples < 2:
|
|
316
|
-
raise ValueError("bootstrap_samples must be >= 2")
|
|
317
|
-
if not 0.0 < min_bootstrap_success_fraction <= 1.0:
|
|
318
|
-
raise ValueError("min_bootstrap_success_fraction must lie in (0, 1]")
|
|
319
|
-
if uncertainty in ("normal", "both") and loss != "squared":
|
|
320
|
-
raise ValueError("normal-approximation uncertainty requires squared loss")
|
|
321
|
-
if bounds is not None:
|
|
322
|
-
if len(bounds) != len(names):
|
|
323
|
-
raise ValueError("bounds must have the same length as parameter_names")
|
|
324
|
-
if any(lower > upper for lower, upper in bounds):
|
|
325
|
-
raise ValueError("each bound must satisfy lower <= upper")
|
|
326
|
-
if any(value < lower or value > upper for value, (lower, upper) in zip(start, bounds)):
|
|
327
|
-
raise ValueError("x0 must lie inside bounds")
|
|
328
|
-
if optimizer not in ("auto", "projected_gradient"):
|
|
329
|
-
raise ValueError("bounded fitting requires optimizer='auto' or 'projected_gradient'")
|
|
330
|
-
|
|
331
|
-
label = target_label if target_label is not None else model.equations[0][0]
|
|
332
|
-
model.equation(label)
|
|
333
|
-
|
|
334
|
-
def objective(values: list[float]) -> float:
|
|
335
|
-
residuals = _prediction_residuals(model, observations, names, values, label)
|
|
336
|
-
return sum(_loss_value(residual, loss, huber_delta) for residual in residuals)
|
|
337
|
-
|
|
338
|
-
chosen, rationale = _select_optimizer(optimizer, loss, bounds)
|
|
339
|
-
starts = _make_starts(start, multi_start, bounds, seed)
|
|
340
|
-
best_values: list[float] | None = None
|
|
341
|
-
best_objective = math.inf
|
|
342
|
-
best_iterations = 0
|
|
343
|
-
best_converged = False
|
|
344
|
-
|
|
345
|
-
for candidate in starts:
|
|
346
|
-
if chosen == "gradient_descent":
|
|
347
|
-
gd_result = gradient_descent(objective, candidate, lr=lr, tol=tol, max_iter=max_iter)
|
|
348
|
-
values = list(gd_result.x)
|
|
349
|
-
score = gd_result.value
|
|
350
|
-
iterations = gd_result.iterations
|
|
351
|
-
converged = gd_result.converged
|
|
352
|
-
elif chosen == "adam":
|
|
353
|
-
adam_result = adam(objective, candidate, lr=lr, tol=tol, max_iter=max_iter)
|
|
354
|
-
values = list(adam_result.x)
|
|
355
|
-
score = adam_result.value
|
|
356
|
-
iterations = adam_result.iterations
|
|
357
|
-
converged = adam_result.converged
|
|
358
|
-
elif chosen == "nelder_mead":
|
|
359
|
-
nm_result = nelder_mead(objective, candidate, max_iter=max_iter)
|
|
360
|
-
values = list(nm_result.x)
|
|
361
|
-
score = nm_result.value
|
|
362
|
-
iterations = nm_result.iterations
|
|
363
|
-
converged = nm_result.converged
|
|
364
|
-
else:
|
|
365
|
-
if bounds is None:
|
|
366
|
-
raise ValueError("projected_gradient requires bounds")
|
|
367
|
-
lower = [pair[0] for pair in bounds]
|
|
368
|
-
upper = [pair[1] for pair in bounds]
|
|
369
|
-
pg_result = projected_gradient_descent(
|
|
370
|
-
objective,
|
|
371
|
-
candidate,
|
|
372
|
-
lower,
|
|
373
|
-
upper,
|
|
374
|
-
lr=lr,
|
|
375
|
-
tol=tol,
|
|
376
|
-
max_iter=max_iter,
|
|
377
|
-
)
|
|
378
|
-
values = list(pg_result.x)
|
|
379
|
-
score = pg_result.fun
|
|
380
|
-
iterations = pg_result.iterations
|
|
381
|
-
converged = pg_result.converged
|
|
382
|
-
|
|
383
|
-
if math.isfinite(score) and score < best_objective:
|
|
384
|
-
best_values = values
|
|
385
|
-
best_objective = score
|
|
386
|
-
best_iterations = iterations
|
|
387
|
-
best_converged = converged
|
|
388
|
-
|
|
389
|
-
if best_values is None:
|
|
390
|
-
raise ArithmeticError("all fitting attempts produced non-finite objective values")
|
|
391
|
-
|
|
392
|
-
residuals = _prediction_residuals(model, observations, names, best_values, label)
|
|
393
|
-
n = len(residuals)
|
|
394
|
-
rmse = math.sqrt(sum(value * value for value in residuals) / n)
|
|
395
|
-
mae = sum(abs(value) for value in residuals) / n
|
|
396
|
-
observed_values = [value for _, value in observations]
|
|
397
|
-
observed_mean = sum(observed_values) / len(observed_values)
|
|
398
|
-
total_variation = sum((value - observed_mean) ** 2 for value in observed_values)
|
|
399
|
-
rss = sum(value * value for value in residuals)
|
|
400
|
-
r_squared = 1.0 - rss / total_variation if total_variation > 0 else (1.0 if rss == 0 else 0.0)
|
|
401
|
-
|
|
402
|
-
resolved_uncertainty: FitUncertainty
|
|
403
|
-
if uncertainty == "auto":
|
|
404
|
-
resolved_uncertainty = "normal" if loss == "squared" else "none"
|
|
405
|
-
else:
|
|
406
|
-
resolved_uncertainty = uncertainty
|
|
407
|
-
|
|
408
|
-
normal_errors: dict[str, float] | None = None
|
|
409
|
-
normal_intervals: dict[str, tuple[float, float]] | None = None
|
|
410
|
-
normal_identifiable = False
|
|
411
|
-
if resolved_uncertainty in ("normal", "both"):
|
|
412
|
-
normal_errors, normal_intervals, normal_identifiable = _uncertainty(
|
|
413
|
-
model,
|
|
414
|
-
observations,
|
|
415
|
-
names,
|
|
416
|
-
best_values,
|
|
417
|
-
label,
|
|
418
|
-
residuals,
|
|
419
|
-
confidence,
|
|
420
|
-
)
|
|
421
|
-
|
|
422
|
-
bootstrap_errors: dict[str, float] | None = None
|
|
423
|
-
bootstrap_intervals: dict[str, tuple[float, float]] | None = None
|
|
424
|
-
bootstrap_successes = 0
|
|
425
|
-
if resolved_uncertainty in ("bootstrap", "both"):
|
|
426
|
-
bootstrap_errors, bootstrap_intervals, bootstrap_successes = _bootstrap_uncertainty(
|
|
427
|
-
model,
|
|
428
|
-
observations,
|
|
429
|
-
names,
|
|
430
|
-
best_values,
|
|
431
|
-
target_label=label,
|
|
432
|
-
optimizer=optimizer,
|
|
433
|
-
loss=loss,
|
|
434
|
-
bounds=bounds,
|
|
435
|
-
huber_delta=huber_delta,
|
|
436
|
-
confidence=confidence,
|
|
437
|
-
bootstrap_samples=bootstrap_samples,
|
|
438
|
-
bootstrap_seed=seed if bootstrap_seed is None else bootstrap_seed,
|
|
439
|
-
min_success_fraction=min_bootstrap_success_fraction,
|
|
440
|
-
lr=lr,
|
|
441
|
-
tol=tol,
|
|
442
|
-
max_iter=max_iter,
|
|
443
|
-
)
|
|
444
|
-
|
|
445
|
-
if resolved_uncertainty == "bootstrap":
|
|
446
|
-
standard_errors = bootstrap_errors
|
|
447
|
-
intervals = bootstrap_intervals
|
|
448
|
-
identifiable = bootstrap_intervals is not None
|
|
449
|
-
else:
|
|
450
|
-
standard_errors = normal_errors
|
|
451
|
-
intervals = normal_intervals
|
|
452
|
-
identifiable = normal_identifiable
|
|
453
|
-
if resolved_uncertainty == "both":
|
|
454
|
-
identifiable = normal_identifiable and bootstrap_intervals is not None
|
|
455
|
-
|
|
456
|
-
diagnostics = FitDiagnostics(
|
|
457
|
-
residuals=tuple(residuals),
|
|
458
|
-
rmse=rmse,
|
|
459
|
-
mae=mae,
|
|
460
|
-
r_squared=r_squared,
|
|
461
|
-
standard_errors=standard_errors,
|
|
462
|
-
confidence_intervals=intervals,
|
|
463
|
-
identifiable=identifiable,
|
|
464
|
-
uncertainty_method=resolved_uncertainty,
|
|
465
|
-
bootstrap_confidence_intervals=bootstrap_intervals,
|
|
466
|
-
bootstrap_successes=bootstrap_successes,
|
|
467
|
-
)
|
|
468
|
-
return AdvancedFitResult(
|
|
469
|
-
parameters=dict(zip(names, best_values)),
|
|
470
|
-
objective=best_objective,
|
|
471
|
-
iterations=best_iterations,
|
|
472
|
-
converged=best_converged,
|
|
473
|
-
optimizer=chosen,
|
|
474
|
-
optimizer_rationale=rationale,
|
|
475
|
-
starts_tried=len(starts),
|
|
476
|
-
diagnostics=diagnostics,
|
|
477
|
-
)
|
|
@@ -1,134 +0,0 @@
|
|
|
1
|
-
"""Named systems of equations — :class:`MathModel`.
|
|
2
|
-
|
|
3
|
-
A :class:`MathModel` bundles a set of named symbolic expressions with shared
|
|
4
|
-
parameters and variables. It is the natural unit for "equation development":
|
|
5
|
-
you write ``v = u + a*t``, then ask the model for the Jacobian column
|
|
6
|
-
``dv/da``, render the whole system to Markdown or LaTeX, and finally hand a
|
|
7
|
-
single equation to :func:`cds.modeling.solver.solve_equation` to find a root.
|
|
8
|
-
|
|
9
|
-
This module is deliberately thin — all symbolic machinery lives in
|
|
10
|
-
:mod:`cds.modeling.expression`. :class:`MathModel` only adds bookkeeping
|
|
11
|
-
(name → expression, parameters, declared variables) and rendering.
|
|
12
|
-
"""
|
|
13
|
-
|
|
14
|
-
from __future__ import annotations
|
|
15
|
-
|
|
16
|
-
from dataclasses import dataclass, field
|
|
17
|
-
|
|
18
|
-
from cds.modeling.expression import Expression
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
@dataclass
|
|
22
|
-
class MathModel:
|
|
23
|
-
"""A named system of symbolic equations sharing parameters and variables.
|
|
24
|
-
|
|
25
|
-
Attributes:
|
|
26
|
-
name: human-readable model title (used in :meth:`to_markdown`).
|
|
27
|
-
equations: ordered ``(label, expression)`` pairs. Labels are the
|
|
28
|
-
equation names callers refer to (e.g. ``"velocity"``);
|
|
29
|
-
expressions are symbolic :class:`Expression` trees.
|
|
30
|
-
parameters: constant values substituted during evaluation. They
|
|
31
|
-
shadow variables of the same name, mirroring how a physicist
|
|
32
|
-
treats ``g`` vs ``t``.
|
|
33
|
-
variables: the declared free variables. Recorded explicitly so the
|
|
34
|
-
model is self-describing even before any equation is inspected.
|
|
35
|
-
description: optional one-line summary.
|
|
36
|
-
"""
|
|
37
|
-
|
|
38
|
-
name: str
|
|
39
|
-
equations: list[tuple[str, Expression]] = field(default_factory=list)
|
|
40
|
-
parameters: dict[str, float] = field(default_factory=dict)
|
|
41
|
-
variables: list[str] = field(default_factory=list)
|
|
42
|
-
description: str | None = None
|
|
43
|
-
|
|
44
|
-
# ------------------------------------------------------------------ #
|
|
45
|
-
# Construction helpers
|
|
46
|
-
# ------------------------------------------------------------------ #
|
|
47
|
-
def add_equation(self, label: str, expr: Expression) -> None:
|
|
48
|
-
"""Append a named equation to the system."""
|
|
49
|
-
self.equations.append((label, expr))
|
|
50
|
-
|
|
51
|
-
def set_parameter(self, name: str, value: float) -> None:
|
|
52
|
-
"""Bind or update a named parameter value."""
|
|
53
|
-
self.parameters[name] = float(value)
|
|
54
|
-
|
|
55
|
-
# ------------------------------------------------------------------ #
|
|
56
|
-
# Analysis
|
|
57
|
-
# ------------------------------------------------------------------ #
|
|
58
|
-
def evaluate(self, env: dict[str, float]) -> dict[str, float]:
|
|
59
|
-
"""Evaluate every equation, merging parameters into the bindings.
|
|
60
|
-
|
|
61
|
-
Args:
|
|
62
|
-
env: values for the free variables (parameters override these
|
|
63
|
-
if a name collides).
|
|
64
|
-
|
|
65
|
-
Returns:
|
|
66
|
-
mapping of equation label to its evaluated numeric value.
|
|
67
|
-
|
|
68
|
-
Raises:
|
|
69
|
-
ValueError: if a free variable has no binding (propagated from
|
|
70
|
-
:meth:`Expression.evaluate`).
|
|
71
|
-
"""
|
|
72
|
-
merged: dict[str, float] = {**env, **self.parameters}
|
|
73
|
-
return {label: expr.evaluate(merged) for label, expr in self.equations}
|
|
74
|
-
|
|
75
|
-
def equation(self, label: str) -> Expression:
|
|
76
|
-
"""Return the expression for a named equation.
|
|
77
|
-
|
|
78
|
-
Raises:
|
|
79
|
-
KeyError: if ``label`` is not in this model.
|
|
80
|
-
"""
|
|
81
|
-
for name, expr in self.equations:
|
|
82
|
-
if name == label:
|
|
83
|
-
return expr
|
|
84
|
-
raise KeyError(f"no equation labelled {label!r} in model {self.name!r}")
|
|
85
|
-
|
|
86
|
-
def gradient(self, label: str, var: str) -> Expression:
|
|
87
|
-
"""Symbolic partial derivative of one equation w.r.t. one variable."""
|
|
88
|
-
return self.equation(label).diff(var)
|
|
89
|
-
|
|
90
|
-
def jacobian(self, var: str) -> dict[str, Expression]:
|
|
91
|
-
"""Symbolic partial derivative of *every* equation w.r.t. ``var``.
|
|
92
|
-
|
|
93
|
-
Returns:
|
|
94
|
-
mapping of equation label to its derivative expression.
|
|
95
|
-
"""
|
|
96
|
-
return {label: expr.diff(var) for label, expr in self.equations}
|
|
97
|
-
|
|
98
|
-
def free_variables(self) -> set[str]:
|
|
99
|
-
"""All variable names that actually appear in some equation."""
|
|
100
|
-
seen: set[str] = set()
|
|
101
|
-
for _, expr in self.equations:
|
|
102
|
-
seen |= expr.variables()
|
|
103
|
-
return seen - set(self.parameters)
|
|
104
|
-
|
|
105
|
-
# ------------------------------------------------------------------ #
|
|
106
|
-
# Rendering
|
|
107
|
-
# ------------------------------------------------------------------ #
|
|
108
|
-
def to_markdown(self) -> str:
|
|
109
|
-
"""Render this model as a structured Markdown document."""
|
|
110
|
-
lines: list[str] = [f"# Model: {self.name}", ""]
|
|
111
|
-
if self.description:
|
|
112
|
-
lines += [self.description, ""]
|
|
113
|
-
if self.parameters:
|
|
114
|
-
lines.append("## Parameters")
|
|
115
|
-
for name, value in self.parameters.items():
|
|
116
|
-
lines.append(f"- `{name}` = {value}")
|
|
117
|
-
lines.append("")
|
|
118
|
-
if self.variables:
|
|
119
|
-
lines += [
|
|
120
|
-
"## Variables",
|
|
121
|
-
", ".join(f"`{v}`" for v in self.variables),
|
|
122
|
-
"",
|
|
123
|
-
]
|
|
124
|
-
lines += ["## Equations"]
|
|
125
|
-
for label, expr in self.equations:
|
|
126
|
-
lines.append(f"- **{label}**: `{expr.to_str()}`")
|
|
127
|
-
lines.append("")
|
|
128
|
-
return "\n".join(lines)
|
|
129
|
-
|
|
130
|
-
def to_latex(self) -> str:
|
|
131
|
-
"""Render the model's equations as a LaTeX align block."""
|
|
132
|
-
rows = [f"{label} &= {expr.to_latex()}" for label, expr in self.equations]
|
|
133
|
-
body = " \\\\ ".join(rows)
|
|
134
|
-
return f"\\begin{{align*}}\n{body}\n\\end{{align*}}"
|