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,124 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Demo: end-to-end PCA with preprocessing — scaling, variance analysis,
|
|
3
|
+
2-D projection, reconstruction, and train/test discipline.
|
|
4
|
+
Everything is 100% Pure Python.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import random
|
|
8
|
+
|
|
9
|
+
from cds.data_analysis import plot_bar
|
|
10
|
+
from cds.ml import PCA, PCAResult, StandardScaler, train_test_split
|
|
11
|
+
|
|
12
|
+
SEED = 42
|
|
13
|
+
FEATURE_NAMES = ["sensor_mm", "load_kg", "temp_diff", "noise", "bias_const"]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def make_dataset(n_per_cluster: int = 80) -> tuple[list[list[float]], list[float]]:
|
|
17
|
+
"""Two latent clusters embedded in 5 features with deliberate pitfalls.
|
|
18
|
+
|
|
19
|
+
- sensor_mm is measured in millimeters (huge scale vs the rest)
|
|
20
|
+
- noise is pure random information
|
|
21
|
+
- bias_const is a zero-variance column
|
|
22
|
+
"""
|
|
23
|
+
rng = random.Random(SEED)
|
|
24
|
+
X: list[list[float]] = []
|
|
25
|
+
y: list[float] = []
|
|
26
|
+
for cluster in (0, 1):
|
|
27
|
+
center = -1.0 if cluster == 0 else 1.0
|
|
28
|
+
for _ in range(n_per_cluster):
|
|
29
|
+
latent = center + rng.gauss(0.0, 0.8)
|
|
30
|
+
row = [
|
|
31
|
+
1000.0 * (latent + 0.3 * rng.gauss(0.0, 1.0)),
|
|
32
|
+
1.5 * latent + 0.3 * rng.gauss(0.0, 1.0),
|
|
33
|
+
-latent + 0.3 * rng.gauss(0.0, 1.0),
|
|
34
|
+
rng.gauss(0.0, 1.0),
|
|
35
|
+
7.0,
|
|
36
|
+
]
|
|
37
|
+
X.append(row)
|
|
38
|
+
y.append(float(cluster))
|
|
39
|
+
return X, y
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def ascii_scatter(points: list[list[float]], labels: list[float]) -> str:
|
|
43
|
+
"""Bin 2-D points into a character grid: cluster 0 -> 'A', 1 -> 'B'."""
|
|
44
|
+
width, height = 56, 16
|
|
45
|
+
xs = [p[0] for p in points]
|
|
46
|
+
ys = [p[1] for p in points]
|
|
47
|
+
x_min, x_max = min(xs), max(xs)
|
|
48
|
+
y_min, y_max = min(ys), max(ys)
|
|
49
|
+
x_span = (x_max - x_min) or 1.0
|
|
50
|
+
y_span = (y_max - y_min) or 1.0
|
|
51
|
+
grid = [[" "] * width for _ in range(height)]
|
|
52
|
+
for (px, py), label in zip(points, labels):
|
|
53
|
+
col = int((px - x_min) / x_span * (width - 1))
|
|
54
|
+
row = height - 1 - int((py - y_min) / y_span * (height - 1))
|
|
55
|
+
mark = "A" if label == 0 else "B"
|
|
56
|
+
if grid[row][col] != " ":
|
|
57
|
+
mark = "#"
|
|
58
|
+
grid[row][col] = mark
|
|
59
|
+
return "\n".join("".join(r) for r in grid)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def explained_variance_report(model: PCAResult, prefix: str) -> None:
|
|
63
|
+
ratios = model.explained_variance_ratio_
|
|
64
|
+
bars = {f"PC{i + 1}": round(r, 4) for i, r in enumerate(ratios)}
|
|
65
|
+
print(plot_bar(bars, title=f"{prefix}: explained variance ratio"))
|
|
66
|
+
cumulative = 0.0
|
|
67
|
+
for i, r in enumerate(ratios):
|
|
68
|
+
cumulative += r
|
|
69
|
+
print(f" PC{i + 1}: {r:7.4f} cumulative {cumulative:7.4f}")
|
|
70
|
+
k90 = next(i + 1 for i, _ in enumerate(ratios) if sum(ratios[: i + 1]) >= 0.90)
|
|
71
|
+
print(f" -> {k90} component(s) capture >= 90% of the variance")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def mean_abs_error(original: list[list[float]], reconstructed: list[list[float]]) -> float:
|
|
75
|
+
diffs = [
|
|
76
|
+
abs(original[i][d] - reconstructed[i][d])
|
|
77
|
+
for i in range(len(original))
|
|
78
|
+
for d in range(len(original[i]))
|
|
79
|
+
]
|
|
80
|
+
return sum(diffs) / len(diffs)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def run_demo() -> None:
|
|
84
|
+
X, y = make_dataset()
|
|
85
|
+
n_samples, n_features = len(X), len(X[0])
|
|
86
|
+
print("--- End-to-End PCA + Preprocessing Demo ---")
|
|
87
|
+
print(f"Dataset: {n_samples} samples x {n_features} features, two hidden clusters")
|
|
88
|
+
print(f"Features: {', '.join(FEATURE_NAMES)}")
|
|
89
|
+
|
|
90
|
+
print("\n[1] Why scaling matters — PCA on RAW data")
|
|
91
|
+
raw_model = PCA(n_components=n_features).fit(X)
|
|
92
|
+
explained_variance_report(raw_model, "RAW")
|
|
93
|
+
print(" The millimeter-scale column dominates; cluster structure is invisible.")
|
|
94
|
+
|
|
95
|
+
print("\n[2] StandardScaler -> PCA on SCALED data")
|
|
96
|
+
scaler = StandardScaler().fit(X)
|
|
97
|
+
Xs = scaler.transform(X)
|
|
98
|
+
scaled_model = PCA(n_components=n_features).fit(Xs)
|
|
99
|
+
explained_variance_report(scaled_model, "SCALED")
|
|
100
|
+
print(" Zero-variance 'bias_const' became a flat 0 column and contributes nothing.")
|
|
101
|
+
|
|
102
|
+
print("\n[3] Project onto the top 2 components")
|
|
103
|
+
model2 = PCA(n_components=2).fit(Xs)
|
|
104
|
+
Z = model2.transform(Xs)
|
|
105
|
+
print(ascii_scatter(Z, y))
|
|
106
|
+
print(" A/B = true clusters — PC1 alone separates them.")
|
|
107
|
+
|
|
108
|
+
print("\n[4] Round-trip: 2-D projection -> inverse_transform")
|
|
109
|
+
X_rec = model2.inverse_transform(Z)
|
|
110
|
+
print(f" mean |x - reconstruct(x)| on scaled data: {mean_abs_error(Xs, X_rec):.4f}")
|
|
111
|
+
|
|
112
|
+
print("\n[5] Train/test discipline — fit on train only, then transform test")
|
|
113
|
+
X_train, X_test, _, _ = train_test_split(X, y, test_size=0.25, seed=SEED)
|
|
114
|
+
scaler_t = StandardScaler().fit(X_train)
|
|
115
|
+
pca_t = PCA(n_components=2).fit(scaler_t.transform(X_train))
|
|
116
|
+
Z_test = pca_t.transform(scaler_t.transform(X_test))
|
|
117
|
+
X_test_rec = pca_t.inverse_transform(Z_test)
|
|
118
|
+
test_err = mean_abs_error(scaler_t.transform(X_test), X_test_rec)
|
|
119
|
+
print(f" test samples: {len(X_test)}, reconstruction error: {test_err:.4f}")
|
|
120
|
+
print(" No statistics leak from the test set into the fitted pipeline.")
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
if __name__ == "__main__":
|
|
124
|
+
run_demo()
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""PDE solver demo — heat diffusion of a Gaussian blob and a plucked string."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
|
|
5
|
+
from cds.pde import solve_heat, solve_wave
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def main() -> None:
|
|
9
|
+
# --- Heat equation: Gaussian blob ---
|
|
10
|
+
print("=== Heat equation: Gaussian blob (alpha=0.01) ===")
|
|
11
|
+
nx = 101
|
|
12
|
+
length = 1.0
|
|
13
|
+
alpha = 0.01
|
|
14
|
+
|
|
15
|
+
def blob(x: float) -> float:
|
|
16
|
+
return math.exp(-(((x - 0.5) / 0.08) ** 2))
|
|
17
|
+
|
|
18
|
+
u0 = [blob(length * i / (nx - 1)) for i in range(nx)]
|
|
19
|
+
dx = length / (nx - 1)
|
|
20
|
+
|
|
21
|
+
hot = solve_heat(u0, alpha, length, t_final=0.4, nx=nx, boundary="dirichlet")
|
|
22
|
+
print(f"Dirichlet ends: auto dt={hot.dt:.6f} ({hot.n_steps} steps)")
|
|
23
|
+
print(f" peak temperature: {max(u0):.6f} -> {max(hot.u_final):.6f}")
|
|
24
|
+
|
|
25
|
+
insulated = solve_heat(u0, alpha, length, t_final=0.4, nx=nx, boundary="neumann")
|
|
26
|
+
mass0 = sum(u0) * dx
|
|
27
|
+
mass1 = sum(insulated.u_final) * dx
|
|
28
|
+
drift = abs(mass1 - mass0) / mass0
|
|
29
|
+
print(f"Neumann ends : auto dt={insulated.dt:.6f} ({insulated.n_steps} steps)")
|
|
30
|
+
print(f" total heat mass: {mass0:.6f} -> {mass1:.6f} (relative drift {drift:.2e})")
|
|
31
|
+
|
|
32
|
+
# --- Wave equation: plucked string ---
|
|
33
|
+
print("\n=== Wave equation: plucked string (c=1.0) ===")
|
|
34
|
+
nx_w = 81
|
|
35
|
+
c = 1.0
|
|
36
|
+
xs_w = [length * i / (nx_w - 1) for i in range(nx_w)]
|
|
37
|
+
center = length / 2.0
|
|
38
|
+
pluck = 0.2
|
|
39
|
+
|
|
40
|
+
def triangle(x: float) -> float:
|
|
41
|
+
if x <= center:
|
|
42
|
+
return 2.0 * pluck * x / length
|
|
43
|
+
return 2.0 * pluck * (1.0 - x / length)
|
|
44
|
+
|
|
45
|
+
u0_w = [triangle(x) for x in xs_w]
|
|
46
|
+
v0_w = [0.0] * nx_w
|
|
47
|
+
t_final_w = 0.8
|
|
48
|
+
string = solve_wave(u0_w, v0_w, c, length, t_final=t_final_w, nx=nx_w)
|
|
49
|
+
courant = c * string.dt / (length / (nx_w - 1))
|
|
50
|
+
print(
|
|
51
|
+
f"Auto dt={string.dt:.6f} chosen by CFL safety rule "
|
|
52
|
+
f"(Courant number C = {courant:.3f}, {string.n_steps} steps)"
|
|
53
|
+
)
|
|
54
|
+
peak0 = max(abs(u) for u in u0_w)
|
|
55
|
+
peak1 = max(abs(u) for u in string.u_final)
|
|
56
|
+
print(f"Peak |displacement| at t={t_final_w}: {peak0:.4f} -> {peak1:.4f}")
|
|
57
|
+
print(f"Reflected wave inverted the profile (final min = {min(string.u_final):+.4f})")
|
|
58
|
+
print(
|
|
59
|
+
f"String still pinned at both ends: "
|
|
60
|
+
f"{abs(string.u_final[0]) < 1e-12 and abs(string.u_final[-1]) < 1e-12}"
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
if __name__ == "__main__":
|
|
65
|
+
main()
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Demo: optional ``cds[plot]`` matplotlib helpers.
|
|
3
|
+
|
|
4
|
+
Requires: ``pip install scientific-computing-system[plot]``
|
|
5
|
+
|
|
6
|
+
Saves figures under ``examples/_plot_out/``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import math
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from cds.plot import (
|
|
15
|
+
plot_acf,
|
|
16
|
+
plot_heatmap,
|
|
17
|
+
plot_histogram,
|
|
18
|
+
plot_loss,
|
|
19
|
+
plot_multi_series,
|
|
20
|
+
plot_optimization_path,
|
|
21
|
+
plot_power_spectrum,
|
|
22
|
+
plot_regression,
|
|
23
|
+
plot_scatter,
|
|
24
|
+
plot_seasonal_decompose,
|
|
25
|
+
plot_series,
|
|
26
|
+
plot_waveform,
|
|
27
|
+
save_figure,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def main() -> None:
|
|
32
|
+
out = Path(__file__).resolve().parent / "_plot_out"
|
|
33
|
+
out.mkdir(exist_ok=True)
|
|
34
|
+
|
|
35
|
+
y = [math.sin(2 * math.pi * i / 40) + 0.1 * math.sin(2 * math.pi * i / 7) for i in range(120)]
|
|
36
|
+
save_figure(plot_series(y, title="Noisy sine"), str(out / "series.png"))
|
|
37
|
+
save_figure(plot_histogram(y, bins=24, title="Amplitude histogram"), str(out / "hist.png"))
|
|
38
|
+
save_figure(
|
|
39
|
+
plot_multi_series(
|
|
40
|
+
{
|
|
41
|
+
"raw": y,
|
|
42
|
+
"abs": [abs(v) for v in y],
|
|
43
|
+
},
|
|
44
|
+
title="Multi-series",
|
|
45
|
+
),
|
|
46
|
+
str(out / "multi.png"),
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
n, fs = 128, 128.0
|
|
50
|
+
signal = [math.sin(2 * math.pi * 8 * t / fs) for t in range(n)]
|
|
51
|
+
save_figure(plot_waveform(signal, sample_rate=fs, title="8 Hz tone"), str(out / "wave.png"))
|
|
52
|
+
save_figure(
|
|
53
|
+
plot_power_spectrum(signal, sample_rate=fs, title="Power spectrum"),
|
|
54
|
+
str(out / "power.png"),
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
ar = [0.0]
|
|
58
|
+
for i in range(1, 100):
|
|
59
|
+
ar.append(0.75 * ar[-1] + (0.2 if i % 3 == 0 else -0.05))
|
|
60
|
+
save_figure(plot_acf(ar, max_lag=20, title="ACF"), str(out / "acf.png"))
|
|
61
|
+
|
|
62
|
+
seasonal = [1.0, 2.0, 3.0, 2.0, 1.0, 0.5] * 5
|
|
63
|
+
save_figure(
|
|
64
|
+
plot_seasonal_decompose(seasonal, period=6, title="Seasonal"),
|
|
65
|
+
str(out / "seasonal.png"),
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
xs = [float(i) for i in range(1, 11)]
|
|
69
|
+
ys = [2.0 * x + 1.0 + (0.3 if i % 2 else -0.2) for i, x in enumerate(xs)]
|
|
70
|
+
save_figure(plot_scatter(xs, ys, title="Scatter"), str(out / "scatter.png"))
|
|
71
|
+
save_figure(plot_regression(xs, ys, title="OLS fit"), str(out / "regression.png"))
|
|
72
|
+
|
|
73
|
+
mat = [[math.sin((i + 1) * (j + 1) / 5) for j in range(8)] for i in range(6)]
|
|
74
|
+
save_figure(plot_heatmap(mat, title="Heatmap"), str(out / "heatmap.png"))
|
|
75
|
+
|
|
76
|
+
save_figure(plot_loss([1.0 / (i + 1) for i in range(40)], title="Loss"), str(out / "loss.png"))
|
|
77
|
+
path = [(math.cos(t / 8) * (1 - t / 40), math.sin(t / 8) * (1 - t / 40)) for t in range(40)]
|
|
78
|
+
save_figure(plot_optimization_path(path, title="Spiral"), str(out / "opt_path.png"))
|
|
79
|
+
|
|
80
|
+
print(f"Wrote figures to {out}")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
if __name__ == "__main__":
|
|
84
|
+
main()
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
{
|
|
2
|
+
"cells": [
|
|
3
|
+
{
|
|
4
|
+
"cell_type": "markdown",
|
|
5
|
+
"id": "7fb27b941602401d91542211134fc71a",
|
|
6
|
+
"metadata": {},
|
|
7
|
+
"source": [
|
|
8
|
+
"# CDS plotting notebook\n",
|
|
9
|
+
"\n",
|
|
10
|
+
"Requires `pip install scientific-computing-system[plot]`.\n",
|
|
11
|
+
"Companion to `examples/plot_demo.py` and the Cookbook matplotlib section.\n"
|
|
12
|
+
]
|
|
13
|
+
},
|
|
14
|
+
{
|
|
15
|
+
"cell_type": "code",
|
|
16
|
+
"execution_count": null,
|
|
17
|
+
"id": "acae54e37e7d407bbb7b55eff062a284",
|
|
18
|
+
"metadata": {},
|
|
19
|
+
"outputs": [],
|
|
20
|
+
"source": [
|
|
21
|
+
"import math\n",
|
|
22
|
+
"\n",
|
|
23
|
+
"from cds.plot import plot_acf, plot_series, plot_spectrum, plot_waveform\n",
|
|
24
|
+
"from cds.signals import power_spectrum"
|
|
25
|
+
]
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
"cell_type": "code",
|
|
29
|
+
"execution_count": null,
|
|
30
|
+
"id": "9a63283cbaf04dbcab1f6479b197f3a8",
|
|
31
|
+
"metadata": {},
|
|
32
|
+
"outputs": [],
|
|
33
|
+
"source": [
|
|
34
|
+
"y = [math.sin(2 * math.pi * i / 40) for i in range(100)]\n",
|
|
35
|
+
"fig = plot_series(y, title=\"Sine wave\")\n",
|
|
36
|
+
"fig"
|
|
37
|
+
]
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
"cell_type": "code",
|
|
41
|
+
"execution_count": null,
|
|
42
|
+
"id": "8dd0d8092fe74a7c96281538738b07e2",
|
|
43
|
+
"metadata": {},
|
|
44
|
+
"outputs": [],
|
|
45
|
+
"source": [
|
|
46
|
+
"n, fs = 128, 128.0\n",
|
|
47
|
+
"signal = [math.sin(2 * math.pi * 8 * t / fs) for t in range(n)]\n",
|
|
48
|
+
"plot_waveform(signal, sample_rate=fs, title=\"8 Hz tone\")"
|
|
49
|
+
]
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
"cell_type": "code",
|
|
53
|
+
"execution_count": null,
|
|
54
|
+
"id": "72eea5119410473aa328ad9291626812",
|
|
55
|
+
"metadata": {},
|
|
56
|
+
"outputs": [],
|
|
57
|
+
"source": [
|
|
58
|
+
"power = power_spectrum(signal)\n",
|
|
59
|
+
"half = [math.sqrt(max(0.0, p)) for p in power[: n // 2]]\n",
|
|
60
|
+
"plot_spectrum(half, sample_rate=fs / 2, title=\"Spectrum\")"
|
|
61
|
+
]
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
"cell_type": "code",
|
|
65
|
+
"execution_count": null,
|
|
66
|
+
"id": "8edb47106e1a46a883d545849b8ab81b",
|
|
67
|
+
"metadata": {},
|
|
68
|
+
"outputs": [],
|
|
69
|
+
"source": [
|
|
70
|
+
"plot_acf(y, max_lag=20, title=\"ACF\")"
|
|
71
|
+
]
|
|
72
|
+
}
|
|
73
|
+
],
|
|
74
|
+
"metadata": {
|
|
75
|
+
"kernelspec": {
|
|
76
|
+
"display_name": "Python 3",
|
|
77
|
+
"language": "python",
|
|
78
|
+
"name": "python3"
|
|
79
|
+
},
|
|
80
|
+
"language_info": {
|
|
81
|
+
"name": "python",
|
|
82
|
+
"pygments_lexer": "ipython3"
|
|
83
|
+
}
|
|
84
|
+
},
|
|
85
|
+
"nbformat": 4,
|
|
86
|
+
"nbformat_minor": 5
|
|
87
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Probability distributions and sampling demo."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
|
|
5
|
+
from cds.probability import (
|
|
6
|
+
binomial_pmf,
|
|
7
|
+
exponential_pdf,
|
|
8
|
+
gaussian_pdf,
|
|
9
|
+
poisson_pmf,
|
|
10
|
+
uniform_pdf,
|
|
11
|
+
uniform_sample,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def main() -> None:
|
|
16
|
+
print("=== Continuous PDFs ===")
|
|
17
|
+
peak = gaussian_pdf(0.0, mu=0.0, sigma=1.0)
|
|
18
|
+
print(f"gaussian_pdf(0; mu=0, sigma=1) = {peak:.6f}")
|
|
19
|
+
print(f" (1/sqrt(2π) ≈ {1.0 / math.sqrt(2 * math.pi):.6f})")
|
|
20
|
+
print(f"uniform_pdf(0.5; a=0, b=1) = {uniform_pdf(0.5, a=0.0, b=1.0):.6f} (expect 1)")
|
|
21
|
+
print(f"exponential_pdf(1; lam=2) = {exponential_pdf(1.0, lam=2.0):.6f}")
|
|
22
|
+
|
|
23
|
+
print("\n=== Discrete PMFs ===")
|
|
24
|
+
print("Binomial PMF (n=10, p=0.5):")
|
|
25
|
+
for k in range(0, 11):
|
|
26
|
+
print(f" P(X={k}) = {binomial_pmf(k, n=10, p=0.5):.4f}")
|
|
27
|
+
print("Poisson PMF (lam=3):")
|
|
28
|
+
for k in range(0, 6):
|
|
29
|
+
print(f" P(X={k}) = {poisson_pmf(k, lam=3.0):.4f}")
|
|
30
|
+
|
|
31
|
+
print("\n=== Sampling ===")
|
|
32
|
+
samples = uniform_sample(a=0.0, b=1.0, n=5, seed=42)
|
|
33
|
+
print(f"5 samples from Uniform(0,1), seed=42: {samples}")
|
|
34
|
+
mean = sum(samples) / len(samples)
|
|
35
|
+
print(f"sample mean = {mean:.4f}")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
if __name__ == "__main__":
|
|
39
|
+
main()
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Quantum computing demo — Bell states and entanglement."""
|
|
2
|
+
|
|
3
|
+
from cds.quantum import (
|
|
4
|
+
QuantumCircuit,
|
|
5
|
+
bell_state,
|
|
6
|
+
ghz_state,
|
|
7
|
+
hadamard,
|
|
8
|
+
is_entangled,
|
|
9
|
+
simulate,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
# --- Single-qubit circuit ---
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def main() -> None:
|
|
16
|
+
print("=== Single-Qubit Circuit ===")
|
|
17
|
+
circuit = QuantumCircuit().add(hadamard())
|
|
18
|
+
result = circuit.run()
|
|
19
|
+
print(f"After Hadamard: P(0)={result.probabilities()[0]:.3f}")
|
|
20
|
+
|
|
21
|
+
counts = simulate(circuit, shots=10000)
|
|
22
|
+
print(f"Measurement (10k shots): {counts}\n")
|
|
23
|
+
|
|
24
|
+
# --- Bell state ---
|
|
25
|
+
print("=== Bell State |Φ+⟩ ===")
|
|
26
|
+
phi_plus = bell_state(0)
|
|
27
|
+
print(f"Entangled? {is_entangled(phi_plus)}")
|
|
28
|
+
bell_counts = phi_plus.measure_shots(shots=10000, seed=42)
|
|
29
|
+
print(f"Measurements: {bell_counts}\n")
|
|
30
|
+
|
|
31
|
+
# --- GHZ state ---
|
|
32
|
+
print("=== 4-Qubit GHZ State ===")
|
|
33
|
+
ghz = ghz_state(4)
|
|
34
|
+
probs = ghz.probabilities()
|
|
35
|
+
print(f"P(|0000⟩) = {probs[0]:.3f}")
|
|
36
|
+
print(f"P(|1111⟩) = {probs[15]:.3f}")
|
|
37
|
+
ghz_counts = ghz.measure_shots(shots=10000, seed=7)
|
|
38
|
+
print(f"Measurements: {ghz_counts}")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
if __name__ == "__main__":
|
|
42
|
+
main()
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Scientific constants and physics formulas demo."""
|
|
2
|
+
|
|
3
|
+
from cds.scientific import (
|
|
4
|
+
CONSTANTS,
|
|
5
|
+
de_broglie_wavelength,
|
|
6
|
+
escape_velocity,
|
|
7
|
+
get_constant,
|
|
8
|
+
gravitational_force,
|
|
9
|
+
ideal_gas_pressure,
|
|
10
|
+
kinetic_energy,
|
|
11
|
+
photon_energy,
|
|
12
|
+
schwarzschild_radius,
|
|
13
|
+
wave_frequency,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def main() -> None:
|
|
18
|
+
print("=== Physical Constants ===")
|
|
19
|
+
c = get_constant("c")
|
|
20
|
+
G = get_constant("G")
|
|
21
|
+
print(f"Speed of light c = {c} m/s")
|
|
22
|
+
print(f"Gravitational constant G = {G} N·m²/kg²")
|
|
23
|
+
print(f"Available constants: {sorted(CONSTANTS)}")
|
|
24
|
+
|
|
25
|
+
print("\n=== Mechanics ===")
|
|
26
|
+
ke = kinetic_energy(mass=10.0, velocity=5.0)
|
|
27
|
+
fg = gravitational_force(m1=5.0, m2=10.0, r=2.0)
|
|
28
|
+
ev = escape_velocity(mass=5.972e24, radius=6.371e6)
|
|
29
|
+
print(f"Kinetic energy (10kg @ 5m/s) = {ke:.2f} J")
|
|
30
|
+
print(f"Gravitational force (5kg,10kg @ 2m) = {fg:.6e} N")
|
|
31
|
+
print(f"Earth escape velocity = {ev:.1f} m/s")
|
|
32
|
+
|
|
33
|
+
print("\n=== Waves & Photons ===")
|
|
34
|
+
pe = photon_energy(frequency=5.0e14)
|
|
35
|
+
wf = wave_frequency(wavelength=500e-9)
|
|
36
|
+
dbw = de_broglie_wavelength(mass=9.109e-31, velocity=1.0e6)
|
|
37
|
+
print(f"Photon energy @ 5e14 Hz = {pe:.4e} J")
|
|
38
|
+
print(f"Frequency of 500nm light = {wf:.4e} Hz")
|
|
39
|
+
print(f"de Broglie wavelength (electron @ 1e6 m/s) = {dbw:.4e} m")
|
|
40
|
+
|
|
41
|
+
print("\n=== Astrophysics & Thermo ===")
|
|
42
|
+
rs = schwarzschild_radius(mass=1.989e30)
|
|
43
|
+
pg = ideal_gas_pressure(n_moles=1.0, temperature=300.0, volume=0.024)
|
|
44
|
+
print(f"Sun Schwarzschild radius = {rs:.2f} m")
|
|
45
|
+
print(f"Ideal gas pressure (n=1,T=300,V=0.024) = {pg:.2f} Pa")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
if __name__ == "__main__":
|
|
49
|
+
main()
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Signal processing demo — FFT and filtering."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
|
|
5
|
+
from cds.signals import (
|
|
6
|
+
apply_filter,
|
|
7
|
+
butter_bandpass,
|
|
8
|
+
butter_lowpass,
|
|
9
|
+
convolve,
|
|
10
|
+
dft,
|
|
11
|
+
fft_radix2,
|
|
12
|
+
low_pass_filter,
|
|
13
|
+
moving_median,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
# --- DFT of a simple signal ---
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def main() -> None:
|
|
20
|
+
print("=== DFT of Cosine Signal ===")
|
|
21
|
+
n = 16
|
|
22
|
+
signal = [complex(math.cos(2 * math.pi * 2 * k / n)) for k in range(n)]
|
|
23
|
+
spectrum = dft(signal)
|
|
24
|
+
print("Frequency magnitudes:")
|
|
25
|
+
for k, x in enumerate(spectrum):
|
|
26
|
+
mag = abs(x)
|
|
27
|
+
if mag > 0.5:
|
|
28
|
+
print(f" Bin {k}: {mag:.2f}")
|
|
29
|
+
|
|
30
|
+
# --- FFT comparison ---
|
|
31
|
+
print("\n=== FFT (radix-2) ===")
|
|
32
|
+
fft_result = fft_radix2(signal)
|
|
33
|
+
print(f"FFT matches DFT: {all(abs(a - b) < 1e-9 for a, b in zip(spectrum, fft_result))}")
|
|
34
|
+
|
|
35
|
+
# --- Convolution ---
|
|
36
|
+
print("\n=== Convolution ===")
|
|
37
|
+
a = [1.0, 2.0, 3.0, 4.0]
|
|
38
|
+
b = [0.5, 0.5] # averaging kernel
|
|
39
|
+
result = convolve(a, b)
|
|
40
|
+
print(f"{a} * {b} = {[round(x, 1) for x in result]}")
|
|
41
|
+
|
|
42
|
+
# --- Low-pass filter ---
|
|
43
|
+
print("\n=== Low-Pass Filter ===")
|
|
44
|
+
noisy = [1 + 0.3 * math.sin(2 * math.pi * 7 * k / n) for k in range(n)]
|
|
45
|
+
filtered = low_pass_filter([complex(x) for x in noisy], cutoff=3)
|
|
46
|
+
print("Original (first 8):", [f"{x:.2f}" for x in noisy[:8]])
|
|
47
|
+
print("Filtered (first 8):", [f"{x.real:.2f}" for x in filtered[:8]])
|
|
48
|
+
|
|
49
|
+
# --- Butterworth IIR low-pass ---
|
|
50
|
+
print("\n=== Butterworth Low-Pass (IIR) ===")
|
|
51
|
+
m = 512
|
|
52
|
+
# slow trend at 2% of Nyquist (well inside the passband), fast jitter at 90%.
|
|
53
|
+
clean = [math.sin(math.pi * 0.02 * k) for k in range(m)]
|
|
54
|
+
jitter = [0.5 * math.sin(math.pi * 0.9 * k) for k in range(m)]
|
|
55
|
+
mixed = [a + c for a, c in zip(clean, jitter)]
|
|
56
|
+
|
|
57
|
+
coef = butter_lowpass(order=4, cutoff=0.2)
|
|
58
|
+
smoothed = apply_filter(mixed, coef)
|
|
59
|
+
tail = slice(m // 2, m)
|
|
60
|
+
in_amp = (max(mixed[tail]) - min(mixed[tail])) / 2
|
|
61
|
+
out_amp = (max(smoothed[tail]) - min(smoothed[tail])) / 2
|
|
62
|
+
print(f"input amplitude : {in_amp:.3f} (trend + near-Nyquist jitter)")
|
|
63
|
+
print(f"output amplitude: {out_amp:.3f} (~1.0: jitter gone, trend kept)")
|
|
64
|
+
|
|
65
|
+
# --- Band-pass isolate a single tone ---
|
|
66
|
+
print("\n=== Band-Pass Isolation ===")
|
|
67
|
+
tones = [math.sin(math.pi * w * k) for w, k in zip([0.1] * m, range(m))]
|
|
68
|
+
for k in range(m): # add a second in-band tone plus an out-of-band one
|
|
69
|
+
tones[k] += 0.8 * math.sin(math.pi * 0.35 * k)
|
|
70
|
+
tones[k] += 0.6 * math.sin(math.pi * 0.8 * k)
|
|
71
|
+
bp = butter_bandpass(order=4, low=0.2, high=0.5)
|
|
72
|
+
isolated = apply_filter(tones, bp)
|
|
73
|
+
iso_amp = (max(isolated[tail]) - min(isolated[tail])) / 2
|
|
74
|
+
print(f"band-pass amplitude (0.35 tone): {iso_amp:.3f} (~0.8 expected)")
|
|
75
|
+
|
|
76
|
+
# --- Moving-median spike removal ---
|
|
77
|
+
print("\n=== Moving-Median Denoising ===")
|
|
78
|
+
base = [1.0] * 8
|
|
79
|
+
spiked = base[:3] + [25.0] + base[3:6] + [-18.0] + base[6:]
|
|
80
|
+
restored = moving_median(spiked, window=3)
|
|
81
|
+
print(f"input : {[round(x, 1) for x in spiked]}")
|
|
82
|
+
print(f"denoised: {[round(x, 1) for x in restored]}")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
if __name__ == "__main__":
|
|
86
|
+
main()
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Statistics and regression demo."""
|
|
2
|
+
|
|
3
|
+
from cds.stats import (
|
|
4
|
+
correlation,
|
|
5
|
+
linear_regression,
|
|
6
|
+
mean,
|
|
7
|
+
median,
|
|
8
|
+
stdev,
|
|
9
|
+
variance,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
# --- Descriptive statistics ---
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def main() -> None:
|
|
16
|
+
data = [23.1, 27.5, 19.8, 31.2, 25.6, 28.3, 22.0, 30.1]
|
|
17
|
+
print("=== Descriptive Statistics ===")
|
|
18
|
+
print(f"Data: {data}")
|
|
19
|
+
print(f"Mean: {mean(data):.2f}")
|
|
20
|
+
print(f"Median: {median(data):.2f}")
|
|
21
|
+
print(f"Variance: {variance(data):.2f}")
|
|
22
|
+
print(f"Std Dev: {stdev(data):.2f}")
|
|
23
|
+
|
|
24
|
+
# --- Correlation ---
|
|
25
|
+
print("\n=== Correlation ===")
|
|
26
|
+
x = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]
|
|
27
|
+
y = [2.1, 4.3, 5.8, 8.1, 9.7, 12.2, 13.8, 16.1]
|
|
28
|
+
r = correlation(x, y)
|
|
29
|
+
print(f"r = {r:.4f} (1.0 = perfect positive)")
|
|
30
|
+
|
|
31
|
+
# --- Linear regression ---
|
|
32
|
+
print("\n=== Linear Regression ===")
|
|
33
|
+
reg = linear_regression(x, y)
|
|
34
|
+
print(f"y = {reg.slope:.2f}x + {reg.intercept:.2f}")
|
|
35
|
+
print(f"R² = {reg.r_squared:.4f}")
|
|
36
|
+
print(f"Prediction at x=10: {reg.predict(10):.2f}")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
if __name__ == "__main__":
|
|
40
|
+
main()
|