scientific-computing-system 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.binder/postBuild +9 -0
- package/.binder/requirements.txt +10 -0
- package/.gitattributes +35 -0
- package/.github/CODEOWNERS +4 -0
- package/.github/FUNDING.yml +3 -0
- package/.github/ISSUE_TEMPLATE/bug_report.md +50 -0
- package/.github/ISSUE_TEMPLATE/config.yml +8 -0
- package/.github/ISSUE_TEMPLATE/feature_request.md +28 -0
- package/.github/PULL_REQUEST_TEMPLATE.md +29 -0
- package/.github/dependabot.yml +32 -0
- package/.github/labeler.yml +50 -0
- package/.github/workflows/benchmarks.yml +97 -0
- package/.github/workflows/bot-reviewer.yml +58 -0
- package/.github/workflows/changelog.yml +130 -0
- package/.github/workflows/cli-package-smoke.yml +45 -0
- package/.github/workflows/codeql.yml +55 -0
- package/.github/workflows/npm-publish.yml +33 -0
- package/.github/workflows/p08-cancel-noncanonical-runs.yml +41 -0
- package/.github/workflows/pr-automation.yml +78 -0
- package/.github/workflows/public-external-validation-p08-v2-glm.yml +161 -0
- package/.github/workflows/public-external-validation-p08-v2-recovery-merge-gate.yml +72 -0
- package/.github/workflows/public-external-validation-p08-v2-recovery-merge.yml +113 -0
- package/.github/workflows/public-external-validation-p08-v2-run-recovery-anatomy-gate.yml +57 -0
- package/.github/workflows/public-external-validation-p08-v2-run-recovery-merge-gate.yml +63 -0
- package/.github/workflows/public-external-validation-p08-v2-run-recovery-merge.yml +89 -0
- package/.github/workflows/public-external-validation-p08-v2-run-recovery.yml +182 -0
- package/.github/workflows/public-external-validation-p08-v3-glm-gate.yml +67 -0
- package/.github/workflows/public-external-validation-p08-v4-recovery-glm-gate.yml +78 -0
- package/.github/workflows/public-external-validation-p08-v4-recovery-glm.yml +248 -0
- package/.github/workflows/public-external-validation-p08-v5-run-recovery-glm-gate.yml +66 -0
- package/.github/workflows/public-external-validation-p08-v5-run-recovery-glm.yml +218 -0
- package/.github/workflows/pypi-registry-smoke.yml +116 -0
- package/.github/workflows/release.yml +359 -0
- package/.github/workflows/tests.yml +250 -0
- package/.github/workflows/tmp-compassion-raw-acquire.yml +63 -0
- package/.github/workflows/wsl-science-runner-smoke.yml +45 -0
- package/.pre-commit-config.yaml +48 -0
- package/CHANGELOG.md +1139 -0
- package/CITATION.cff +29 -0
- package/CODE_OF_CONDUCT.md +25 -0
- package/CONTRIBUTING.md +275 -0
- package/LICENSE +21 -0
- package/README.md +281 -0
- package/ROADMAP.md +155 -0
- package/SECURITY.md +82 -0
- package/assets/logo.svg +38 -0
- package/assets/social_preview.png +0 -0
- package/benchmarks/results.json +43 -0
- package/benchmarks/robust_runner.py +118 -0
- package/benchmarks/run_benchmarks.py +394 -0
- package/bin/scs.js +2 -0
- package/cliff.toml +100 -0
- package/dashboard/app.py +224 -0
- package/docs/ARCHITECTURE.md +252 -0
- package/docs/CASE_STUDY_HUBBLE.md +78 -0
- package/docs/CASE_STUDY_QUANTUM_ML.md +79 -0
- package/docs/api.md +133 -0
- package/docs/assets/icon.svg +17 -0
- package/docs/assets/logo.svg +38 -0
- package/docs/benchmarks.md +62 -0
- package/docs/cookbook.md +930 -0
- package/docs/getting-started.md +185 -0
- package/docs/index.md +111 -0
- package/docs/maintenance.md +61 -0
- package/docs/ml_reference.md +92 -0
- package/docs/research-workflows.md +82 -0
- package/docs/stylesheets/extra.css +122 -0
- package/docs/tour_of_numerical_methods.md +330 -0
- package/docs/tutorials/core_demo.md +35 -0
- package/docs/tutorials/data_analysis_demo.md +43 -0
- package/docs/tutorials/diffeq_demo.md +48 -0
- package/docs/tutorials/fft2_demo.md +67 -0
- package/docs/tutorials/graph_demo.md +45 -0
- package/docs/tutorials/hypothesis_demo.md +44 -0
- package/docs/tutorials/hypothesis_tests_demo.md +170 -0
- package/docs/tutorials/hypothesis_with_stats_demo.md +80 -0
- package/docs/tutorials/knowledge_demo.md +114 -0
- package/docs/tutorials/linalg_demo.md +103 -0
- package/docs/tutorials/math_utils_demo.md +46 -0
- package/docs/tutorials/ml_advanced_demo.md +96 -0
- package/docs/tutorials/ml_and_viz_demo.md +93 -0
- package/docs/tutorials/ml_demo.md +70 -0
- package/docs/tutorials/modeling_demo.md +82 -0
- package/docs/tutorials/montecarlo_demo.md +42 -0
- package/docs/tutorials/nlp_attention_demo.md +107 -0
- package/docs/tutorials/nlp_bpe_demo.md +103 -0
- package/docs/tutorials/nlp_mini_gpt_demo.md +110 -0
- package/docs/tutorials/nlp_viz.md +76 -0
- package/docs/tutorials/numerical_integration_demo.md +65 -0
- package/docs/tutorials/optimization_demo.md +106 -0
- package/docs/tutorials/pandas_io_demo.md +160 -0
- package/docs/tutorials/pca_demo.md +87 -0
- package/docs/tutorials/probability_demo.md +48 -0
- package/docs/tutorials/quantum_demo.md +31 -0
- package/docs/tutorials/quick_start.md +44 -0
- package/docs/tutorials/scientific_demo.md +46 -0
- package/docs/tutorials/signals_demo.md +167 -0
- package/docs/tutorials/stats_demo.md +94 -0
- package/docs/tutorials/stiff_ode_demo.md +84 -0
- package/docs/tutorials/time_series_demo.md +145 -0
- package/examples/core_demo.py +40 -0
- package/examples/data_analysis_demo.py +60 -0
- package/examples/diffeq_demo.py +34 -0
- package/examples/discovery_pipeline_demo.py +57 -0
- package/examples/ensemble_showcase.py +81 -0
- package/examples/fft2_demo.py +32 -0
- package/examples/graph_demo.py +49 -0
- package/examples/hypothesis_custom_generator.py +121 -0
- package/examples/hypothesis_demo.py +48 -0
- package/examples/hypothesis_tests_demo.py +52 -0
- package/examples/hypothesis_with_stats_demo.py +43 -0
- package/examples/interpolate_demo.py +57 -0
- package/examples/knowledge_demo.py +100 -0
- package/examples/linalg_demo.py +61 -0
- package/examples/math_utils_demo.py +53 -0
- package/examples/ml_and_viz_demo.py +47 -0
- package/examples/modeling_demo.py +110 -0
- package/examples/montecarlo_demo.py +41 -0
- package/examples/nlp_attention_demo.py +168 -0
- package/examples/nlp_bpe_demo.py +79 -0
- package/examples/nlp_mini_gpt_demo.py +76 -0
- package/examples/nlp_viz_demo.py +98 -0
- package/examples/numerical_integration_demo.py +60 -0
- package/examples/optimization_demo.py +34 -0
- package/examples/pca_demo.py +124 -0
- package/examples/pde_demo.py +65 -0
- package/examples/plot_demo.py +84 -0
- package/examples/plotting_notebook.ipynb +87 -0
- package/examples/probability_demo.py +39 -0
- package/examples/quantum_demo.py +42 -0
- package/examples/scientific_demo.py +49 -0
- package/examples/signals_demo.py +86 -0
- package/examples/stats_demo.py +40 -0
- package/examples/tour_of_numerical_methods.ipynb +497 -0
- package/index.js +1 -0
- package/mkdocs.yml +159 -0
- package/package.json +1 -0
- package/pyproject.toml +288 -0
- package/requirements-dev.lock +427 -0
- package/requirements-dev.txt +39 -0
- package/requirements.lock +6 -0
- package/requirements.txt +13 -0
- package/scripts/build_gif.py +111 -0
- package/scripts/build_video.py +214 -0
- package/scripts/cleanup_deployments.py +173 -0
- package/scripts/crop_readme_png.py +40 -0
- package/scripts/make_pi_dashboard.py +316 -0
- package/scripts/make_pi_gif.py +138 -0
- package/scripts/publish.py +203 -0
- package/scripts/render_promo.mjs +93 -0
- package/scripts/render_readme.py +211 -0
- package/scripts/render_readme_sections.py +168 -0
- package/scripts/verify_cli_install.py +99 -0
- package/scripts/verify_cookbook.py +601 -0
- package/scripts/verify_d1_numerics.py +504 -0
- package/scripts/verify_d2_edge_cases.py +442 -0
- package/scripts/verify_d4_hypothesis.py +337 -0
- package/scripts/verify_ml_reference.py +160 -0
- package/scripts/verify_pypi_release.py +97 -0
- package/scripts/verify_release_integrity.py +194 -0
- package/src/cds/__init__.py +132 -0
- package/src/cds/__main__.py +8 -0
- package/src/cds/_version.py +11 -0
- package/src/cds/bayes/__init__.py +25 -0
- package/src/cds/bayes/conjugate.py +560 -0
- package/src/cds/cli/__init__.py +104 -0
- package/src/cds/cli/__main__.py +8 -0
- package/src/cds/cli/_handlers.py +323 -0
- package/src/cds/cli/_parser.py +155 -0
- package/src/cds/cli/_style.py +208 -0
- package/src/cds/cli/_system_info.py +71 -0
- package/src/cds/core/__init__.py +5 -0
- package/src/cds/core/_numeric.py +92 -0
- package/src/cds/core/models.py +166 -0
- package/src/cds/data_analysis/__init__.py +30 -0
- package/src/cds/data_analysis/dataset.py +122 -0
- package/src/cds/data_analysis/loader.py +75 -0
- package/src/cds/data_analysis/pandas_io.py +108 -0
- package/src/cds/data_analysis/transform.py +36 -0
- package/src/cds/data_analysis/viz.py +88 -0
- package/src/cds/data_io/__init__.py +27 -0
- package/src/cds/data_io/streaming.py +314 -0
- package/src/cds/diffeq/__init__.py +37 -0
- package/src/cds/diffeq/_implicit.py +349 -0
- package/src/cds/diffeq/solvers.py +312 -0
- package/src/cds/diffeq/symplectic.py +225 -0
- package/src/cds/fractals/__init__.py +34 -0
- package/src/cds/fractals/sets.py +356 -0
- package/src/cds/genetics/__init__.py +22 -0
- package/src/cds/genetics/sequence.py +199 -0
- package/src/cds/graph/__init__.py +31 -0
- package/src/cds/graph/algorithms.py +399 -0
- package/src/cds/hypothesis/__init__.py +51 -0
- package/src/cds/hypothesis/evaluator.py +311 -0
- package/src/cds/hypothesis/generator.py +275 -0
- package/src/cds/hypothesis/mining.py +314 -0
- package/src/cds/infotheory/__init__.py +25 -0
- package/src/cds/infotheory/measures.py +276 -0
- package/src/cds/interpolate/__init__.py +156 -0
- package/src/cds/knowledge/__init__.py +45 -0
- package/src/cds/knowledge/graph.py +489 -0
- package/src/cds/knowledge/notes.py +231 -0
- package/src/cds/knowledge/retrieval.py +339 -0
- package/src/cds/math_utils/__init__.py +46 -0
- package/src/cds/math_utils/calculus.py +40 -0
- package/src/cds/math_utils/linalg.py +496 -0
- package/src/cds/math_utils/special.py +167 -0
- package/src/cds/math_utils/svd.py +261 -0
- package/src/cds/ml/__init__.py +60 -0
- package/src/cds/ml/boosting.py +304 -0
- package/src/cds/ml/clustering.py +190 -0
- package/src/cds/ml/decomposition.py +172 -0
- package/src/cds/ml/ensemble.py +152 -0
- package/src/cds/ml/linear_models.py +225 -0
- package/src/cds/ml/metrics.py +227 -0
- package/src/cds/ml/model_selection.py +150 -0
- package/src/cds/ml/naive_bayes.py +179 -0
- package/src/cds/ml/neighbors.py +162 -0
- package/src/cds/ml/neural.py +204 -0
- package/src/cds/ml/preprocessing.py +131 -0
- package/src/cds/ml/tree.py +228 -0
- package/src/cds/ml/voting.py +175 -0
- package/src/cds/modeling/__init__.py +44 -0
- package/src/cds/modeling/_base.py +210 -0
- package/src/cds/modeling/_nodes.py +526 -0
- package/src/cds/modeling/expression.py +81 -0
- package/src/cds/modeling/fitting.py +477 -0
- package/src/cds/modeling/model.py +134 -0
- package/src/cds/modeling/solver.py +187 -0
- package/src/cds/montecarlo/__init__.py +24 -0
- package/src/cds/montecarlo/markov.py +112 -0
- package/src/cds/montecarlo/methods.py +294 -0
- package/src/cds/nlp/__init__.py +170 -0
- package/src/cds/nlp/attention.py +285 -0
- package/src/cds/nlp/autograd/__init__.py +70 -0
- package/src/cds/nlp/autograd/_grad.py +120 -0
- package/src/cds/nlp/autograd/ops.py +133 -0
- package/src/cds/nlp/autograd/tensor.py +298 -0
- package/src/cds/nlp/bpe.py +449 -0
- package/src/cds/nlp/data.py +70 -0
- package/src/cds/nlp/embed.py +190 -0
- package/src/cds/nlp/layers.py +259 -0
- package/src/cds/nlp/model.py +456 -0
- package/src/cds/nlp/optim.py +163 -0
- package/src/cds/nlp/training.py +167 -0
- package/src/cds/nlp/viz.py +254 -0
- package/src/cds/numerical_integration/__init__.py +31 -0
- package/src/cds/numerical_integration/quadrature.py +480 -0
- package/src/cds/optimization/__init__.py +26 -0
- package/src/cds/optimization/_metaheuristics.py +287 -0
- package/src/cds/optimization/constrained.py +212 -0
- package/src/cds/optimization/minimize.py +425 -0
- package/src/cds/pde/__init__.py +266 -0
- package/src/cds/plot/__init__.py +49 -0
- package/src/cds/plot/_backend.py +32 -0
- package/src/cds/plot/charts.py +462 -0
- package/src/cds/probability/__init__.py +65 -0
- package/src/cds/probability/_advanced.py +283 -0
- package/src/cds/probability/distributions.py +236 -0
- package/src/cds/probability/extra_distributions.py +199 -0
- package/src/cds/provenance/__init__.py +25 -0
- package/src/cds/provenance/manifest.py +355 -0
- package/src/cds/py.typed +0 -0
- package/src/cds/quantum/__init__.py +51 -0
- package/src/cds/quantum/circuit.py +122 -0
- package/src/cds/quantum/multi_qubit.py +310 -0
- package/src/cds/quantum/simulator.py +53 -0
- package/src/cds/scientific/__init__.py +34 -0
- package/src/cds/scientific/constants.py +35 -0
- package/src/cds/scientific/formulas.py +116 -0
- package/src/cds/sensitivity.py +204 -0
- package/src/cds/signals/__init__.py +59 -0
- package/src/cds/signals/filters.py +449 -0
- package/src/cds/signals/processing.py +224 -0
- package/src/cds/signals/stft.py +177 -0
- package/src/cds/signals/wavelet.py +146 -0
- package/src/cds/stats/__init__.py +99 -0
- package/src/cds/stats/_distributions.py +102 -0
- package/src/cds/stats/bootstrap.py +188 -0
- package/src/cds/stats/descriptive.py +172 -0
- package/src/cds/stats/hypothesis_tests.py +294 -0
- package/src/cds/stats/nonparametric.py +141 -0
- package/src/cds/stats/power.py +290 -0
- package/src/cds/stats/regression.py +51 -0
- package/src/cds/stats/time_series.py +420 -0
- package/src/cds/tools/__init__.py +29 -0
- package/src/cds/tools/adapters.py +218 -0
- package/src/cds/tools/registry.py +181 -0
- package/src/cds/uncertainty/__init__.py +17 -0
- package/src/cds/uncertainty/propagation.py +233 -0
- package/src/cds/units/__init__.py +45 -0
- package/src/cds/units/core.py +199 -0
- package/src/cds/validation/__init__.py +41 -0
- package/src/cds/validation/adequacy.py +157 -0
- package/src/cds/validation/checks.py +485 -0
- package/src/cds/validation/report.py +50 -0
- package/src/cds/wavelets/__init__.py +5 -0
- package/src/cds/wavelets/haar.py +219 -0
- package/src/cds/workflow/__init__.py +77 -0
- package/src/cds/workflow/engine.py +116 -0
- package/src/cds/workflow/gates.py +120 -0
- package/src/cds/workflow/orchestrator.py +431 -0
- package/src/cds/workflow/selection.py +454 -0
- package/src/cds/workflow/tooling.py +155 -0
- package/src/cds/workflow/types.py +107 -0
- package/tests/__init__.py +0 -0
- package/tests/conftest.py +109 -0
- package/tests/test_advanced_fitting.py +247 -0
- package/tests/test_audit_completion_coverage.py +183 -0
- package/tests/test_audit_guard_coverage.py +115 -0
- package/tests/test_audit_hardening.py +138 -0
- package/tests/test_audit_hardening_coverage.py +111 -0
- package/tests/test_bayes_v2.py +208 -0
- package/tests/test_benchmarks.py +111 -0
- package/tests/test_bootstrap.py +135 -0
- package/tests/test_cli.py +51 -0
- package/tests/test_cli_color.py +114 -0
- package/tests/test_cli_extended.py +239 -0
- package/tests/test_cli_system_info.py +36 -0
- package/tests/test_constrained_opt.py +174 -0
- package/tests/test_core.py +273 -0
- package/tests/test_data_analysis.py +146 -0
- package/tests/test_data_analysis_lazy_bridge.py +68 -0
- package/tests/test_data_analysis_pandas_io.py +119 -0
- package/tests/test_data_io.py +149 -0
- package/tests/test_dataset.py +91 -0
- package/tests/test_diffeq.py +186 -0
- package/tests/test_diffeq_implicit.py +173 -0
- package/tests/test_domain_validation.py +66 -0
- package/tests/test_edge_misc_numerical.py +666 -0
- package/tests/test_edge_ml_quantum_linalg.py +191 -0
- package/tests/test_edge_nlp.py +229 -0
- package/tests/test_edge_quantum_evaluator_cli.py +601 -0
- package/tests/test_edge_stats_optimization_signals.py +406 -0
- package/tests/test_extra_distributions.py +206 -0
- package/tests/test_fft2.py +67 -0
- package/tests/test_fitting_bootstrap.py +202 -0
- package/tests/test_fractals.py +387 -0
- package/tests/test_genetics.py +159 -0
- package/tests/test_graph.py +380 -0
- package/tests/test_hardening_privacy_provenance.py +306 -0
- package/tests/test_hypothesis.py +216 -0
- package/tests/test_hypothesis_engine.py +59 -0
- package/tests/test_hypothesis_mining.py +247 -0
- package/tests/test_hypothesis_tests.py +277 -0
- package/tests/test_infotheory.py +302 -0
- package/tests/test_interpolate.py +189 -0
- package/tests/test_knowledge.py +1149 -0
- package/tests/test_layering.py +112 -0
- package/tests/test_linalg_extended.py +179 -0
- package/tests/test_linalg_qr_cholesky.py +68 -0
- package/tests/test_markov.py +155 -0
- package/tests/test_math_utils.py +157 -0
- package/tests/test_ml_boosting.py +148 -0
- package/tests/test_ml_clustering.py +92 -0
- package/tests/test_ml_ensemble.py +103 -0
- package/tests/test_ml_knn.py +95 -0
- package/tests/test_ml_linreg.py +70 -0
- package/tests/test_ml_logreg.py +84 -0
- package/tests/test_ml_metrics.py +125 -0
- package/tests/test_ml_model_selection.py +108 -0
- package/tests/test_ml_naive_bayes.py +183 -0
- package/tests/test_ml_pca.py +98 -0
- package/tests/test_ml_preprocessing.py +104 -0
- package/tests/test_ml_tree.py +89 -0
- package/tests/test_ml_viz.py +58 -0
- package/tests/test_ml_voting.py +219 -0
- package/tests/test_modeling.py +726 -0
- package/tests/test_modeling_fit_validation.py +46 -0
- package/tests/test_montecarlo.py +245 -0
- package/tests/test_multi_qubit.py +466 -0
- package/tests/test_nlp_attention.py +335 -0
- package/tests/test_nlp_autograd.py +435 -0
- package/tests/test_nlp_bpe.py +463 -0
- package/tests/test_nlp_embed.py +240 -0
- package/tests/test_nlp_layers.py +276 -0
- package/tests/test_nlp_model.py +172 -0
- package/tests/test_nlp_training.py +262 -0
- package/tests/test_nlp_viz.py +188 -0
- package/tests/test_numerical_integration.py +374 -0
- package/tests/test_numerical_invariants.py +768 -0
- package/tests/test_numerical_oracles.py +241 -0
- package/tests/test_optimization.py +139 -0
- package/tests/test_optimization_metaheuristics.py +221 -0
- package/tests/test_pde.py +294 -0
- package/tests/test_plot_charts.py +247 -0
- package/tests/test_plot_lazy.py +48 -0
- package/tests/test_power.py +226 -0
- package/tests/test_probability.py +274 -0
- package/tests/test_probability_advanced.py +226 -0
- package/tests/test_property_invariants.py +277 -0
- package/tests/test_provenance.py +215 -0
- package/tests/test_provenance_audit_hardening.py +45 -0
- package/tests/test_public_api.py +75 -0
- package/tests/test_quantum.py +195 -0
- package/tests/test_release_contract.py +105 -0
- package/tests/test_retrieval.py +255 -0
- package/tests/test_scientific.py +185 -0
- package/tests/test_selection_audit_hardening.py +55 -0
- package/tests/test_sensitivity.py +59 -0
- package/tests/test_sensitivity_global.py +73 -0
- package/tests/test_signals.py +146 -0
- package/tests/test_signals_filters.py +460 -0
- package/tests/test_special_invariants.py +222 -0
- package/tests/test_special_numerics.py +44 -0
- package/tests/test_statistical_audit.py +75 -0
- package/tests/test_stats.py +206 -0
- package/tests/test_stats_audit_coverage.py +17 -0
- package/tests/test_stats_nonparametric.py +87 -0
- package/tests/test_stats_time_series.py +352 -0
- package/tests/test_stft.py +208 -0
- package/tests/test_streaming_analytics.py +128 -0
- package/tests/test_svd.py +170 -0
- package/tests/test_symplectic.py +200 -0
- package/tests/test_tool_adapters.py +197 -0
- package/tests/test_tools_registry.py +132 -0
- package/tests/test_uncertainty.py +171 -0
- package/tests/test_units.py +139 -0
- package/tests/test_validation.py +100 -0
- package/tests/test_validation_adequacy.py +129 -0
- package/tests/test_validation_advanced.py +110 -0
- package/tests/test_wavelet.py +170 -0
- package/tests/test_wavelets_v2.py +119 -0
- package/tests/test_workflow.py +173 -0
- package/tests/test_workflow_gates.py +144 -0
- package/tests/test_workflow_orchestrator.py +516 -0
- package/tests/test_workflow_orchestrator_blocked_review.py +95 -0
- package/tests/test_workflow_selection.py +312 -0
- package/tests/test_workflow_selection_coverage.py +114 -0
- package/tests/test_workflow_tooling.py +190 -0
|
@@ -0,0 +1,425 @@
|
|
|
1
|
+
"""Minimization algorithms for single and multi-variable functions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Generic, TypedDict, TypeVar, cast, overload
|
|
9
|
+
|
|
10
|
+
from cds.core._numeric import (
|
|
11
|
+
ADAM_DEFAULT_BETAS,
|
|
12
|
+
ADAM_DEFAULT_EPS,
|
|
13
|
+
ADAM_DEFAULT_LR,
|
|
14
|
+
DEFAULT_FD_STEP,
|
|
15
|
+
DEFAULT_TOLERANCE,
|
|
16
|
+
GD_DEFAULT_LR,
|
|
17
|
+
NEAR_ZERO,
|
|
18
|
+
NEWTON_DERIVATIVE_STEP,
|
|
19
|
+
NEWTON_TOLERANCE,
|
|
20
|
+
)
|
|
21
|
+
from cds.math_utils.calculus import derivative as _central_difference
|
|
22
|
+
|
|
23
|
+
# Type parameter for the minimizer payload: a single scalar (``float``) or a
|
|
24
|
+
# vector of scalars (``list[float]``). Constraining ``T`` to these two keeps
|
|
25
|
+
# :class:`OptResult` honest about what the minimizers actually return and lets
|
|
26
|
+
# callers read ``OptResult[float].x`` as a ``float`` without narrowing the union.
|
|
27
|
+
_T = TypeVar("_T", float, list[float])
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
# Adam optimizer state shape: {"m": float|[float], "v": float|[float], "t": int}.
|
|
31
|
+
# The scalar and vector variants are tracked separately so callers that resume a
|
|
32
|
+
# scalar run get a scalar back, and vice versa.
|
|
33
|
+
#
|
|
34
|
+
# Deliberately *not* generic: ``TypedDict`` + ``Generic`` inheritance raises
|
|
35
|
+
# ``TypeError: metaclass conflict`` on Python 3.10 (fixed upstream only in
|
|
36
|
+
# 3.11+, see CPython issue #89026), and CDS supports ``>=3.10``. The
|
|
37
|
+
# ``m``/``v`` union is narrowed inside :func:`adam` via ``cast`` instead.
|
|
38
|
+
class AdamState(TypedDict, total=False):
|
|
39
|
+
"""State checkpoint for resuming an Adam run.
|
|
40
|
+
|
|
41
|
+
``m`` / ``v`` are floats for scalar optimization and lists for vector
|
|
42
|
+
optimization; ``t`` is the last completed iteration (0-based).
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
m: float | list[float]
|
|
46
|
+
v: float | list[float]
|
|
47
|
+
t: int
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass
|
|
51
|
+
class OptResult(Generic[_T]):
|
|
52
|
+
"""Result of an optimization run.
|
|
53
|
+
|
|
54
|
+
Parameterized over the ``x`` payload so the scalar and vector minimizers
|
|
55
|
+
each advertise the concrete type they return: :func:`newton_method` and
|
|
56
|
+
:func:`line_search` always return :class:`OptResult`\\ ``[float]``, while
|
|
57
|
+
:func:`gradient_descent` and :func:`adam` return ``OptResult[float]`` or
|
|
58
|
+
``OptResult[list[float]]`` depending on whether ``x0`` was a scalar or a
|
|
59
|
+
list (see their overloads).
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
x: _T
|
|
63
|
+
value: float
|
|
64
|
+
iterations: int
|
|
65
|
+
converged: bool
|
|
66
|
+
state: AdamState | None = None
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@overload
|
|
70
|
+
def _compute_gradient(f: Callable[..., float], x: float, h_base: float = DEFAULT_FD_STEP) -> float:
|
|
71
|
+
"""Scalar overload: central-difference derivative at a single point."""
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@overload
|
|
75
|
+
def _compute_gradient(
|
|
76
|
+
f: Callable[..., float], x: list[float], h_base: float = DEFAULT_FD_STEP
|
|
77
|
+
) -> list[float]:
|
|
78
|
+
"""Vector overload: coordinate-wise gradient via finite differences."""
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _compute_gradient(
|
|
82
|
+
f: Callable[..., float], x: float | list[float], h_base: float = DEFAULT_FD_STEP
|
|
83
|
+
) -> float | list[float]:
|
|
84
|
+
"""Compute numerical gradient with adaptive step size for precision.
|
|
85
|
+
|
|
86
|
+
The scalar branch delegates to :func:`cds.math_utils.calculus.derivative`
|
|
87
|
+
so the central-difference formula ``(f(x+h) - f(x-h)) / (2h)`` with an
|
|
88
|
+
``x``-scaled step lives in exactly one place. The vector branch is kept
|
|
89
|
+
here because it uses the ``f(list)`` calling convention (positional index
|
|
90
|
+
access), whereas :func:`cds.math_utils.calculus.gradient` expects
|
|
91
|
+
``f(*coords)`` — they are genuinely different APIs, not duplicates.
|
|
92
|
+
"""
|
|
93
|
+
if isinstance(x, (int, float)):
|
|
94
|
+
return _central_difference(f, x, h_base)
|
|
95
|
+
|
|
96
|
+
grad = [0.0] * len(x)
|
|
97
|
+
for i in range(len(x)):
|
|
98
|
+
h = h_base * max(1.0, abs(x[i]))
|
|
99
|
+
x_plus = x[:]
|
|
100
|
+
x_plus[i] += h
|
|
101
|
+
x_minus = x[:]
|
|
102
|
+
x_minus[i] -= h
|
|
103
|
+
grad[i] = float((f(x_plus) - f(x_minus)) / (2 * h))
|
|
104
|
+
return grad
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@overload
|
|
108
|
+
def _update_x(x: float, grad: float, step: float) -> float:
|
|
109
|
+
"""Scalar overload: return the next iterate ``x - step * grad``."""
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
@overload
|
|
113
|
+
def _update_x(x: list[float], grad: list[float], step: float) -> list[float]:
|
|
114
|
+
"""Vector overload: element-wise gradient step applied to each coordinate."""
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _update_x(
|
|
118
|
+
x: float | list[float], grad: float | list[float], step: float
|
|
119
|
+
) -> float | list[float]:
|
|
120
|
+
"""Apply gradient update step for scalar or vector inputs."""
|
|
121
|
+
if isinstance(x, (int, float)):
|
|
122
|
+
# grad is the scalar branch here (see _compute_gradient return type)
|
|
123
|
+
return x - step * (grad if isinstance(grad, float) else grad[0])
|
|
124
|
+
|
|
125
|
+
grad_list: list[float] = grad if isinstance(grad, list) else [grad]
|
|
126
|
+
return [xi - step * gi for xi, gi in zip(x, grad_list)]
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _magnitude(vec: float | list[float]) -> float:
|
|
130
|
+
"""Compute magnitude of a scalar or vector."""
|
|
131
|
+
if isinstance(vec, (int, float)):
|
|
132
|
+
return abs(vec)
|
|
133
|
+
return math.sqrt(sum(vi * vi for vi in vec))
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@overload
|
|
137
|
+
def gradient_descent(
|
|
138
|
+
f: Callable[..., float],
|
|
139
|
+
x0: float,
|
|
140
|
+
lr: float = GD_DEFAULT_LR,
|
|
141
|
+
tol: float = DEFAULT_TOLERANCE,
|
|
142
|
+
max_iter: int = 10000,
|
|
143
|
+
h: float = DEFAULT_FD_STEP,
|
|
144
|
+
) -> OptResult[float]:
|
|
145
|
+
"""Scalar overload: minimize a 1-D function from a scalar start."""
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
@overload
|
|
149
|
+
def gradient_descent(
|
|
150
|
+
f: Callable[..., float],
|
|
151
|
+
x0: list[float],
|
|
152
|
+
lr: float = GD_DEFAULT_LR,
|
|
153
|
+
tol: float = DEFAULT_TOLERANCE,
|
|
154
|
+
max_iter: int = 10000,
|
|
155
|
+
h: float = DEFAULT_FD_STEP,
|
|
156
|
+
) -> OptResult[list[float]]:
|
|
157
|
+
"""Vector overload: minimize a multivariate function from a vector start."""
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def gradient_descent(
|
|
161
|
+
f: Callable[..., float],
|
|
162
|
+
x0: float | list[float],
|
|
163
|
+
lr: float = GD_DEFAULT_LR,
|
|
164
|
+
tol: float = DEFAULT_TOLERANCE,
|
|
165
|
+
max_iter: int = 10000,
|
|
166
|
+
h: float = DEFAULT_FD_STEP,
|
|
167
|
+
) -> OptResult[float] | OptResult[list[float]]:
|
|
168
|
+
"""Minimize a scalar or vector function using gradient descent.
|
|
169
|
+
|
|
170
|
+
Args:
|
|
171
|
+
f: objective function
|
|
172
|
+
x0: starting point (scalar or list of floats)
|
|
173
|
+
lr: learning rate
|
|
174
|
+
tol: convergence tolerance on gradient magnitude
|
|
175
|
+
max_iter: iteration limit
|
|
176
|
+
h: step size for numerical gradient
|
|
177
|
+
"""
|
|
178
|
+
if isinstance(x0, (int, float)):
|
|
179
|
+
# Scalar branch — typed so OptResult[float] is returned without a cast.
|
|
180
|
+
x: float = x0
|
|
181
|
+
for i in range(max_iter):
|
|
182
|
+
grad = _compute_gradient(f, x, h)
|
|
183
|
+
if _magnitude(grad) < tol:
|
|
184
|
+
return OptResult(x=x, value=f(x), iterations=i, converged=True)
|
|
185
|
+
x = _update_x(x, grad, lr)
|
|
186
|
+
return OptResult(x=x, value=f(x), iterations=max_iter, converged=False)
|
|
187
|
+
|
|
188
|
+
# Vector branch — typed so OptResult[list[float]] is returned without a cast.
|
|
189
|
+
# ``grad_vec`` (not ``grad``) so mypy keeps the scalar/vector types separate:
|
|
190
|
+
# the scalar branch above binds the name ``grad`` to ``float``, and a single
|
|
191
|
+
# function scope can't hold both ``float`` and ``list[float]`` for one name.
|
|
192
|
+
x_vec: list[float] = list(x0)
|
|
193
|
+
for i in range(max_iter):
|
|
194
|
+
grad_vec = _compute_gradient(f, x_vec, h)
|
|
195
|
+
if _magnitude(grad_vec) < tol:
|
|
196
|
+
return OptResult(x=x_vec, value=f(x_vec), iterations=i, converged=True)
|
|
197
|
+
x_vec = _update_x(x_vec, grad_vec, lr)
|
|
198
|
+
return OptResult(x=x_vec, value=f(x_vec), iterations=max_iter, converged=False)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def newton_method(
|
|
202
|
+
f: Callable[[float], float],
|
|
203
|
+
x0: float,
|
|
204
|
+
tol: float = NEWTON_TOLERANCE,
|
|
205
|
+
max_iter: int = 1000,
|
|
206
|
+
h_base: float = NEWTON_DERIVATIVE_STEP,
|
|
207
|
+
) -> OptResult[float]:
|
|
208
|
+
"""Find a root of f using Newton-Raphson method with adaptive step size.
|
|
209
|
+
|
|
210
|
+
Args:
|
|
211
|
+
f: function whose root to find
|
|
212
|
+
x0: starting point
|
|
213
|
+
tol: convergence tolerance
|
|
214
|
+
max_iter: iteration limit
|
|
215
|
+
h_base: base step for numerical derivative
|
|
216
|
+
"""
|
|
217
|
+
x = float(x0)
|
|
218
|
+
for i in range(max_iter):
|
|
219
|
+
fx = f(x)
|
|
220
|
+
if abs(fx) < tol:
|
|
221
|
+
return OptResult(x=x, value=fx, iterations=i, converged=True)
|
|
222
|
+
|
|
223
|
+
# Newton's derivative comes from the same central-difference kernel as
|
|
224
|
+
# the gradient methods (``h_base`` defaults to NEWTON_DERIVATIVE_STEP,
|
|
225
|
+
# finer than the gradient DEFAULT_FD_STEP).
|
|
226
|
+
dfx = _compute_gradient(f, x, h_base)
|
|
227
|
+
|
|
228
|
+
if abs(dfx) < NEAR_ZERO:
|
|
229
|
+
break
|
|
230
|
+
x -= fx / dfx
|
|
231
|
+
return OptResult(
|
|
232
|
+
x=x,
|
|
233
|
+
value=f(x),
|
|
234
|
+
iterations=max_iter,
|
|
235
|
+
converged=False,
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
@overload
|
|
240
|
+
def adam(
|
|
241
|
+
f: Callable[..., float],
|
|
242
|
+
x0: float,
|
|
243
|
+
lr: float = ADAM_DEFAULT_LR,
|
|
244
|
+
beta1: float = ADAM_DEFAULT_BETAS[0],
|
|
245
|
+
beta2: float = ADAM_DEFAULT_BETAS[1],
|
|
246
|
+
eps: float = ADAM_DEFAULT_EPS,
|
|
247
|
+
tol: float = DEFAULT_TOLERANCE,
|
|
248
|
+
max_iter: int = 10000,
|
|
249
|
+
h: float = DEFAULT_FD_STEP,
|
|
250
|
+
state: AdamState | None = None,
|
|
251
|
+
grad_f: Callable[..., float | list[float]] | None = None,
|
|
252
|
+
) -> OptResult[float]:
|
|
253
|
+
"""Scalar overload: adapt the learning rate per-iteration for a scalar x0."""
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
@overload
|
|
257
|
+
def adam(
|
|
258
|
+
f: Callable[..., float],
|
|
259
|
+
x0: list[float],
|
|
260
|
+
lr: float = ADAM_DEFAULT_LR,
|
|
261
|
+
beta1: float = ADAM_DEFAULT_BETAS[0],
|
|
262
|
+
beta2: float = ADAM_DEFAULT_BETAS[1],
|
|
263
|
+
eps: float = ADAM_DEFAULT_EPS,
|
|
264
|
+
tol: float = DEFAULT_TOLERANCE,
|
|
265
|
+
max_iter: int = 10000,
|
|
266
|
+
h: float = DEFAULT_FD_STEP,
|
|
267
|
+
state: AdamState | None = None,
|
|
268
|
+
grad_f: Callable[..., float | list[float]] | None = None,
|
|
269
|
+
) -> OptResult[list[float]]:
|
|
270
|
+
"""Vector overload: coordinate-wise adaptive moments for a vector x0."""
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def adam(
|
|
274
|
+
f: Callable[..., float],
|
|
275
|
+
x0: float | list[float],
|
|
276
|
+
lr: float = ADAM_DEFAULT_LR,
|
|
277
|
+
beta1: float = ADAM_DEFAULT_BETAS[0],
|
|
278
|
+
beta2: float = ADAM_DEFAULT_BETAS[1],
|
|
279
|
+
eps: float = ADAM_DEFAULT_EPS,
|
|
280
|
+
tol: float = DEFAULT_TOLERANCE,
|
|
281
|
+
max_iter: int = 10000,
|
|
282
|
+
h: float = DEFAULT_FD_STEP,
|
|
283
|
+
state: AdamState | None = None,
|
|
284
|
+
grad_f: Callable[..., float | list[float]] | None = None,
|
|
285
|
+
) -> OptResult[float] | OptResult[list[float]]:
|
|
286
|
+
"""Minimize using Adam optimizer (adaptive learning rate) for scalars or vectors.
|
|
287
|
+
|
|
288
|
+
Args:
|
|
289
|
+
f: objective function
|
|
290
|
+
x0: starting point
|
|
291
|
+
lr: learning rate
|
|
292
|
+
beta1: first moment decay
|
|
293
|
+
beta2: second moment decay
|
|
294
|
+
eps: numerical stability constant
|
|
295
|
+
tol: convergence tolerance
|
|
296
|
+
max_iter: iteration limit
|
|
297
|
+
h: step for numerical gradient
|
|
298
|
+
state: optional dictionary to resume optimization (contains m, v, t)
|
|
299
|
+
grad_f: optional gradient function. If None, numerical gradient is used.
|
|
300
|
+
"""
|
|
301
|
+
if isinstance(x0, (int, float)):
|
|
302
|
+
x_scalar: float = float(x0)
|
|
303
|
+
|
|
304
|
+
if state is None:
|
|
305
|
+
m_s = 0.0
|
|
306
|
+
v_s = 0.0
|
|
307
|
+
t_start = 1
|
|
308
|
+
else:
|
|
309
|
+
m_s = float(cast(float, state["m"]))
|
|
310
|
+
v_s = float(cast(float, state["v"]))
|
|
311
|
+
t_start = int(state["t"]) + 1
|
|
312
|
+
|
|
313
|
+
last_t = t_start - 1
|
|
314
|
+
for i in range(t_start, t_start + max_iter):
|
|
315
|
+
last_t = i
|
|
316
|
+
if grad_f:
|
|
317
|
+
grad_s: float = float(cast(float, grad_f(x_scalar)))
|
|
318
|
+
else:
|
|
319
|
+
grad_s = _compute_gradient(f, x_scalar, h)
|
|
320
|
+
|
|
321
|
+
if abs(grad_s) < tol:
|
|
322
|
+
return OptResult(
|
|
323
|
+
x=x_scalar,
|
|
324
|
+
value=f(x_scalar),
|
|
325
|
+
iterations=i - t_start + 1,
|
|
326
|
+
converged=True,
|
|
327
|
+
state={"m": m_s, "v": v_s, "t": i},
|
|
328
|
+
)
|
|
329
|
+
m_s = beta1 * m_s + (1 - beta1) * grad_s
|
|
330
|
+
v_s = beta2 * v_s + (1 - beta2) * grad_s**2
|
|
331
|
+
m_hat = m_s / (1 - beta1**i)
|
|
332
|
+
v_hat = v_s / (1 - beta2**i)
|
|
333
|
+
x_scalar -= lr * m_hat / (math.sqrt(v_hat) + eps)
|
|
334
|
+
|
|
335
|
+
return OptResult(
|
|
336
|
+
x=x_scalar,
|
|
337
|
+
value=f(x_scalar),
|
|
338
|
+
iterations=max_iter,
|
|
339
|
+
converged=False,
|
|
340
|
+
state={"m": m_s, "v": v_s, "t": last_t},
|
|
341
|
+
)
|
|
342
|
+
else:
|
|
343
|
+
x_list: list[float] = list(x0)
|
|
344
|
+
|
|
345
|
+
if state is None:
|
|
346
|
+
m_l = [0.0] * len(x_list)
|
|
347
|
+
v_l = [0.0] * len(x_list)
|
|
348
|
+
t_start = 1
|
|
349
|
+
else:
|
|
350
|
+
m_l = list(cast(list[float], state["m"]))
|
|
351
|
+
v_l = list(cast(list[float], state["v"]))
|
|
352
|
+
t_start = int(state["t"]) + 1
|
|
353
|
+
|
|
354
|
+
last_t = t_start - 1
|
|
355
|
+
for i in range(t_start, t_start + max_iter):
|
|
356
|
+
last_t = i
|
|
357
|
+
if grad_f:
|
|
358
|
+
grad_l: list[float] = list(cast(list[float], grad_f(x_list)))
|
|
359
|
+
else:
|
|
360
|
+
grad_l = _compute_gradient(f, x_list, h)
|
|
361
|
+
|
|
362
|
+
if _magnitude(grad_l) < tol:
|
|
363
|
+
return OptResult(
|
|
364
|
+
x=x_list,
|
|
365
|
+
value=f(x_list),
|
|
366
|
+
iterations=i - t_start + 1,
|
|
367
|
+
converged=True,
|
|
368
|
+
state={"m": m_l, "v": v_l, "t": i},
|
|
369
|
+
)
|
|
370
|
+
|
|
371
|
+
for j in range(len(x_list)):
|
|
372
|
+
m_l[j] = beta1 * m_l[j] + (1 - beta1) * grad_l[j]
|
|
373
|
+
v_l[j] = beta2 * v_l[j] + (1 - beta2) * grad_l[j] ** 2
|
|
374
|
+
m_hat = m_l[j] / (1 - beta1**i)
|
|
375
|
+
v_hat = v_l[j] / (1 - beta2**i)
|
|
376
|
+
x_list[j] -= lr * m_hat / (math.sqrt(v_hat) + eps)
|
|
377
|
+
|
|
378
|
+
return OptResult(
|
|
379
|
+
x=x_list,
|
|
380
|
+
value=f(x_list),
|
|
381
|
+
iterations=max_iter,
|
|
382
|
+
converged=False,
|
|
383
|
+
state={"m": m_l, "v": v_l, "t": last_t},
|
|
384
|
+
)
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def line_search(
|
|
388
|
+
f: Callable[[float], float],
|
|
389
|
+
a: float,
|
|
390
|
+
b: float,
|
|
391
|
+
tol: float = DEFAULT_TOLERANCE,
|
|
392
|
+
max_iter: int = 100,
|
|
393
|
+
) -> OptResult[float]:
|
|
394
|
+
"""Golden section search for minimum in [a, b].
|
|
395
|
+
|
|
396
|
+
Args:
|
|
397
|
+
f: unimodal function to minimize
|
|
398
|
+
a: left bound
|
|
399
|
+
b: right bound
|
|
400
|
+
tol: convergence tolerance on interval width
|
|
401
|
+
max_iter: iteration limit
|
|
402
|
+
"""
|
|
403
|
+
phi = (math.sqrt(5) - 1) / 2
|
|
404
|
+
for i in range(max_iter):
|
|
405
|
+
if abs(b - a) < tol:
|
|
406
|
+
mid = (a + b) / 2
|
|
407
|
+
return OptResult(
|
|
408
|
+
x=mid,
|
|
409
|
+
value=f(mid),
|
|
410
|
+
iterations=i,
|
|
411
|
+
converged=True,
|
|
412
|
+
)
|
|
413
|
+
x1 = b - phi * (b - a)
|
|
414
|
+
x2 = a + phi * (b - a)
|
|
415
|
+
if f(x1) < f(x2):
|
|
416
|
+
b = x2
|
|
417
|
+
else:
|
|
418
|
+
a = x1
|
|
419
|
+
mid = (a + b) / 2
|
|
420
|
+
return OptResult(
|
|
421
|
+
x=mid,
|
|
422
|
+
value=f(mid),
|
|
423
|
+
iterations=max_iter,
|
|
424
|
+
converged=False,
|
|
425
|
+
)
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
"""Finite-difference PDE solvers on uniform 1-D grids — zero dependencies.
|
|
2
|
+
|
|
3
|
+
Explicit time marching for the two classic model equations of mathematical
|
|
4
|
+
physics, discretised on a uniform grid of ``nx`` points spanning
|
|
5
|
+
``[0, length]`` with spacing ``dx = length / (nx - 1)``:
|
|
6
|
+
|
|
7
|
+
Heat equation ``u_t = alpha * u_xx`` (parabolic)
|
|
8
|
+
Forward-Time Central-Space (FTCS). Every interior point is blended with
|
|
9
|
+
its two neighbours each step::
|
|
10
|
+
|
|
11
|
+
u[i] <- u[i] + r * (u[i-1] - 2*u[i] + u[i+1]), r = alpha*dt/dx**2
|
|
12
|
+
|
|
13
|
+
FTCS is stable if and only if ``r <= 0.5`` (von Neumann analysis). When
|
|
14
|
+
``dt`` is omitted the solver picks ``dt = 0.9 * dx**2 / (2 * alpha)``,
|
|
15
|
+
i.e. the stability limit shrunk by a 10 % safety margin giving
|
|
16
|
+
``r = 0.45``; a caller-supplied ``dt`` with ``r > 0.5`` is rejected.
|
|
17
|
+
|
|
18
|
+
Wave equation ``u_tt = c**2 * u_xx`` (hyperbolic)
|
|
19
|
+
Explicit central differences in space and time (three-level leapfrog)::
|
|
20
|
+
|
|
21
|
+
u_new[i] <- 2*u[i] - u_old[i] + C**2 * (u[i-1] - 2*u[i] + u[i+1])
|
|
22
|
+
|
|
23
|
+
with Courant number ``C = c*dt/dx``, subject to the CFL condition
|
|
24
|
+
``C <= 1``. The first step is seeded from the initial velocity ``v0``
|
|
25
|
+
with the matching second-order Taylor expansion
|
|
26
|
+
``u(dt) = u0 + dt*v0 + dt**2/2 * c**2 * u_xx``. When ``dt`` is omitted
|
|
27
|
+
the solver picks ``dt = 0.9 * dx / c`` (``C = 0.9``); a caller-supplied
|
|
28
|
+
``dt`` with ``C > 1`` is rejected.
|
|
29
|
+
|
|
30
|
+
Both solvers march a whole number of uniform steps,
|
|
31
|
+
``n_steps = ceil(t_final / dt)``, so the simulated horizon ``n_steps * dt``
|
|
32
|
+
matches ``t_final`` up to one step. Boundary handling: ``"dirichlet"`` pins
|
|
33
|
+
the two end values at their initial levels; ``"neumann"`` mirrors the
|
|
34
|
+
adjacent interior point onto each end after every step (zero-flux, insulated
|
|
35
|
+
ends). All failures surface as lowercase :class:`ValueError`.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
from __future__ import annotations
|
|
39
|
+
|
|
40
|
+
import math
|
|
41
|
+
from dataclasses import dataclass
|
|
42
|
+
|
|
43
|
+
__all__ = ["HeatResult", "WaveResult", "solve_heat", "solve_wave"]
|
|
44
|
+
|
|
45
|
+
_ALLOWED_BOUNDARIES = ("dirichlet", "neumann")
|
|
46
|
+
_HEAT_SAFETY = 0.9
|
|
47
|
+
_WAVE_SAFETY = 0.9
|
|
48
|
+
_MAX_HEAT_COURANT = 0.5
|
|
49
|
+
_MAX_WAVE_COURANT = 1.0
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass
|
|
53
|
+
class HeatResult:
|
|
54
|
+
"""Outcome of one heat-equation integration.
|
|
55
|
+
|
|
56
|
+
Attributes:
|
|
57
|
+
u_final: temperature profile after the last step, one entry per
|
|
58
|
+
grid point, ordered left to right.
|
|
59
|
+
dt: time step actually used (auto-chosen or caller-supplied).
|
|
60
|
+
n_steps: number of uniform FTCS steps taken; the simulated horizon
|
|
61
|
+
is ``n_steps * dt``.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
u_final: list[float]
|
|
65
|
+
dt: float
|
|
66
|
+
n_steps: int
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@dataclass
|
|
70
|
+
class WaveResult:
|
|
71
|
+
"""Outcome of one wave-equation integration.
|
|
72
|
+
|
|
73
|
+
Attributes:
|
|
74
|
+
u_final: displacement profile after the last step, one entry per
|
|
75
|
+
grid point, ordered left to right.
|
|
76
|
+
dt: time step actually used (auto-chosen or caller-supplied).
|
|
77
|
+
n_steps: number of uniform leapfrog steps taken; the simulated
|
|
78
|
+
horizon is ``n_steps * dt``.
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
u_final: list[float]
|
|
82
|
+
dt: float
|
|
83
|
+
n_steps: int
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _check_grid(u0: list[float], nx: int, length: float, t_final: float) -> None:
|
|
87
|
+
"""Validate the arguments shared by both solvers.
|
|
88
|
+
|
|
89
|
+
Args:
|
|
90
|
+
u0: initial profile candidate.
|
|
91
|
+
nx: declared grid size.
|
|
92
|
+
length: domain length.
|
|
93
|
+
t_final: requested simulation horizon.
|
|
94
|
+
|
|
95
|
+
Raises:
|
|
96
|
+
ValueError: if ``u0`` does not hold exactly ``nx`` points, ``nx``
|
|
97
|
+
is below 3, or ``length`` / ``t_final`` is not strictly
|
|
98
|
+
positive.
|
|
99
|
+
"""
|
|
100
|
+
if len(u0) != nx:
|
|
101
|
+
raise ValueError(f"u0 must have exactly {nx} points, got {len(u0)}")
|
|
102
|
+
if nx < 3:
|
|
103
|
+
raise ValueError("nx must be at least 3")
|
|
104
|
+
if length <= 0:
|
|
105
|
+
raise ValueError("length must be positive")
|
|
106
|
+
if t_final <= 0:
|
|
107
|
+
raise ValueError("t_final must be positive")
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _pick_dt(dt: float | None, auto_dt: float) -> float:
|
|
111
|
+
"""Resolve the time step, rejecting non-positive caller-supplied values.
|
|
112
|
+
|
|
113
|
+
Args:
|
|
114
|
+
dt: caller-supplied step, or ``None`` to take ``auto_dt`` — the
|
|
115
|
+
pre-computed automatic choice, which already carries the scheme
|
|
116
|
+
safety margin and therefore always satisfies stability.
|
|
117
|
+
auto_dt: automatic step used when ``dt`` is ``None``.
|
|
118
|
+
|
|
119
|
+
Returns:
|
|
120
|
+
The time step to march with.
|
|
121
|
+
|
|
122
|
+
Raises:
|
|
123
|
+
ValueError: if a caller-supplied ``dt`` is not strictly positive.
|
|
124
|
+
"""
|
|
125
|
+
if dt is None:
|
|
126
|
+
return auto_dt
|
|
127
|
+
if dt <= 0:
|
|
128
|
+
raise ValueError("dt must be positive")
|
|
129
|
+
return dt
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def solve_heat(
|
|
133
|
+
u0: list[float],
|
|
134
|
+
alpha: float,
|
|
135
|
+
length: float,
|
|
136
|
+
t_final: float,
|
|
137
|
+
nx: int,
|
|
138
|
+
*,
|
|
139
|
+
boundary: str = "dirichlet",
|
|
140
|
+
dt: float | None = None,
|
|
141
|
+
) -> HeatResult:
|
|
142
|
+
"""Integrate the 1-D heat equation with explicit FTCS time stepping.
|
|
143
|
+
|
|
144
|
+
Marches ``n_steps = ceil(t_final / dt)`` uniform applications of the
|
|
145
|
+
three-point stencil ``u += r * (left - 2*u + right)`` with
|
|
146
|
+
``r = alpha*dt/dx**2``. When ``dt`` is omitted it defaults to
|
|
147
|
+
``0.9 * dx**2 / (2 * alpha)`` — the FTCS stability limit
|
|
148
|
+
``alpha*dt/dx**2 <= 0.5`` shrunk by a 10 % safety margin (``r = 0.45``).
|
|
149
|
+
|
|
150
|
+
Args:
|
|
151
|
+
u0: initial temperatures, one per grid point, left to right.
|
|
152
|
+
alpha: thermal diffusivity, must be positive.
|
|
153
|
+
length: domain length; grid spacing is ``length / (nx - 1)``.
|
|
154
|
+
t_final: target simulation horizon.
|
|
155
|
+
nx: number of grid points, at least 3.
|
|
156
|
+
boundary: ``"dirichlet"`` pins the end values at ``u0[0]`` /
|
|
157
|
+
``u0[-1]`` for all time; ``"neumann"`` mirrors the neighbouring
|
|
158
|
+
interior value onto each end (zero flux, insulated ends).
|
|
159
|
+
dt: optional forced time step. Must satisfy the stability condition
|
|
160
|
+
``alpha*dt/dx**2 <= 0.5`` or the call is rejected.
|
|
161
|
+
|
|
162
|
+
Returns:
|
|
163
|
+
A :class:`HeatResult` holding the final profile, the time step used
|
|
164
|
+
and the number of steps taken.
|
|
165
|
+
|
|
166
|
+
Raises:
|
|
167
|
+
ValueError: if ``len(u0) != nx``, ``nx < 3``, ``alpha <= 0``,
|
|
168
|
+
``length <= 0``, ``t_final <= 0``, ``boundary`` is neither
|
|
169
|
+
``"dirichlet"`` nor ``"neumann"``, ``dt`` is not strictly
|
|
170
|
+
positive, or ``dt`` breaks the stability condition.
|
|
171
|
+
"""
|
|
172
|
+
_check_grid(u0, nx, length, t_final)
|
|
173
|
+
if boundary not in _ALLOWED_BOUNDARIES:
|
|
174
|
+
raise ValueError(f"boundary must be 'dirichlet' or 'neumann', got {boundary!r}")
|
|
175
|
+
if alpha <= 0:
|
|
176
|
+
raise ValueError("alpha must be positive")
|
|
177
|
+
dx = length / (nx - 1)
|
|
178
|
+
dt_step = _pick_dt(dt, _HEAT_SAFETY * dx * dx / (2.0 * alpha))
|
|
179
|
+
r = alpha * dt_step / (dx * dx)
|
|
180
|
+
if r > _MAX_HEAT_COURANT:
|
|
181
|
+
raise ValueError(
|
|
182
|
+
f"dt={dt} violates heat stability: alpha*dt/dx**2 = {r:.4g} exceeds {_MAX_HEAT_COURANT}"
|
|
183
|
+
)
|
|
184
|
+
n_steps = math.ceil(t_final / dt_step)
|
|
185
|
+
u = [float(value) for value in u0]
|
|
186
|
+
for _ in range(n_steps):
|
|
187
|
+
new_u = list(u)
|
|
188
|
+
for i in range(1, nx - 1):
|
|
189
|
+
new_u[i] = u[i] + r * (u[i - 1] - 2.0 * u[i] + u[i + 1])
|
|
190
|
+
if boundary == "neumann":
|
|
191
|
+
new_u[0] = new_u[1]
|
|
192
|
+
new_u[-1] = new_u[-2]
|
|
193
|
+
u = new_u
|
|
194
|
+
return HeatResult(u_final=u, dt=dt_step, n_steps=n_steps)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def solve_wave(
|
|
198
|
+
u0: list[float],
|
|
199
|
+
v0: list[float],
|
|
200
|
+
c: float,
|
|
201
|
+
length: float,
|
|
202
|
+
t_final: float,
|
|
203
|
+
nx: int,
|
|
204
|
+
*,
|
|
205
|
+
dt: float | None = None,
|
|
206
|
+
) -> WaveResult:
|
|
207
|
+
"""Integrate the 1-D wave equation with explicit central differences.
|
|
208
|
+
|
|
209
|
+
Uses the three-level leapfrog stencil
|
|
210
|
+
``u_new = 2*u - u_old + C**2 * (left - 2*u + right)`` with
|
|
211
|
+
``C = c*dt/dx``, seeded by the second-order Taylor step
|
|
212
|
+
``u(dt) = u0 + dt*v0 + dt**2/2 * c**2 * u_xx``. When ``dt`` is omitted
|
|
213
|
+
it defaults to ``0.9 * dx / c`` — the CFL limit ``c*dt/dx <= 1`` shrunk
|
|
214
|
+
by a 10 % safety margin. Ends are Dirichlet-pinned at ``u0[0]`` /
|
|
215
|
+
``u0[-1]``.
|
|
216
|
+
|
|
217
|
+
Args:
|
|
218
|
+
u0: initial displacements, one per grid point, left to right.
|
|
219
|
+
v0: initial velocities aligned with ``u0``.
|
|
220
|
+
c: wave speed, must be positive.
|
|
221
|
+
length: domain length; grid spacing is ``length / (nx - 1)``.
|
|
222
|
+
t_final: target simulation horizon.
|
|
223
|
+
nx: number of grid points, at least 3.
|
|
224
|
+
dt: optional forced time step. Must satisfy the CFL condition
|
|
225
|
+
``c*dt/dx <= 1`` or the call is rejected.
|
|
226
|
+
|
|
227
|
+
Returns:
|
|
228
|
+
A :class:`WaveResult` holding the final displacement profile, the
|
|
229
|
+
time step used and the number of steps taken.
|
|
230
|
+
|
|
231
|
+
Raises:
|
|
232
|
+
ValueError: if ``len(u0) != nx`` or ``len(v0) != nx``, ``nx < 3``,
|
|
233
|
+
``c <= 0``, ``length <= 0``, ``t_final <= 0``, ``dt`` is not
|
|
234
|
+
strictly positive, or ``dt`` breaks the CFL condition.
|
|
235
|
+
"""
|
|
236
|
+
_check_grid(u0, nx, length, t_final)
|
|
237
|
+
if len(v0) != nx:
|
|
238
|
+
raise ValueError(f"v0 must have exactly {nx} points, got {len(v0)}")
|
|
239
|
+
if c <= 0:
|
|
240
|
+
raise ValueError("c must be positive")
|
|
241
|
+
dx = length / (nx - 1)
|
|
242
|
+
dt_step = _pick_dt(dt, _WAVE_SAFETY * dx / c)
|
|
243
|
+
courant = c * dt_step / dx
|
|
244
|
+
if courant > _MAX_WAVE_COURANT:
|
|
245
|
+
raise ValueError(
|
|
246
|
+
f"dt={dt} violates wave CFL: c*dt/dx = {courant:.4g} exceeds {_MAX_WAVE_COURANT}"
|
|
247
|
+
)
|
|
248
|
+
lam = courant * courant
|
|
249
|
+
n_steps = math.ceil(t_final / dt_step)
|
|
250
|
+
u_prev = [float(value) for value in u0]
|
|
251
|
+
vel = [float(value) for value in v0]
|
|
252
|
+
|
|
253
|
+
# First step: Taylor seed built from the initial velocity.
|
|
254
|
+
u_curr = list(u_prev)
|
|
255
|
+
for i in range(1, nx - 1):
|
|
256
|
+
curvature = u_prev[i - 1] - 2.0 * u_prev[i] + u_prev[i + 1]
|
|
257
|
+
u_curr[i] = u_prev[i] + dt_step * vel[i] + 0.5 * lam * curvature
|
|
258
|
+
|
|
259
|
+
# Remaining steps: three-level central difference in time.
|
|
260
|
+
for _ in range(n_steps - 1):
|
|
261
|
+
u_next = list(u_curr)
|
|
262
|
+
for i in range(1, nx - 1):
|
|
263
|
+
curvature = u_curr[i - 1] - 2.0 * u_curr[i] + u_curr[i + 1]
|
|
264
|
+
u_next[i] = 2.0 * u_curr[i] - u_prev[i] + lam * curvature
|
|
265
|
+
u_prev, u_curr = u_curr, u_next
|
|
266
|
+
return WaveResult(u_final=u_curr, dt=dt_step, n_steps=n_steps)
|