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,122 @@
|
|
|
1
|
+
"""Basic quantum circuit representation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _finite_complex(value: complex) -> bool:
|
|
10
|
+
"""Return whether both real and imaginary components are finite."""
|
|
11
|
+
return math.isfinite(value.real) and math.isfinite(value.imag)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class Qubit:
|
|
16
|
+
"""Single qubit state as (alpha, beta) amplitudes."""
|
|
17
|
+
|
|
18
|
+
alpha: complex = 1 + 0j
|
|
19
|
+
beta: complex = 0 + 0j
|
|
20
|
+
|
|
21
|
+
def __post_init__(self) -> None:
|
|
22
|
+
if not _finite_complex(complex(self.alpha)) or not _finite_complex(complex(self.beta)):
|
|
23
|
+
raise ValueError("qubit amplitudes must be finite")
|
|
24
|
+
|
|
25
|
+
def probabilities(self) -> tuple[float, float]:
|
|
26
|
+
"""Return normalized ``(P(|0>), P(|1>))`` measurement probabilities."""
|
|
27
|
+
p0 = abs(self.alpha) ** 2
|
|
28
|
+
p1 = abs(self.beta) ** 2
|
|
29
|
+
total = p0 + p1
|
|
30
|
+
if not math.isfinite(total) or total <= 0.0:
|
|
31
|
+
raise ValueError("qubit state must have a finite non-zero norm")
|
|
32
|
+
return (p0 / total, p1 / total)
|
|
33
|
+
|
|
34
|
+
def normalize(self) -> None:
|
|
35
|
+
"""Renormalize the state amplitudes in-place to unit length."""
|
|
36
|
+
mag = (abs(self.alpha) ** 2) + (abs(self.beta) ** 2)
|
|
37
|
+
norm = math.sqrt(mag)
|
|
38
|
+
if norm > 0:
|
|
39
|
+
self.alpha /= norm
|
|
40
|
+
self.beta /= norm
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class QuantumGate:
|
|
45
|
+
"""A validated 2x2 unitary gate stored as flat list [a, b, c, d]."""
|
|
46
|
+
|
|
47
|
+
name: str
|
|
48
|
+
matrix: list[complex]
|
|
49
|
+
|
|
50
|
+
def __post_init__(self) -> None:
|
|
51
|
+
if not self.name.strip():
|
|
52
|
+
raise ValueError("quantum gate name must not be empty")
|
|
53
|
+
if len(self.matrix) != 4:
|
|
54
|
+
raise ValueError("quantum gate matrix must contain exactly four entries")
|
|
55
|
+
entries = tuple(complex(value) for value in self.matrix)
|
|
56
|
+
if any(not _finite_complex(value) for value in entries):
|
|
57
|
+
raise ValueError("quantum gate matrix entries must be finite")
|
|
58
|
+
a, b, c, d = entries
|
|
59
|
+
first_norm = abs(a) ** 2 + abs(c) ** 2
|
|
60
|
+
second_norm = abs(b) ** 2 + abs(d) ** 2
|
|
61
|
+
inner_product = a.conjugate() * b + c.conjugate() * d
|
|
62
|
+
if (
|
|
63
|
+
not math.isclose(first_norm, 1.0, rel_tol=1e-9, abs_tol=1e-12)
|
|
64
|
+
or not math.isclose(second_norm, 1.0, rel_tol=1e-9, abs_tol=1e-12)
|
|
65
|
+
or abs(inner_product) > 1e-9
|
|
66
|
+
):
|
|
67
|
+
raise ValueError("quantum gate matrix must be unitary")
|
|
68
|
+
self.matrix = list(entries)
|
|
69
|
+
|
|
70
|
+
def apply(self, q: Qubit) -> Qubit:
|
|
71
|
+
"""Apply this gate to ``q`` and return a new Qubit without mutating it."""
|
|
72
|
+
a, b, c, d = self.matrix
|
|
73
|
+
new_alpha = a * q.alpha + b * q.beta
|
|
74
|
+
new_beta = c * q.alpha + d * q.beta
|
|
75
|
+
return Qubit(alpha=new_alpha, beta=new_beta)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
# common gates
|
|
79
|
+
def hadamard() -> QuantumGate:
|
|
80
|
+
"""Hadamard gate H = (1/sqrt(2)) * [[1, 1], [1, -1]]."""
|
|
81
|
+
s = 1 / math.sqrt(2)
|
|
82
|
+
return QuantumGate("H", [s, s, s, -s])
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def pauli_x() -> QuantumGate:
|
|
86
|
+
"""Pauli-X (NOT) gate X = [[0, 1], [1, 0]]."""
|
|
87
|
+
return QuantumGate("X", [0, 1, 1, 0])
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def pauli_z() -> QuantumGate:
|
|
91
|
+
"""Pauli-Z gate Z = [[1, 0], [0, -1]]."""
|
|
92
|
+
return QuantumGate("Z", [1, 0, 0, -1])
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def phase_gate(theta: float) -> QuantumGate:
|
|
96
|
+
"""Phase rotation gate P(theta) = diag(1, e^{i*theta})."""
|
|
97
|
+
if not math.isfinite(theta):
|
|
98
|
+
raise ValueError("theta must be finite")
|
|
99
|
+
return QuantumGate(f"P({theta:.2f})", [1, 0, 0, complex(math.cos(theta), math.sin(theta))])
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@dataclass
|
|
103
|
+
class QuantumCircuit:
|
|
104
|
+
"""Simple circuit that applies gates sequentially to a single qubit."""
|
|
105
|
+
|
|
106
|
+
gates: list[QuantumGate] = field(default_factory=list)
|
|
107
|
+
|
|
108
|
+
def add(self, gate: QuantumGate) -> QuantumCircuit:
|
|
109
|
+
"""Append a gate to the circuit (returns self for fluent chaining)."""
|
|
110
|
+
self.gates.append(gate)
|
|
111
|
+
return self
|
|
112
|
+
|
|
113
|
+
def run(self, initial: Qubit | None = None) -> Qubit:
|
|
114
|
+
"""Apply all gates sequentially; starts from ``initial`` or |0>."""
|
|
115
|
+
q = initial if initial is not None else Qubit()
|
|
116
|
+
for gate in self.gates:
|
|
117
|
+
q = gate.apply(q)
|
|
118
|
+
return q
|
|
119
|
+
|
|
120
|
+
def __len__(self) -> int:
|
|
121
|
+
"""Return the number of gates in the circuit."""
|
|
122
|
+
return len(self.gates)
|
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
"""Multi-qubit quantum register with entanglement support."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import random
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
|
|
9
|
+
from cds.core._numeric import CONCURRENCE_THRESHOLD
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _finite_complex(value: complex) -> bool:
|
|
13
|
+
return math.isfinite(value.real) and math.isfinite(value.imag)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _validate_qubit_count(n: int) -> None:
|
|
17
|
+
if isinstance(n, bool) or not isinstance(n, int) or n <= 0:
|
|
18
|
+
raise ValueError("n_qubits must be a positive integer")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _validate_qubit_index(reg: QuantumRegister, index: int, *, name: str = "qubit") -> None:
|
|
22
|
+
if isinstance(index, bool) or not isinstance(index, int) or not 0 <= index < reg.n_qubits:
|
|
23
|
+
raise ValueError(f"{name} index must be between 0 and {reg.n_qubits - 1}")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _validate_distinct_indices(*indices: int) -> None:
|
|
27
|
+
if len(set(indices)) != len(indices):
|
|
28
|
+
raise ValueError("control and target qubit indices must be distinct")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class QuantumRegister:
|
|
33
|
+
"""N-qubit state vector with exactly ``2**n_qubits`` finite amplitudes."""
|
|
34
|
+
|
|
35
|
+
n_qubits: int
|
|
36
|
+
amplitudes: list[complex]
|
|
37
|
+
|
|
38
|
+
def __post_init__(self) -> None:
|
|
39
|
+
_validate_qubit_count(self.n_qubits)
|
|
40
|
+
expected = 1 << self.n_qubits
|
|
41
|
+
if len(self.amplitudes) != expected:
|
|
42
|
+
raise ValueError(f"amplitudes must contain exactly {expected} entries")
|
|
43
|
+
normalized_entries = [complex(amplitude) for amplitude in self.amplitudes]
|
|
44
|
+
if any(not _finite_complex(amplitude) for amplitude in normalized_entries):
|
|
45
|
+
raise ValueError("quantum register amplitudes must be finite")
|
|
46
|
+
self.amplitudes = normalized_entries
|
|
47
|
+
|
|
48
|
+
@classmethod
|
|
49
|
+
def zeros(cls, n: int) -> QuantumRegister:
|
|
50
|
+
"""Return the all-zero computational basis state for ``n`` qubits."""
|
|
51
|
+
_validate_qubit_count(n)
|
|
52
|
+
amps: list[complex] = [0 + 0j] * (1 << n)
|
|
53
|
+
amps[0] = 1 + 0j
|
|
54
|
+
return cls(n_qubits=n, amplitudes=amps)
|
|
55
|
+
|
|
56
|
+
@classmethod
|
|
57
|
+
def from_bits(cls, n: int, value: int) -> QuantumRegister:
|
|
58
|
+
"""Return computational basis state ``|value>`` for ``n`` qubits."""
|
|
59
|
+
_validate_qubit_count(n)
|
|
60
|
+
if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value < (1 << n):
|
|
61
|
+
raise ValueError(f"value must be an integer between 0 and {(1 << n) - 1}")
|
|
62
|
+
amps: list[complex] = [0 + 0j] * (1 << n)
|
|
63
|
+
amps[value] = 1 + 0j
|
|
64
|
+
return cls(n_qubits=n, amplitudes=amps)
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def size(self) -> int:
|
|
68
|
+
"""Number of amplitudes in the state vector (= 2**n_qubits)."""
|
|
69
|
+
return len(self.amplitudes)
|
|
70
|
+
|
|
71
|
+
def probabilities(self) -> list[float]:
|
|
72
|
+
"""Return normalized probabilities for all computational basis states."""
|
|
73
|
+
raw = [abs(amplitude) ** 2 for amplitude in self.amplitudes]
|
|
74
|
+
total = sum(raw)
|
|
75
|
+
if not math.isfinite(total) or total <= 0.0:
|
|
76
|
+
raise ValueError("quantum register state must have a finite non-zero norm")
|
|
77
|
+
return [probability / total for probability in raw]
|
|
78
|
+
|
|
79
|
+
def normalize(self) -> None:
|
|
80
|
+
"""Renormalize the state vector in-place to unit length."""
|
|
81
|
+
try:
|
|
82
|
+
squared_norm = sum(abs(amplitude) ** 2 for amplitude in self.amplitudes)
|
|
83
|
+
except OverflowError as exc:
|
|
84
|
+
raise ValueError("quantum register norm must be finite") from exc
|
|
85
|
+
if not math.isfinite(squared_norm):
|
|
86
|
+
raise ValueError("quantum register norm must be finite")
|
|
87
|
+
norm = math.sqrt(squared_norm)
|
|
88
|
+
if norm > 0:
|
|
89
|
+
self.amplitudes = [amplitude / norm for amplitude in self.amplitudes]
|
|
90
|
+
|
|
91
|
+
def measure(self, seed: int | None = None) -> int:
|
|
92
|
+
"""Measure the register and collapse its state vector."""
|
|
93
|
+
rng = random.Random(seed)
|
|
94
|
+
probs = self.probabilities()
|
|
95
|
+
r = rng.random()
|
|
96
|
+
cumulative = 0.0
|
|
97
|
+
for index, probability in enumerate(probs):
|
|
98
|
+
cumulative += probability
|
|
99
|
+
if r < cumulative:
|
|
100
|
+
new_amps = [0.0 + 0j] * len(self.amplitudes)
|
|
101
|
+
new_amps[index] = 1.0 + 0j
|
|
102
|
+
self.amplitudes = new_amps
|
|
103
|
+
return index
|
|
104
|
+
|
|
105
|
+
# Normalized probabilities can miss 1.0 only by floating-point roundoff.
|
|
106
|
+
final_idx = len(probs) - 1
|
|
107
|
+
new_amps = [0.0 + 0j] * len(self.amplitudes)
|
|
108
|
+
new_amps[final_idx] = 1.0 + 0j
|
|
109
|
+
self.amplitudes = new_amps
|
|
110
|
+
return final_idx
|
|
111
|
+
|
|
112
|
+
def measure_shots(
|
|
113
|
+
self,
|
|
114
|
+
shots: int = 1000,
|
|
115
|
+
seed: int | None = None,
|
|
116
|
+
) -> dict[str, int]:
|
|
117
|
+
"""Run multiple measurements and return counts as binary strings."""
|
|
118
|
+
if isinstance(shots, bool) or not isinstance(shots, int) or shots <= 0:
|
|
119
|
+
raise ValueError("shots must be a positive integer")
|
|
120
|
+
rng = random.Random(seed)
|
|
121
|
+
counts: dict[str, int] = {}
|
|
122
|
+
probs = self.probabilities()
|
|
123
|
+
for _ in range(shots):
|
|
124
|
+
r = rng.random()
|
|
125
|
+
cumulative = 0.0
|
|
126
|
+
result = len(probs) - 1
|
|
127
|
+
for index, probability in enumerate(probs):
|
|
128
|
+
cumulative += probability
|
|
129
|
+
if r < cumulative:
|
|
130
|
+
result = index
|
|
131
|
+
break
|
|
132
|
+
label = format(result, f"0{self.n_qubits}b")
|
|
133
|
+
counts[label] = counts.get(label, 0) + 1
|
|
134
|
+
return counts
|
|
135
|
+
|
|
136
|
+
def expectation(self) -> float:
|
|
137
|
+
"""Expected value treating the basis index as the eigenvalue."""
|
|
138
|
+
return sum(index * probability for index, probability in enumerate(self.probabilities()))
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _gate_2x2(
|
|
142
|
+
reg: QuantumRegister,
|
|
143
|
+
target: int,
|
|
144
|
+
matrix: list[complex],
|
|
145
|
+
) -> QuantumRegister:
|
|
146
|
+
"""Apply a 2x2 gate to a specific qubit in the register."""
|
|
147
|
+
_validate_qubit_index(reg, target, name="target")
|
|
148
|
+
n = reg.n_qubits
|
|
149
|
+
new_amps = list(reg.amplitudes)
|
|
150
|
+
step = 1 << target
|
|
151
|
+
a, b, c, d = matrix
|
|
152
|
+
|
|
153
|
+
for i in range(0, 1 << n, step << 1):
|
|
154
|
+
for j in range(step):
|
|
155
|
+
idx0 = i + j
|
|
156
|
+
idx1 = idx0 + step
|
|
157
|
+
v0 = reg.amplitudes[idx0]
|
|
158
|
+
v1 = reg.amplitudes[idx1]
|
|
159
|
+
new_amps[idx0] = a * v0 + b * v1
|
|
160
|
+
new_amps[idx1] = c * v0 + d * v1
|
|
161
|
+
|
|
162
|
+
return QuantumRegister(n_qubits=n, amplitudes=new_amps)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def h_gate(reg: QuantumRegister, target: int) -> QuantumRegister:
|
|
166
|
+
"""Hadamard on qubit ``target``."""
|
|
167
|
+
s = 1 / math.sqrt(2)
|
|
168
|
+
return _gate_2x2(reg, target, [s, s, s, -s])
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def x_gate(reg: QuantumRegister, target: int) -> QuantumRegister:
|
|
172
|
+
"""Pauli-X (NOT) on qubit ``target``."""
|
|
173
|
+
return _gate_2x2(reg, target, [0, 1, 1, 0])
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def z_gate(reg: QuantumRegister, target: int) -> QuantumRegister:
|
|
177
|
+
"""Pauli-Z on qubit ``target``."""
|
|
178
|
+
return _gate_2x2(reg, target, [1, 0, 0, -1])
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def y_gate(reg: QuantumRegister, target: int) -> QuantumRegister:
|
|
182
|
+
"""Pauli-Y on qubit ``target``."""
|
|
183
|
+
return _gate_2x2(reg, target, [0, -1j, 1j, 0])
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def rz_gate(
|
|
187
|
+
reg: QuantumRegister,
|
|
188
|
+
target: int,
|
|
189
|
+
theta: float,
|
|
190
|
+
) -> QuantumRegister:
|
|
191
|
+
"""Rotation around Z axis."""
|
|
192
|
+
if not math.isfinite(theta):
|
|
193
|
+
raise ValueError("theta must be finite")
|
|
194
|
+
e_neg = complex(math.cos(theta / 2), -math.sin(theta / 2))
|
|
195
|
+
e_pos = complex(math.cos(theta / 2), math.sin(theta / 2))
|
|
196
|
+
return _gate_2x2(reg, target, [e_neg, 0, 0, e_pos])
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def cnot(
|
|
200
|
+
reg: QuantumRegister,
|
|
201
|
+
control: int,
|
|
202
|
+
target: int,
|
|
203
|
+
) -> QuantumRegister:
|
|
204
|
+
"""Controlled-NOT gate."""
|
|
205
|
+
_validate_qubit_index(reg, control, name="control")
|
|
206
|
+
_validate_qubit_index(reg, target, name="target")
|
|
207
|
+
_validate_distinct_indices(control, target)
|
|
208
|
+
n = reg.n_qubits
|
|
209
|
+
new_amps = list(reg.amplitudes)
|
|
210
|
+
for i in range(1 << n):
|
|
211
|
+
if i & (1 << control):
|
|
212
|
+
j = i ^ (1 << target)
|
|
213
|
+
if j > i:
|
|
214
|
+
new_amps[i], new_amps[j] = reg.amplitudes[j], reg.amplitudes[i]
|
|
215
|
+
return QuantumRegister(n_qubits=n, amplitudes=new_amps)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def cz(
|
|
219
|
+
reg: QuantumRegister,
|
|
220
|
+
control: int,
|
|
221
|
+
target: int,
|
|
222
|
+
) -> QuantumRegister:
|
|
223
|
+
"""Controlled-Z gate."""
|
|
224
|
+
_validate_qubit_index(reg, control, name="control")
|
|
225
|
+
_validate_qubit_index(reg, target, name="target")
|
|
226
|
+
_validate_distinct_indices(control, target)
|
|
227
|
+
n = reg.n_qubits
|
|
228
|
+
new_amps = list(reg.amplitudes)
|
|
229
|
+
for i in range(1 << n):
|
|
230
|
+
if (i & (1 << control)) and (i & (1 << target)):
|
|
231
|
+
new_amps[i] = -reg.amplitudes[i]
|
|
232
|
+
return QuantumRegister(n_qubits=n, amplitudes=new_amps)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def swap(
|
|
236
|
+
reg: QuantumRegister,
|
|
237
|
+
q1: int,
|
|
238
|
+
q2: int,
|
|
239
|
+
) -> QuantumRegister:
|
|
240
|
+
"""SWAP gate — exchange two qubits."""
|
|
241
|
+
_validate_qubit_index(reg, q1, name="first")
|
|
242
|
+
_validate_qubit_index(reg, q2, name="second")
|
|
243
|
+
if q1 == q2:
|
|
244
|
+
return QuantumRegister(reg.n_qubits, list(reg.amplitudes))
|
|
245
|
+
reg = cnot(reg, q1, q2)
|
|
246
|
+
reg = cnot(reg, q2, q1)
|
|
247
|
+
reg = cnot(reg, q1, q2)
|
|
248
|
+
return reg
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def toffoli(
|
|
252
|
+
reg: QuantumRegister,
|
|
253
|
+
c1: int,
|
|
254
|
+
c2: int,
|
|
255
|
+
target: int,
|
|
256
|
+
) -> QuantumRegister:
|
|
257
|
+
"""Toffoli (CCNOT) gate — 3-qubit controlled-controlled-NOT."""
|
|
258
|
+
_validate_qubit_index(reg, c1, name="first control")
|
|
259
|
+
_validate_qubit_index(reg, c2, name="second control")
|
|
260
|
+
_validate_qubit_index(reg, target, name="target")
|
|
261
|
+
_validate_distinct_indices(c1, c2, target)
|
|
262
|
+
n = reg.n_qubits
|
|
263
|
+
new_amps = list(reg.amplitudes)
|
|
264
|
+
for i in range(1 << n):
|
|
265
|
+
if (i & (1 << c1)) and (i & (1 << c2)):
|
|
266
|
+
j = i ^ (1 << target)
|
|
267
|
+
if j > i:
|
|
268
|
+
new_amps[i], new_amps[j] = (
|
|
269
|
+
reg.amplitudes[j],
|
|
270
|
+
reg.amplitudes[i],
|
|
271
|
+
)
|
|
272
|
+
return QuantumRegister(n_qubits=n, amplitudes=new_amps)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
# ----- common state preparation -----
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def bell_state(which: int = 0) -> QuantumRegister:
|
|
279
|
+
"""Create one of the four Bell states, indexed 0 through 3."""
|
|
280
|
+
if isinstance(which, bool) or not isinstance(which, int) or which not in range(4):
|
|
281
|
+
raise ValueError("which must be an integer from 0 through 3")
|
|
282
|
+
reg = QuantumRegister.zeros(2)
|
|
283
|
+
if which in (2, 3):
|
|
284
|
+
reg = x_gate(reg, 1)
|
|
285
|
+
reg = h_gate(reg, 0)
|
|
286
|
+
reg = cnot(reg, 0, 1)
|
|
287
|
+
if which in (1, 3):
|
|
288
|
+
reg = z_gate(reg, 0)
|
|
289
|
+
return reg
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def ghz_state(n: int) -> QuantumRegister:
|
|
293
|
+
"""GHZ state: (|00...0> + |11...1>) / √2."""
|
|
294
|
+
reg = QuantumRegister.zeros(n)
|
|
295
|
+
reg = h_gate(reg, 0)
|
|
296
|
+
for i in range(1, n):
|
|
297
|
+
reg = cnot(reg, 0, i)
|
|
298
|
+
return reg
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def is_entangled(reg: QuantumRegister) -> bool:
|
|
302
|
+
"""Check whether a normalized-equivalent two-qubit pure state is entangled."""
|
|
303
|
+
if reg.n_qubits != 2:
|
|
304
|
+
raise ValueError("entanglement check only for 2-qubit states")
|
|
305
|
+
norm_squared = sum(abs(amplitude) ** 2 for amplitude in reg.amplitudes)
|
|
306
|
+
if not math.isfinite(norm_squared) or norm_squared <= 0.0:
|
|
307
|
+
raise ValueError("quantum register state must have a finite non-zero norm")
|
|
308
|
+
a, b, c, d = reg.amplitudes
|
|
309
|
+
concurrence = 2 * abs(a * d - b * c) / norm_squared
|
|
310
|
+
return concurrence > CONCURRENCE_THRESHOLD
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Run a circuit many times and collect measurement statistics."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import random
|
|
6
|
+
from collections import Counter
|
|
7
|
+
|
|
8
|
+
from cds.quantum.circuit import QuantumCircuit, Qubit
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def measure(
|
|
12
|
+
q: Qubit,
|
|
13
|
+
*,
|
|
14
|
+
seed: int | None = None,
|
|
15
|
+
rng: random.Random | None = None,
|
|
16
|
+
) -> int:
|
|
17
|
+
"""Measure and collapse a qubit with private reproducible randomness.
|
|
18
|
+
|
|
19
|
+
A caller may provide either a fixed ``seed`` for a one-off reproducible
|
|
20
|
+
measurement or a private :class:`random.Random` instance for a reproducible
|
|
21
|
+
stream of repeated measurements. The module-global RNG is never touched.
|
|
22
|
+
"""
|
|
23
|
+
if seed is not None and rng is not None:
|
|
24
|
+
raise ValueError("provide either seed or rng, not both")
|
|
25
|
+
sampler = rng if rng is not None else random.Random(seed)
|
|
26
|
+
p0, _ = q.probabilities()
|
|
27
|
+
outcome = 0 if sampler.random() < p0 else 1
|
|
28
|
+
|
|
29
|
+
if outcome == 0:
|
|
30
|
+
q.alpha, q.beta = 1.0 + 0j, 0.0 + 0j
|
|
31
|
+
else:
|
|
32
|
+
q.alpha, q.beta = 0.0 + 0j, 1.0 + 0j
|
|
33
|
+
|
|
34
|
+
return outcome
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def simulate(circuit: QuantumCircuit, shots: int = 1000, seed: int | None = None) -> dict[int, int]:
|
|
38
|
+
"""Run a circuit repeatedly and collect reproducible measurement counts.
|
|
39
|
+
|
|
40
|
+
The final state vector is computed once and then sampled ``shots`` times.
|
|
41
|
+
``shots`` must be a positive integer; invalid quantum states are rejected by
|
|
42
|
+
:meth:`Qubit.probabilities` instead of being silently interpreted as a
|
|
43
|
+
probability distribution.
|
|
44
|
+
"""
|
|
45
|
+
if isinstance(shots, bool) or not isinstance(shots, int) or shots <= 0:
|
|
46
|
+
raise ValueError("shots must be a positive integer")
|
|
47
|
+
rng = random.Random(seed)
|
|
48
|
+
|
|
49
|
+
q = circuit.run()
|
|
50
|
+
p0, _ = q.probabilities()
|
|
51
|
+
|
|
52
|
+
results = [0 if rng.random() < p0 else 1 for _ in range(shots)]
|
|
53
|
+
return dict(Counter(results))
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Scientific computing utilities."""
|
|
2
|
+
|
|
3
|
+
from cds.scientific.constants import CONSTANTS, get_constant
|
|
4
|
+
from cds.scientific.formulas import (
|
|
5
|
+
centripetal_acceleration,
|
|
6
|
+
coulomb_force,
|
|
7
|
+
de_broglie_wavelength,
|
|
8
|
+
doppler_frequency,
|
|
9
|
+
escape_velocity,
|
|
10
|
+
gravitational_force,
|
|
11
|
+
ideal_gas_pressure,
|
|
12
|
+
kinetic_energy,
|
|
13
|
+
pendulum_period,
|
|
14
|
+
photon_energy,
|
|
15
|
+
schwarzschild_radius,
|
|
16
|
+
wave_frequency,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"CONSTANTS",
|
|
21
|
+
"get_constant",
|
|
22
|
+
"kinetic_energy",
|
|
23
|
+
"gravitational_force",
|
|
24
|
+
"wave_frequency",
|
|
25
|
+
"ideal_gas_pressure",
|
|
26
|
+
"schwarzschild_radius",
|
|
27
|
+
"de_broglie_wavelength",
|
|
28
|
+
"escape_velocity",
|
|
29
|
+
"photon_energy",
|
|
30
|
+
"coulomb_force",
|
|
31
|
+
"centripetal_acceleration",
|
|
32
|
+
"pendulum_period",
|
|
33
|
+
"doppler_frequency",
|
|
34
|
+
]
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Physical and mathematical constants."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
|
|
7
|
+
CONSTANTS: dict[str, tuple[float, str]] = {
|
|
8
|
+
"c": (299_792_458.0, "speed of light (m/s)"),
|
|
9
|
+
"G": (6.674_30e-11, "gravitational constant (m^3 kg^-1 s^-2)"),
|
|
10
|
+
"h": (6.626_070_15e-34, "Planck constant (J·s)"),
|
|
11
|
+
"hbar": (1.054_571_817e-34, "reduced Planck constant (J·s)"),
|
|
12
|
+
"k_B": (1.380_649e-23, "Boltzmann constant (J/K)"),
|
|
13
|
+
"e": (1.602_176_634e-19, "elementary charge (C)"),
|
|
14
|
+
"N_A": (6.022_140_76e23, "Avogadro number (mol^-1)"),
|
|
15
|
+
"R": (8.314_462_618, "gas constant (J mol^-1 K^-1)"),
|
|
16
|
+
"sigma": (5.670_374_419e-8, "Stefan-Boltzmann constant (W m^-2 K^-4)"),
|
|
17
|
+
"pi": (math.pi, "pi"),
|
|
18
|
+
"e_math": (math.e, "Euler's number"),
|
|
19
|
+
"m_e": (9.109_383_7015e-31, "electron mass (kg)"),
|
|
20
|
+
"m_p": (1.672_621_923_69e-27, "proton mass (kg)"),
|
|
21
|
+
"epsilon_0": (8.854_187_8128e-12, "vacuum permittivity (F/m)"),
|
|
22
|
+
"g": (9.806_65, "standard gravity (m/s^2)"),
|
|
23
|
+
"mu_0": (1.256_637_062_12e-6, "vacuum permeability (N A^-2)"),
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def get_constant(name: str) -> float:
|
|
28
|
+
"""Look up a physical/mathematical constant by short name and return its value.
|
|
29
|
+
|
|
30
|
+
Raises:
|
|
31
|
+
KeyError: if `name` is not in the table (lists valid names in the message).
|
|
32
|
+
"""
|
|
33
|
+
if name not in CONSTANTS:
|
|
34
|
+
raise KeyError(f"unknown constant: {name}. available: {list(CONSTANTS.keys())}")
|
|
35
|
+
return CONSTANTS[name][0]
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""Common physics formulas."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
|
|
7
|
+
from cds.scientific.constants import get_constant
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def kinetic_energy(mass: float, velocity: float) -> float:
|
|
11
|
+
"""KE = 0.5 * m * v^2"""
|
|
12
|
+
return 0.5 * mass * velocity**2
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def gravitational_force(m1: float, m2: float, r: float) -> float:
|
|
16
|
+
"""F = G * m1 * m2 / r^2"""
|
|
17
|
+
G = get_constant("G")
|
|
18
|
+
if r == 0:
|
|
19
|
+
raise ValueError("distance can't be zero")
|
|
20
|
+
return G * m1 * m2 / r**2
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def wave_frequency(wavelength: float) -> float:
|
|
24
|
+
"""f = c / lambda"""
|
|
25
|
+
c = get_constant("c")
|
|
26
|
+
if wavelength <= 0:
|
|
27
|
+
raise ValueError("wavelength must be positive")
|
|
28
|
+
return c / wavelength
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def ideal_gas_pressure(n_moles: float, temperature: float, volume: float) -> float:
|
|
32
|
+
"""PV = nRT => P = nRT/V"""
|
|
33
|
+
R = get_constant("R")
|
|
34
|
+
if volume <= 0:
|
|
35
|
+
raise ValueError("volume must be positive")
|
|
36
|
+
return n_moles * R * temperature / volume
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def photon_energy(frequency: float) -> float:
|
|
40
|
+
"""E = h * f"""
|
|
41
|
+
h = get_constant("h")
|
|
42
|
+
return h * frequency
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def schwarzschild_radius(mass: float) -> float:
|
|
46
|
+
"""r_s = 2GM/c^2"""
|
|
47
|
+
G = get_constant("G")
|
|
48
|
+
c = get_constant("c")
|
|
49
|
+
return 2 * G * mass / c**2
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def de_broglie_wavelength(mass: float, velocity: float) -> float:
|
|
53
|
+
"""lambda = h / (m * v)"""
|
|
54
|
+
h = get_constant("h")
|
|
55
|
+
mv = mass * velocity
|
|
56
|
+
if mv == 0:
|
|
57
|
+
raise ValueError("momentum can't be zero")
|
|
58
|
+
return h / mv
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def escape_velocity(mass: float, radius: float) -> float:
|
|
62
|
+
"""v_esc = sqrt(2GM/r)"""
|
|
63
|
+
G = get_constant("G")
|
|
64
|
+
return math.sqrt(2 * G * mass / radius)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def coulomb_force(q1: float, q2: float, r: float) -> float:
|
|
68
|
+
"""Coulomb's law: ``F = k * |q1 q2| / r^2`` (SI, returns magnitude).
|
|
69
|
+
|
|
70
|
+
Uses ``k = 1 / (4 π ε0)`` with ``ε0`` from :mod:`cds.scientific.constants`.
|
|
71
|
+
"""
|
|
72
|
+
if r == 0:
|
|
73
|
+
raise ValueError("distance can't be zero")
|
|
74
|
+
eps0 = get_constant("epsilon_0")
|
|
75
|
+
k = 1.0 / (4.0 * math.pi * eps0)
|
|
76
|
+
return k * abs(q1 * q2) / (r**2)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def centripetal_acceleration(velocity: float, radius: float) -> float:
|
|
80
|
+
"""``a = v^2 / r`` (magnitude)."""
|
|
81
|
+
if radius <= 0:
|
|
82
|
+
raise ValueError("radius must be positive")
|
|
83
|
+
return (velocity**2) / radius
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def pendulum_period(length: float, g: float | None = None) -> float:
|
|
87
|
+
"""Small-angle simple pendulum period ``T = 2π √(L/g)``."""
|
|
88
|
+
if length <= 0:
|
|
89
|
+
raise ValueError("length must be positive")
|
|
90
|
+
gravity = get_constant("g") if g is None else g
|
|
91
|
+
if gravity <= 0:
|
|
92
|
+
raise ValueError("g must be positive")
|
|
93
|
+
return 2.0 * math.pi * math.sqrt(length / gravity)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def doppler_frequency(
|
|
97
|
+
f0: float,
|
|
98
|
+
v_source: float = 0.0,
|
|
99
|
+
v_observer: float = 0.0,
|
|
100
|
+
v_sound: float | None = None,
|
|
101
|
+
) -> float:
|
|
102
|
+
"""1-D acoustic Doppler: ``f = f0 * (v + vo) / (v + vs)``.
|
|
103
|
+
|
|
104
|
+
Sign convention: positive ``v_source`` means the source moves **away**
|
|
105
|
+
from the observer (denominator increases → lower pitch). Positive
|
|
106
|
+
``v_observer`` means the observer moves **toward** the source.
|
|
107
|
+
"""
|
|
108
|
+
if f0 <= 0:
|
|
109
|
+
raise ValueError("f0 must be positive")
|
|
110
|
+
v = 343.0 if v_sound is None else v_sound
|
|
111
|
+
if v <= 0:
|
|
112
|
+
raise ValueError("v_sound must be positive")
|
|
113
|
+
den = v + v_source
|
|
114
|
+
if den == 0:
|
|
115
|
+
raise ValueError("denominator (v + v_source) can't be zero")
|
|
116
|
+
return f0 * (v + v_observer) / den
|