├── .coveragerc ├── .git-template └── hooks │ └── pre-commit ├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ ├── config.yml │ ├── documentation_request.md │ └── feature_request.md ├── dependabot.yml ├── pr-title-checker-config.json ├── pull_request_template.md ├── scripts │ └── update_dependency.py └── workflows │ ├── check-format.yml │ ├── code-freeze.yml │ ├── dependent-tests.yml │ ├── pr-title-checker.yml │ ├── publish-to-pypi.yml │ ├── python-package.yml │ ├── stale_issue.yml │ └── twine-check.yml ├── .gitignore ├── .pre-commit-config.yaml ├── .readthedocs.yml ├── CHANGELOG.md ├── CODEOWNERS ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── MANIFEST.in ├── NOTICE ├── README.md ├── bin └── apply-header.py ├── doc ├── Makefile ├── conf.py ├── examples-adv-circuits-algorithms.rst ├── examples-braket-features.rst ├── examples-getting-started.rst ├── examples-hybrid-jobs.rst ├── examples-hybrid-quantum.rst ├── examples-ml-pennylane.rst ├── examples.rst ├── getting-started.rst ├── index.rst └── requirements.txt ├── examples ├── bell.py ├── bell_result_types.py ├── debug_bell.py ├── hybrid_job.py ├── hybrid_job_script.py ├── local_bell.py ├── local_noise_simulation.py └── reservation.py ├── program.py ├── pydoclint-baseline.txt ├── pyproject.toml ├── setup.cfg ├── setup.py ├── src └── braket │ ├── _sdk │ ├── __init__.py │ └── _version.py │ ├── ahs │ ├── __init__.py │ ├── analog_hamiltonian_simulation.py │ ├── atom_arrangement.py │ ├── discretization_types.py │ ├── driving_field.py │ ├── field.py │ ├── hamiltonian.py │ ├── local_detuning.py │ ├── pattern.py │ └── shifting_field.py │ ├── annealing │ ├── __init__.py │ └── problem.py │ ├── aws │ ├── __init__.py │ ├── aws_device.py │ ├── aws_quantum_job.py │ ├── aws_quantum_task.py │ ├── aws_quantum_task_batch.py │ ├── aws_session.py │ ├── direct_reservations.py │ └── queue_information.py │ ├── circuits │ ├── __init__.py │ ├── angled_gate.py │ ├── ascii_circuit_diagram.py │ ├── basis_state.py │ ├── braket_program_context.py │ ├── circuit.py │ ├── circuit_diagram.py │ ├── circuit_helpers.py │ ├── compiler_directive.py │ ├── compiler_directives.py │ ├── free_parameter.py │ ├── free_parameter_expression.py │ ├── gate.py │ ├── gate_calibrations.py │ ├── gates.py │ ├── instruction.py │ ├── measure.py │ ├── moments.py │ ├── noise.py │ ├── noise_helpers.py │ ├── noise_model │ │ ├── __init__.py │ │ ├── circuit_instruction_criteria.py │ │ ├── criteria.py │ │ ├── criteria_input_parsing.py │ │ ├── gate_criteria.py │ │ ├── initialization_criteria.py │ │ ├── noise_model.py │ │ ├── observable_criteria.py │ │ ├── qubit_initialization_criteria.py │ │ ├── result_type_criteria.py │ │ └── unitary_gate_criteria.py │ ├── noises.py │ ├── observable.py │ ├── observables.py │ ├── operator.py │ ├── parameterizable.py │ ├── quantum_operator.py │ ├── quantum_operator_helpers.py │ ├── qubit.py │ ├── qubit_set.py │ ├── result_type.py │ ├── result_types.py │ ├── serialization.py │ ├── text_diagram_builders │ │ ├── ascii_circuit_diagram.py │ │ ├── text_circuit_diagram.py │ │ ├── text_circuit_diagram_utils.py │ │ └── unicode_circuit_diagram.py │ ├── translations.py │ └── unitary_calculation.py │ ├── devices │ ├── __init__.py │ ├── device.py │ ├── devices.py │ └── local_simulator.py │ ├── error_mitigation │ ├── __init__.py │ ├── debias.py │ └── error_mitigation.py │ ├── ipython_utils.py │ ├── jobs │ ├── __init__.py │ ├── _entry_point_template.py │ ├── config.py │ ├── data_persistence.py │ ├── environment_variables.py │ ├── hybrid_job.py │ ├── image_uri_config │ │ ├── base.json │ │ ├── pl_pytorch.json │ │ └── pl_tensorflow.json │ ├── image_uris.py │ ├── local │ │ ├── __init__.py │ │ ├── local_job.py │ │ ├── local_job_container.py │ │ └── local_job_container_setup.py │ ├── logs.py │ ├── metrics.py │ ├── metrics_data │ │ ├── __init__.py │ │ ├── cwl_insights_metrics_fetcher.py │ │ ├── cwl_metrics_fetcher.py │ │ ├── definitions.py │ │ ├── exceptions.py │ │ └── log_metrics_parser.py │ ├── quantum_job.py │ ├── quantum_job_creation.py │ └── serialization.py │ ├── parametric │ ├── __init__.py │ ├── free_parameter.py │ ├── free_parameter_expression.py │ └── parameterizable.py │ ├── pulse │ ├── __init__.py │ ├── ast │ │ ├── approximation_parser.py │ │ ├── free_parameters.py │ │ ├── qasm_parser.py │ │ └── qasm_transformer.py │ ├── frame.py │ ├── port.py │ ├── pulse_sequence.py │ ├── pulse_sequence_trace.py │ └── waveforms.py │ ├── quantum_information │ ├── __init__.py │ └── pauli_string.py │ ├── registers │ ├── __init__.py │ ├── qubit.py │ └── qubit_set.py │ ├── tasks │ ├── __init__.py │ ├── analog_hamiltonian_simulation_quantum_task_result.py │ ├── annealing_quantum_task_result.py │ ├── gate_model_quantum_task_result.py │ ├── local_quantum_task.py │ ├── local_quantum_task_batch.py │ ├── photonic_model_quantum_task_result.py │ ├── quantum_task.py │ └── quantum_task_batch.py │ ├── timings │ ├── __init__.py │ └── time_series.py │ └── tracking │ ├── __init__.py │ ├── pricing.py │ ├── tracker.py │ ├── tracking_context.py │ └── tracking_events.py ├── test ├── integ_tests │ ├── conftest.py │ ├── gate_model_device_testing_utils.py │ ├── job_test_module │ │ └── job_test_submodule │ │ │ ├── job_test_submodule_file.py │ │ │ └── requirements.txt │ ├── job_test_script.py │ ├── job_testing_utils.py │ ├── requirements.txt │ ├── test_adjoint_gradient.py │ ├── test_aws_session_s3.py │ ├── test_cost_tracking.py │ ├── test_create_local_quantum_job.py │ ├── test_create_quantum_job.py │ ├── test_density_matrix_simulator.py │ ├── test_device_creation.py │ ├── test_local_braket_simulator.py │ ├── test_local_noise_simulator.py │ ├── test_measure.py │ ├── test_pulse.py │ ├── test_queue_information.py │ ├── test_reservation_arn.py │ ├── test_simulator_quantum_task.py │ ├── test_tensor_network_simulator.py │ └── test_user_agents.py └── unit_tests │ └── braket │ ├── ahs │ ├── test_analog_hamiltonian_simulation.py │ ├── test_atom_arrangement.py │ ├── test_driving_field.py │ ├── test_field.py │ ├── test_hamiltonian.py │ ├── test_local_detuning.py │ └── test_pattern.py │ ├── annealing │ └── test_problem.py │ ├── aws │ ├── common_test_utils.py │ ├── test_aws_device.py │ ├── test_aws_quantum_job.py │ ├── test_aws_quantum_task.py │ ├── test_aws_quantum_task_batch.py │ ├── test_aws_session.py │ └── test_direct_reservations.py │ ├── circuits │ ├── noise │ │ ├── test_gate_criteria.py │ │ ├── test_noise_model.py │ │ ├── test_observable_criteria.py │ │ ├── test_qubit_initialization_criteria.py │ │ └── test_unitary_gate_criteria.py │ ├── test_angled_gate.py │ ├── test_ascii_circuit_diagram.py │ ├── test_basis_state.py │ ├── test_circuit.py │ ├── test_circuit_helpers.py │ ├── test_compiler_directive.py │ ├── test_compiler_directives.py │ ├── test_gate.py │ ├── test_gate_calibration.py │ ├── test_gates.py │ ├── test_instruction.py │ ├── test_measure.py │ ├── test_moments.py │ ├── test_noise.py │ ├── test_noise_helpers.py │ ├── test_noises.py │ ├── test_observable.py │ ├── test_observables.py │ ├── test_quantum_operator.py │ ├── test_quantum_operator_helpers.py │ ├── test_result_type.py │ ├── test_result_types.py │ └── test_unicode_circuit_diagram.py │ ├── devices │ └── test_local_simulator.py │ ├── jobs │ ├── job_module.py │ ├── local │ │ ├── test_local_job.py │ │ ├── test_local_job_container.py │ │ └── test_local_job_container_setup.py │ ├── metrics_data │ │ ├── test_cwl_insights_metrics_fetcher.py │ │ ├── test_cwl_metrics_fetcher.py │ │ └── test_log_metrics_parser.py │ ├── test_data_persistence.py │ ├── test_environment_variables.py │ ├── test_hybrid_job.py │ ├── test_image_uris.py │ ├── test_metrics.py │ ├── test_quantum_job_creation.py │ └── test_serialization.py │ ├── parametric │ ├── test_free_parameter.py │ └── test_free_parameter_expression.py │ ├── pulse │ ├── ast │ │ └── test_approximation_parser.py │ ├── test_frame.py │ ├── test_port.py │ ├── test_pulse_sequence.py │ └── test_waveforms.py │ ├── quantum_information │ └── test_pauli_string.py │ ├── registers │ ├── test_qubit.py │ └── test_qubit_set.py │ ├── tasks │ ├── test_analog_hamiltonian_simulation_task_result.py │ ├── test_annealing_quantum_task_result.py │ ├── test_gate_model_quantum_task_result.py │ ├── test_local_quantum_task.py │ ├── test_local_quantum_task_batch.py │ ├── test_photonic_model_quantum_task_result.py │ └── test_tasks_init.py │ ├── test_imports.py │ ├── test_ipython_utils.py │ ├── timings │ └── test_time_series.py │ └── tracking │ ├── test_pricing.py │ ├── test_tracker.py │ └── test_tracking_context.py └── tox.ini /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | parallel = True 3 | branch = True 4 | source = 5 | src 6 | omit = 7 | **/braket/ir/* 8 | **/braket/device_schema/* 9 | **/braket/schema_common/* 10 | **/braket/task_result/* 11 | **/braket/simulator/* 12 | */site-packages/braket/* 13 | 14 | [paths] 15 | source = 16 | src 17 | */site-packages/braket 18 | 19 | [report] 20 | show_missing = True 21 | ignore_errors = True 22 | exclude_lines = 23 | # Have to re-enable the standard pragma 24 | pragma: no cover 25 | 26 | # Skipping import testing 27 | from importlib.metadata import entry_points 28 | 29 | # Don't complain if tests don't hit defensive assertion code: 30 | raise NotImplementedError 31 | 32 | # Avoid situation where system version causes coverage issues 33 | if sys.version_info.minor == 9: 34 | 35 | # Avoid type checking import conditionals 36 | if TYPE_CHECKING: 37 | 38 | [html] 39 | directory = build/coverage 40 | 41 | [xml] 42 | output = build/coverage/coverage.xml 43 | -------------------------------------------------------------------------------- /.git-template/hooks/pre-commit: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | if [ -f .pre-commit-config.yaml ]; then 3 | echo 'pre-commit configuration detected, but `pre-commit install` was never run' 1>&2 4 | exit 1 5 | fi 6 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: File a report to help us reproduce and fix the problem 4 | title: '' 5 | labels: 'bug' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To reproduce** 14 | A clear, step-by-step set of instructions to reproduce the bug. 15 | 16 | **Expected behavior** 17 | A clear and concise description of what you expected to happen. 18 | 19 | **Screenshots or logs** 20 | If applicable, add screenshots or logs to help explain your problem. 21 | 22 | **System information** 23 | A description of your system. Please provide: 24 | - **Amazon Braket Python SDK version**: 25 | - **Amazon Braket Python Schemas version**: 26 | - **Amazon Braket Python Default Simulator version**: 27 | - **Python version**: 28 | 29 | **Additional context** 30 | Add any other context about the problem here. 31 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false 2 | contact_links: 3 | - name: Ask a question 4 | url: https://forums.aws.amazon.com/tags/braket 5 | about: Use AWS Developer Forums to ask and answer questions 6 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/documentation_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Documentation request 3 | about: Request improved documentation 4 | title: '' 5 | labels: 'documentation' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **What did you find confusing? Please describe.** 11 | A clear and concise description of what you found confusing. Ex. I tried to [...] but I didn't understand how to [...] 12 | 13 | **Describe how documentation can be improved** 14 | A clear and concise description of where documentation was lacking and how it can be improved. 15 | 16 | **Additional context** 17 | Add any other context or screenshots about the documentation request here. 18 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest new functionality for this library 4 | title: '' 5 | labels: 'feature' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the feature you'd like** 11 | A clear and concise description of the functionality you want. 12 | 13 | **How would this feature be used? Please describe.** 14 | A clear and concise description of the use case for this feature. Please provide an example, if possible. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # Set update schedule for GitHub Actions 2 | 3 | version: 2 4 | updates: 5 | 6 | - package-ecosystem: "github-actions" 7 | directory: "/" 8 | schedule: 9 | # Check for updates to GitHub Actions every week 10 | interval: "monthly" 11 | commit-message: 12 | prefix: infra 13 | -------------------------------------------------------------------------------- /.github/pr-title-checker-config.json: -------------------------------------------------------------------------------- 1 | { 2 | "LABEL": { 3 | "name": "title needs formatting", 4 | "color": "EEEEEE" 5 | }, 6 | "CHECKS": { 7 | "prefixes": ["fix: ", "feat: ", "test: ", "infra: ", "doc: ", "change: ", "break: ", "breaking: ", "deprecation: ", "feature: ", "depr: ", "documentation: "], 8 | "regexp": "docs\\(v[0-9]\\): ", 9 | "regexpFlags": "i", 10 | "ignoreLabels" : ["dont-check-PRs-with-this-label", "meta"] 11 | }, 12 | "MESSAGES": { 13 | "success": "All OK", 14 | "failure": "Failing CI test", 15 | "notice": "" 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | *Issue #, if available:* 2 | 3 | *Description of changes:* 4 | 5 | *Testing done:* 6 | 7 | ## Merge Checklist 8 | 9 | _Put an `x` in the boxes that apply. You can also fill these out after creating the PR. If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your pull request._ 10 | 11 | #### General 12 | 13 | - [ ] I have read the [CONTRIBUTING](https://github.com/amazon-braket/amazon-braket-sdk-python/blob/main/CONTRIBUTING.md) doc 14 | - [ ] I used the PR title format described in [CONTRIBUTING](https://github.com/amazon-braket/amazon-braket-sdk-python/blob/main/CONTRIBUTING.md#PR-title-format) 15 | - [ ] I have updated any necessary documentation, including [READMEs](https://github.com/amazon-braket/amazon-braket-sdk-python/blob/main/README.md) and [API docs](https://github.com/amazon-braket/amazon-braket-sdk-python/blob/main/CONTRIBUTING.md#documentation-guidelines) (if appropriate) 16 | 17 | #### Tests 18 | 19 | - [ ] I have added tests that prove my fix is effective or that my feature works (if appropriate) 20 | - [ ] I have checked that my tests are not configured for a specific region or account (if appropriate) 21 | 22 | By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license. 23 | -------------------------------------------------------------------------------- /.github/scripts/update_dependency.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | import fileinput 15 | from pathlib import Path 16 | 17 | # Here we replace the `amazon-braket-sdk` dependency to point to the file system; otherwise 18 | # pip will install them separately, allowing it to override the version of 19 | # any mutual dependencies with the sdk. By pointing to the file system, pip will be 20 | # forced to reconcile the dependencies in setup.py with the dependencies of the sdk, 21 | # and raise an error if there are conflicts. While we can't do this for every upstream 22 | # dependency, we can do this for the ones we own to make sure that when the sdk updates 23 | # its dependencies, these upstream github repos will not be impacted. 24 | 25 | package = "amazon-braket-sdk" 26 | path = Path.cwd().parent.resolve() 27 | 28 | for line in fileinput.input("setup.py", inplace=True): 29 | # Update the amazon-braket-sdk dependency in setup.py to use the local path. This 30 | # would help catch conflicts during the installation process. 31 | replaced_line = ( 32 | line if package not in line else f'"{package} @ file://{path}/{package}-python",\n' 33 | ) 34 | print(replaced_line, end="") 35 | -------------------------------------------------------------------------------- /.github/workflows/check-format.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a variety of Python versions 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions 3 | 4 | name: Check code format 5 | 6 | on: 7 | pull_request: 8 | branches: 9 | - main 10 | - public-main 11 | - feature/** 12 | 13 | permissions: 14 | contents: read 15 | 16 | jobs: 17 | check-code-format: 18 | runs-on: ubuntu-latest 19 | steps: 20 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 21 | - name: Set up Python 22 | uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 23 | with: 24 | python-version: '3.9' 25 | - name: Install dependencies 26 | run: | 27 | pip install tox 28 | - name: Run code format checks 29 | run: | 30 | tox -e linters_check -p auto 31 | -------------------------------------------------------------------------------- /.github/workflows/code-freeze.yml: -------------------------------------------------------------------------------- 1 | name: Code Freeze 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - main 7 | workflow_dispatch: 8 | 9 | permissions: 10 | contents: read 11 | 12 | env: 13 | FROZEN: ${{ vars.FROZEN }} 14 | UNFROZEN_PREFIX: ${{ vars.UNFROZEN_PREFIX }} 15 | 16 | jobs: 17 | check-pr-frozen-status: 18 | runs-on: ubuntu-latest 19 | steps: 20 | - name: Fetch PR data and check if merge allowed 21 | if: env.FROZEN == 'true' 22 | env: 23 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 24 | run: | 25 | PR_DATA=$(curl -s \ 26 | -H "Authorization: Bearer $GITHUB_TOKEN" \ 27 | -H "Accept: application/vnd.github.v3+json" \ 28 | https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.pull_request.number }}) 29 | BRANCH_NAME=$(echo $PR_DATA | jq .head.ref -r) 30 | PR_TITLE=$(echo $PR_DATA | jq .title -r) 31 | 32 | echo $BRANCH_NAME 33 | echo $PR_TITLE 34 | 35 | # if it's not a critical fix 36 | if ! [[ "$PR_TITLE" == fix\(critical\):* ]]; then 37 | # and there's an unfrozen prefix 38 | if ! [[ -z $UNFROZEN_PREFIX ]]; then 39 | # check if the branch matches unfrozen prefix 40 | if [[ "$BRANCH_NAME" != $UNFROZEN_PREFIX* ]]; then 41 | echo "Error: You can only merge from branches that start with '$UNFROZEN_PREFIX', or PRs titled with prefix 'fix(critical): '." 42 | exit 1 43 | fi 44 | # repo is fully frozen 45 | else 46 | echo "Error: You can only merge PRs titled with prefix 'fix(critical): '." 47 | exit 1 48 | fi 49 | fi 50 | -------------------------------------------------------------------------------- /.github/workflows/dependent-tests.yml: -------------------------------------------------------------------------------- 1 | name: Dependent tests 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - main 7 | - feature/** 8 | 9 | permissions: 10 | contents: read 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ${{ matrix.os }} 16 | strategy: 17 | matrix: 18 | os: [ubuntu-latest, macos-latest, windows-latest] 19 | python-version: ["3.9", "3.10", "3.11"] 20 | dependent: 21 | - amazon-braket-pennylane-plugin-python 22 | 23 | steps: 24 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 25 | - name: Set up Python ${{ matrix.python-version }} 26 | uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 27 | with: 28 | python-version: ${{ matrix.python-version }} 29 | - name: Install dependencies 30 | run: | 31 | pip install --upgrade pip 32 | pip install --upgrade git+https://github.com/aws/amazon-braket-schemas-python.git@main 33 | pip install --upgrade git+https://github.com/aws/amazon-braket-default-simulator-python.git@main 34 | pip install -e . 35 | cd .. 36 | git clone https://github.com/aws/${{ matrix.dependent }}.git 37 | cd ${{ matrix.dependent }} 38 | # Update the amazon-braket-sdk dependency to reference the current commit 39 | python ${GITHUB_WORKSPACE}/.github/scripts/update_dependency.py 40 | pip install -e .[test] 41 | - name: Run unit tests 42 | run: | 43 | cd ../${{ matrix.dependent }} 44 | pytest 45 | -------------------------------------------------------------------------------- /.github/workflows/pr-title-checker.yml: -------------------------------------------------------------------------------- 1 | name: "PR Title Checker" 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | - feature/** 11 | pull_request_target: 12 | types: 13 | - opened 14 | - edited 15 | - synchronize 16 | - labeled 17 | - unlabeled 18 | 19 | permissions: 20 | pull-requests: write 21 | 22 | jobs: 23 | check: 24 | runs-on: ubuntu-latest 25 | steps: 26 | - name: "Check PR Title" 27 | uses: thehanimo/pr-title-checker@v1.4.3 28 | with: 29 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 30 | pass_on_octokit_error: false 31 | configuration_path: .github/pr-title-checker-config.json #(optional. defaults to .github/pr-title-checker-config.json) 32 | -------------------------------------------------------------------------------- /.github/workflows/publish-to-pypi.yml: -------------------------------------------------------------------------------- 1 | name: Publish distribution to PyPI 2 | 3 | on: 4 | release: 5 | types: [published] 6 | 7 | permissions: 8 | contents: read 9 | 10 | jobs: 11 | build-and-publish: 12 | name: Build and publish distribution to PyPi 13 | runs-on: ubuntu-latest 14 | steps: 15 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 16 | - name: Set up Python 17 | uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 18 | with: 19 | python-version: '3.x' 20 | - name: Install wheel 21 | run: python -m pip install --user --upgrade wheel 22 | - name: Install twine 23 | run: python -m pip install --user --upgrade twine 24 | - name: Install setuptools 25 | run: python -m pip install --user --upgrade setuptools 26 | - name: Build a binary wheel and a source tarball 27 | run: python setup.py sdist bdist_wheel 28 | - name: Publish distribution to PyPI 29 | uses: pypa/gh-action-pypi-publish@76f52bc884231f62b9a034ebfe128415bbaabdfc # release/v1 30 | with: 31 | password: ${{ secrets.pypi_token }} 32 | -------------------------------------------------------------------------------- /.github/workflows/python-package.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a variety of Python versions 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions 3 | 4 | name: Python package 5 | 6 | on: 7 | push: 8 | branches: 9 | - main 10 | pull_request: 11 | branches: 12 | - main 13 | - public-main 14 | - feature/** 15 | 16 | permissions: 17 | contents: read 18 | 19 | jobs: 20 | build: 21 | runs-on: ${{ matrix.os }} 22 | strategy: 23 | matrix: 24 | os: [ubuntu-latest, macos-latest, windows-latest] 25 | python-version: ["3.9", "3.10", "3.11"] 26 | 27 | steps: 28 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 29 | - name: Set up Python ${{ matrix.python-version }} 30 | uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 31 | with: 32 | python-version: ${{ matrix.python-version }} 33 | - name: Install dependencies 34 | run: | 35 | pip install tox 36 | - name: Run unit tests 37 | run: | 38 | tox -e unit-tests 39 | - name: Upload coverage report to Codecov 40 | uses: codecov/codecov-action@18283e04ce6e62d37312384ff67231eb8fd56d24 # v5.4.3 41 | with: 42 | token: ${{ secrets.CODECOV_TOKEN }} 43 | if: ${{ strategy.job-index }} == 0 44 | -------------------------------------------------------------------------------- /.github/workflows/stale_issue.yml: -------------------------------------------------------------------------------- 1 | name: "Close stale issues" 2 | 3 | # Controls when the action will run. 4 | # This is every day at 10am 5 | on: 6 | schedule: 7 | - cron: "0 10 * * *" 8 | 9 | permissions: 10 | contents: read 11 | 12 | jobs: 13 | cleanup: 14 | runs-on: ubuntu-latest 15 | permissions: 16 | issues: write # comment on issues 17 | name: Stale issue job 18 | steps: 19 | - uses: aws-actions/stale-issue-cleanup@7de35968489e4142233d2a6812519a82e68b5c38 # v6 20 | with: 21 | # Setting messages to an empty string will cause the automation to skip 22 | # that category 23 | ancient-issue-message: Greetings! It looks like this issue hasn’t been active in longer than three years. We encourage you to check if this is still an issue in the latest release. Because it has been longer than three years since the last update on this, and in the absence of more information, we will be closing this issue soon. If you find that this is still a problem, please feel free to provide a comment to prevent automatic closure, or if the issue is already closed, please feel free to reopen it. 24 | stale-issue-message: Greetings! It looks like this issue hasn’t been active in longer than a week. We encourage you to check if this is still an issue in the latest release. Because it has been longer than a week since the last update on this, and in the absence of more information, we will be closing this issue soon. If you find that this is still a problem, please feel free to provide a comment or add an upvote to prevent automatic closure, or if the issue is already closed, please feel free to open a new one. 25 | stale-pr-message: Greetings! It looks like this PR hasn’t been active in longer than a week, add a comment or an upvote to prevent automatic closure, or if the issue is already closed, please feel free to open a new one. 26 | 27 | # These labels are required 28 | stale-issue-label: closing-soon 29 | exempt-issue-label: auto-label-exempt 30 | stale-pr-label: closing-soon 31 | exempt-pr-label: pr/needs-review 32 | response-requested-label: response-requested 33 | 34 | # Don't set closed-for-staleness label to skip closing very old issues 35 | # regardless of label 36 | closed-for-staleness-label: closed-for-staleness 37 | 38 | # Issue timing 39 | days-before-stale: 7 40 | days-before-close: 4 41 | days-before-ancient: 1095 42 | 43 | # If you don't want to mark a issue as being ancient based on a 44 | # threshold of "upvotes", you can set this here. An "upvote" is 45 | # the total number of +1, heart, hooray, and rocket reactions 46 | # on an issue. 47 | minimum-upvotes-to-exempt: 1 48 | 49 | repo-token: ${{ secrets.GITHUB_TOKEN }} 50 | loglevel: DEBUG 51 | # Set dry-run to true to not perform label or close actions. 52 | dry-run: false 53 | -------------------------------------------------------------------------------- /.github/workflows/twine-check.yml: -------------------------------------------------------------------------------- 1 | name: Check long description for PyPI 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - main 7 | - public-main 8 | - feature/** 9 | 10 | permissions: 11 | contents: read 12 | 13 | jobs: 14 | twine-check: 15 | name: Check long description 16 | runs-on: ubuntu-latest 17 | steps: 18 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 19 | - name: Set up Python 20 | uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 21 | with: 22 | python-version: '3.x' 23 | - name: Install wheel 24 | run: python -m pip install --user --upgrade wheel 25 | - name: Install twine 26 | run: python -m pip install --user --upgrade twine 27 | - name: Install setuptools 28 | run: python -m pip install --user --upgrade setuptools 29 | - name: Build a binary wheel and a source tarball 30 | run: python setup.py sdist bdist_wheel 31 | - name: Check that long description will render correctly on PyPI. 32 | run: twine check dist/* 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | *# 3 | *.swp 4 | *.idea 5 | *.iml 6 | *.DS_Store 7 | .vscode/* 8 | build_files.tar.gz 9 | 10 | .ycm_extra_conf.py 11 | .tox 12 | .python-version 13 | 14 | __pycache__/ 15 | *.py[cod] 16 | *$py.class 17 | *.egg-info/ 18 | *.ipynb_checkpoints/ 19 | 20 | /.coverage 21 | /.coverage.* 22 | /.cache 23 | /.pytest_cache 24 | /.mypy_cache 25 | /pip-wheel-metadata 26 | 27 | /doc/_apidoc/ 28 | /build 29 | /venv 30 | /dist 31 | /model.tar.gz 32 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: local 3 | hooks: 4 | - id: tox_linters 5 | name: linters 6 | entry: tox -e linters_check 7 | language: system 8 | types: [python] 9 | -------------------------------------------------------------------------------- /.readthedocs.yml: -------------------------------------------------------------------------------- 1 | # .readthedocs.yml 2 | # Read the Docs configuration file 3 | # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details 4 | 5 | # Required 6 | version: 2 7 | 8 | # Build documentation in the docs/ directory with Sphinx 9 | sphinx: 10 | configuration: doc/conf.py 11 | 12 | # Optionally build your docs in additional formats such as PDF 13 | formats: 14 | - pdf 15 | 16 | # setting up build.os and the python version 17 | build: 18 | os: ubuntu-22.04 19 | tools: 20 | python: "3.9" 21 | 22 | # Optionally set the version of Python and requirements required to build your docs 23 | python: 24 | install: 25 | - method: pip 26 | path: . 27 | - requirements: doc/requirements.txt 28 | -------------------------------------------------------------------------------- /CODEOWNERS: -------------------------------------------------------------------------------- 1 | # https://help.github.com/en/github/creating-cloning-and-archiving-repositories/about-code-owners 2 | 3 | # These owners will be the default owners for everything in 4 | # the repo. Unless a later match takes precedence, these accounts 5 | # will be requested for review when someone opens a pull request. 6 | * @amazon-braket/braket-maintainers 7 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 4 | opensource-codeofconduct@amazon.com with any additional questions or comments. 5 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include *.md 2 | include *.yaml 3 | include *.yml 4 | include .coveragerc 5 | include CODEOWNERS 6 | include tox.ini 7 | recursive-include src *.json 8 | recursive-include bin *.py 9 | recursive-include doc *.py 10 | recursive-include doc *.rst 11 | recursive-include doc *.txt 12 | recursive-include doc Makefile 13 | recursive-include examples *.py 14 | recursive-include test *.py 15 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | -------------------------------------------------------------------------------- /bin/apply-header.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | """ 4 | Run from the root of the git repository, will apply contents of header to the beginning of 5 | all *.py files in the chosen directories. Script is idempotent, meaning it won't apply the 6 | header to a file that already contains it. 7 | 8 | Usage: python bin/apply-header.py 9 | """ 10 | 11 | HEADER = """# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 12 | # 13 | # Licensed under the Apache License, Version 2.0 (the "License"). You 14 | # may not use this file except in compliance with the License. A copy of 15 | # the License is located at 16 | # 17 | # http://aws.amazon.com/apache2.0/ 18 | # 19 | # or in the "license" file accompanying this file. This file is 20 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 21 | # ANY KIND, either express or implied. See the License for the specific 22 | # language governing permissions and limitations under the License. 23 | 24 | """ 25 | 26 | ROOT_DIRS = ["src", "test", "."] 27 | 28 | 29 | def main(): 30 | for root_dir in ROOT_DIRS: 31 | for root, dirs, files in os.walk(root_dir): 32 | for py_file in python_files(files): 33 | idempotent_prepend(os.path.join(root, py_file), HEADER) 34 | 35 | # don't recurse "." directory, just look at local files 36 | if root_dir == ".": 37 | break 38 | 39 | 40 | def python_files(files): 41 | return [file for file in files if file.endswith("py")] 42 | 43 | 44 | def idempotent_prepend(filename: str, new_content: str) -> None: 45 | with open(filename, "r+") as file: 46 | existing_content = file.read() 47 | 48 | if existing_content.startswith(new_content): 49 | print(f"Skipping {filename}, already contains the content.") 50 | else: 51 | print(f"Applying content to {filename}...") 52 | file.seek(0, 0) 53 | file.write(new_content + existing_content) 54 | 55 | 56 | if __name__ == "__main__": 57 | main() 58 | -------------------------------------------------------------------------------- /doc/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = python -msphinx 7 | SPHINXPROJ = amazon-braket-sdk 8 | SOURCEDIR = . 9 | BUILDDIR = ../build/documentation 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | -------------------------------------------------------------------------------- /doc/conf.py: -------------------------------------------------------------------------------- 1 | """Sphinx configuration.""" 2 | 3 | import datetime 4 | from importlib.metadata import version 5 | 6 | # Sphinx configuration below. 7 | project = "amazon-braket-sdk" 8 | version = version(project) 9 | release = version 10 | copyright = f"{datetime.datetime.now().year}, Amazon.com" 11 | 12 | extensions = [ 13 | "sphinxcontrib.apidoc", 14 | "sphinx.ext.autodoc", 15 | "sphinx.ext.viewcode", 16 | "sphinx.ext.napoleon", 17 | "sphinx.ext.todo", 18 | "sphinx.ext.coverage", 19 | ] 20 | 21 | source_suffix = ".rst" 22 | root_doc = "index" 23 | 24 | autoclass_content = "both" 25 | autodoc_member_order = "bysource" 26 | default_role = "py:obj" 27 | 28 | html_theme = "sphinx_rtd_theme" 29 | html_theme_options = { 30 | "prev_next_buttons_location": "both", 31 | } 32 | htmlhelp_basename = f"{project}doc" 33 | 34 | language = "en" 35 | 36 | napoleon_use_rtype = False 37 | napoleon_google_docstring = True 38 | napoleon_numpy_docstring = False 39 | 40 | apidoc_module_dir = "../src/braket" 41 | apidoc_output_dir = "_apidoc" 42 | apidoc_excluded_paths = ["../test"] 43 | apidoc_separate_modules = True 44 | apidoc_module_first = True 45 | apidoc_extra_args = ["-f", "--implicit-namespaces", "-H", "API Reference"] 46 | -------------------------------------------------------------------------------- /doc/examples-hybrid-quantum.rst: -------------------------------------------------------------------------------- 1 | ################################ 2 | Hybrid quantum algorithms 3 | ################################ 4 | 5 | Learn more about hybrid quantum algorithms. 6 | 7 | .. toctree:: 8 | :maxdepth: 2 9 | 10 | ************************************************************************************************************************************* 11 | `QAOA `_ 12 | ************************************************************************************************************************************* 13 | 14 | This tutorial shows how to (approximately) solve binary combinatorial optimization problems 15 | using the Quantum Approximate Optimization Algorithm (QAOA). 16 | 17 | ************************************************************************************************************************************************************************************ 18 | `VQE Transverse Ising `_ 19 | ************************************************************************************************************************************************************************************ 20 | 21 | This tutorial shows how to solve for the ground state of the Transverse Ising Model 22 | using the variational quantum eigenvalue solver (VQE). 23 | 24 | **************************************************************************************************************************************************************** 25 | `VQE Chemistry `_ 26 | **************************************************************************************************************************************************************** 27 | 28 | This tutorial shows how to implement the Variational Quantum Eigensolver (VQE) algorithm in 29 | Amazon Braket SDK to compute the potential energy surface (PES) for the Hydrogen molecule. 30 | -------------------------------------------------------------------------------- /doc/examples.rst: -------------------------------------------------------------------------------- 1 | ######## 2 | Examples 3 | ######## 4 | 5 | There are several examples available in the Amazon Braket repo: 6 | https://github.com/amazon-braket/amazon-braket-examples. 7 | 8 | .. toctree:: 9 | :maxdepth: 2 10 | 11 | examples-getting-started.rst 12 | examples-braket-features.rst 13 | examples-adv-circuits-algorithms.rst 14 | examples-hybrid-quantum.rst 15 | examples-ml-pennylane.rst 16 | examples-hybrid-jobs.rst 17 | -------------------------------------------------------------------------------- /doc/getting-started.rst: -------------------------------------------------------------------------------- 1 | ################################################# 2 | Getting Started with the Amazon Braket Python SDK 3 | ################################################# 4 | 5 | It is easy to get started with Amazon Braket Python SDK. You can get 6 | started using an Amazon Braket notebook instance or using 7 | your own environment. 8 | 9 | For more information about Amazon Braket, see the full set of documentation 10 | at https://docs.aws.amazon.com/braket/index.html. 11 | 12 | .. toctree:: 13 | :maxdepth: 2 14 | 15 | ************************************************ 16 | Getting started using an Amazon Braket notebook 17 | ************************************************ 18 | 19 | You can use the AWS Console to enable Amazon Braket, 20 | then create an Amazon Braket notebook instance 21 | and run your first circuit with the Amazon Braket Python SDK: 22 | 23 | 1. `Enable Amazon Braket `_. 24 | 2. `Create an Amazon Braket notebook instance `_. 25 | 3. `Run your first circuit using the Amazon Braket Python SDK `_. 26 | 27 | When you use an Amazon Braket notebook, the Amazon Braket SDK and plugins are 28 | preloaded. 29 | 30 | *********************************** 31 | Getting started in your environment 32 | *********************************** 33 | 34 | You can install the Amazon Braket Python SDK in your environment 35 | after enabling Amazon Braket and configuring the AWS SDK for Python: 36 | 37 | 1. `Enable Amazon Braket `_. 38 | 2. Configure the AWS SDK for Python (Boto3) using the `Quickstart `_. 39 | 3. `Run your first circuit using the Amazon Braket Python SDK `_. 40 | -------------------------------------------------------------------------------- /doc/index.rst: -------------------------------------------------------------------------------- 1 | ######################## 2 | Amazon Braket Python SDK 3 | ######################## 4 | 5 | The Amazon Braket Python SDK is an open source library to design and build quantum circuits, 6 | submit them to Amazon Braket devices as quantum tasks, and monitor their execution. 7 | 8 | This documentation provides information about the Amazon Braket Python SDK library. The project 9 | homepage is in Github https://github.com/amazon-braket/amazon-braket-sdk-python. The project 10 | includes SDK source, installation instructions, and other information. 11 | 12 | *************** 13 | Getting Started 14 | *************** 15 | 16 | .. toctree:: 17 | :maxdepth: 2 18 | 19 | getting-started 20 | 21 | 22 | ******** 23 | Examples 24 | ******** 25 | 26 | Explore Amazon Braket examples. 27 | 28 | .. toctree:: 29 | :maxdepth: 3 30 | 31 | examples.rst 32 | 33 | 34 | *************** 35 | Python SDK APIs 36 | *************** 37 | 38 | The Amazon Braket Python SDK APIs: 39 | 40 | .. toctree:: 41 | :maxdepth: 2 42 | 43 | _apidoc/modules 44 | -------------------------------------------------------------------------------- /doc/requirements.txt: -------------------------------------------------------------------------------- 1 | sphinx>7 2 | sphinx-rtd-theme>=1.3.0 3 | sphinxcontrib-apidoc 4 | -------------------------------------------------------------------------------- /examples/bell.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket.aws import AwsDevice 15 | from braket.circuits import Circuit 16 | from braket.devices import Devices 17 | 18 | device = AwsDevice(Devices.Amazon.SV1) 19 | 20 | # https://wikipedia.org/wiki/Bell_state 21 | bell = Circuit().h(0).cnot(0, 1) 22 | task = device.run(bell, shots=100) 23 | print(task.result().measurement_counts) 24 | -------------------------------------------------------------------------------- /examples/bell_result_types.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket.circuits import Circuit, observables 15 | from braket.devices import LocalSimulator 16 | 17 | device = LocalSimulator() 18 | 19 | print("Example for shots=0") 20 | # Result types can be requested in the circuit 21 | # Example of result types for shots=0 22 | bell = ( 23 | Circuit() 24 | .h(0) 25 | .cnot(0, 1) 26 | .probability(target=[0]) 27 | .expectation(observable=observables.Z(1)) 28 | .amplitude(state=["00"]) 29 | .state_vector() 30 | ) 31 | 32 | # State vector and amplitude can only be requested when shots=0 for a simulator 33 | # When shots=0 for a simulator, probability, expectation, variance are the exact values, 34 | # not calculated from measurements 35 | # Users cannot request Sample as a result when shots=0 36 | result = device.run(bell).result() 37 | print("Marginal probability for target 0 in computational basis:", result.values[0]) 38 | print("Expectation of target 1 in the computational basis:", result.values[1]) 39 | print("Amplitude of state 00:", result.values[2]) 40 | print("State vector:", result.values[3]) 41 | 42 | print("\nExample for shots>0") 43 | # Example of result types for shots > 0 44 | bell = ( 45 | Circuit() 46 | .h(0) 47 | .cnot(0, 1) 48 | .expectation(observable=observables.Y(0) @ observables.X(1)) 49 | .variance(observable=observables.Y(0) @ observables.X(1)) 50 | .sample(observable=observables.Y(0) @ observables.X(1)) 51 | ) 52 | 53 | # When shots>0 for a simulator, probability, expectation, variance are calculated from measurements 54 | # Users can request sample as a result when shots > 0 55 | result = device.run(bell, shots=100).result() 56 | print("Expectation of target 0, 1 in the basis of Pauli-Y @ Pauli-X:", result.values[0]) 57 | print("Variance of target 0, 1 in the basis of Pauli-Y @ Pauli-X:", result.values[1]) 58 | print("Samples of target 0, 1 in the basis of Pauli-Y @ Pauli-X:", result.values[2]) 59 | 60 | # Probability, sample, expectation, and variance are also supported for QPU devices 61 | -------------------------------------------------------------------------------- /examples/debug_bell.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | import logging 15 | import sys 16 | 17 | from braket.aws import AwsDevice 18 | from braket.circuits import Circuit 19 | from braket.devices import Devices 20 | 21 | logger = logging.getLogger("newLogger") # create new logger 22 | logger.addHandler(logging.StreamHandler(stream=sys.stdout)) # configure to print to sys.stdout 23 | logger.setLevel(logging.DEBUG) # print to sys.stdout all log messages with level DEBUG or above 24 | 25 | device = AwsDevice(Devices.Amazon.SV1) 26 | 27 | bell = Circuit().h(0).cnot(0, 1) 28 | # pass in logger to device.run, enabling debugging logs to print to console 29 | logger.info( 30 | device.run( 31 | bell, 32 | shots=100, 33 | poll_timeout_seconds=120, 34 | poll_interval_seconds=0.25, 35 | logger=logger, 36 | ) 37 | .result() 38 | .measurement_counts 39 | ) 40 | -------------------------------------------------------------------------------- /examples/hybrid_job.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket.aws import AwsDevice 15 | from braket.circuits import Circuit, FreeParameter, observables 16 | from braket.devices import Devices 17 | from braket.jobs import get_job_device_arn, hybrid_job 18 | from braket.jobs.metrics import log_metric 19 | 20 | 21 | @hybrid_job( 22 | device=Devices.Amazon.SV1, 23 | wait_until_complete=True, 24 | # If you want to run the job in a device reservation window, 25 | # change the device to the one you've reserved, 26 | # uncomment the following line and fill in your reservation ARN 27 | # reservation_arn="" 28 | ) 29 | def run_hybrid_job(num_tasks=1): 30 | # declare AwsDevice within the hybrid job 31 | device = AwsDevice(get_job_device_arn()) 32 | 33 | # create a parametric circuit 34 | circ = Circuit() 35 | circ.rx(0, FreeParameter("theta")) 36 | circ.cnot(0, 1) 37 | circ.expectation(observable=observables.X(0)) 38 | 39 | # initial parameter 40 | theta = 0.0 41 | 42 | for i in range(num_tasks): 43 | # run task, specifying input parameter 44 | task = device.run(circ, shots=100, inputs={"theta": theta}) 45 | exp_val = task.result().values[0] 46 | 47 | # modify the parameter (e.g. gradient descent) 48 | theta += exp_val 49 | 50 | log_metric(metric_name="exp_val", value=exp_val, iteration_number=i) 51 | 52 | return {"final_theta": theta, "final_exp_val": exp_val} 53 | 54 | 55 | job = run_hybrid_job(num_tasks=5) 56 | print(job.result()) 57 | -------------------------------------------------------------------------------- /examples/hybrid_job_script.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | 15 | from braket.aws import AwsDevice, AwsQuantumJob 16 | from braket.circuits import Circuit, FreeParameter, observables 17 | from braket.devices import Devices 18 | from braket.jobs import get_job_device_arn, save_job_result 19 | from braket.jobs.metrics import log_metric 20 | 21 | 22 | def run_hybrid_job(num_tasks: int): 23 | # use the device specified in the hybrid job 24 | device = AwsDevice(get_job_device_arn()) 25 | 26 | # create a parametric circuit 27 | circ = Circuit() 28 | circ.rx(0, FreeParameter("theta")) 29 | circ.cnot(0, 1) 30 | circ.expectation(observable=observables.X(0)) 31 | 32 | # initial parameter 33 | theta = 0.0 34 | 35 | for i in range(num_tasks): 36 | # run task, specifying input parameter 37 | task = device.run(circ, shots=100, inputs={"theta": theta}) 38 | exp_val = task.result().values[0] 39 | 40 | # modify the parameter (e.g. gradient descent) 41 | theta += exp_val 42 | 43 | log_metric(metric_name="exp_val", value=exp_val, iteration_number=i) 44 | 45 | save_job_result({"final_theta": theta, "final_exp_val": exp_val}) 46 | 47 | 48 | if __name__ == "__main__": 49 | job = AwsQuantumJob.create( 50 | device=Devices.Amazon.SV1, # choose priority device 51 | source_module="hybrid_job_script.py", # specify file or directory with code to run 52 | entry_point="hybrid_job_script:run_hybrid_job", # specify function to run 53 | hyperparameters={"num_tasks": 5}, 54 | wait_until_complete=True, 55 | ) 56 | print(job.result()) 57 | -------------------------------------------------------------------------------- /examples/local_bell.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket.circuits import Circuit 15 | from braket.devices import LocalSimulator 16 | 17 | device = LocalSimulator() 18 | 19 | bell = Circuit().h(0).cnot(0, 1) 20 | print(device.run(bell, shots=100).result().measurement_counts) 21 | -------------------------------------------------------------------------------- /examples/local_noise_simulation.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket.circuits import Circuit, noises 15 | from braket.devices import LocalSimulator 16 | 17 | device = LocalSimulator("braket_dm") 18 | 19 | circuit = Circuit().x(0).x(1).bit_flip(0, probability=0.1) 20 | print("First example: ") 21 | print(circuit) 22 | print(device.run(circuit, shots=1000).result().measurement_counts) 23 | 24 | 25 | circuit = Circuit().x(0).x(1) 26 | noise = noises.BitFlip(probability=0.1) 27 | circuit.apply_gate_noise(noise) 28 | print("Second example: ") 29 | print(circuit) 30 | print(device.run(circuit, shots=1000).result().measurement_counts) 31 | -------------------------------------------------------------------------------- /examples/reservation.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket.aws import AwsDevice, DirectReservation 15 | from braket.circuits import Circuit 16 | from braket.devices import Devices 17 | 18 | bell = Circuit().h(0).cnot(0, 1) 19 | device = AwsDevice(Devices.IonQ.Aria1) 20 | 21 | # To run a task in a device reservation, change the device to the one you reserved 22 | # and fill in your reservation ARN. 23 | with DirectReservation(device, reservation_arn=""): 24 | task = device.run(bell, shots=100) 25 | print(task.result().measurement_counts) 26 | 27 | # Alternatively, you may start the reservation globally 28 | reservation = DirectReservation(device, reservation_arn="").start() 29 | task = device.run(bell, shots=100) 30 | print(task.result().measurement_counts) 31 | reservation.stop() # stop creating tasks in the reservation 32 | 33 | # Lastly, you may pass the reservation ARN directly to a quantum task 34 | task = device.run(bell, shots=100, reservation_arn="") 35 | print(task.result().measurement_counts) 36 | -------------------------------------------------------------------------------- /program.py: -------------------------------------------------------------------------------- 1 | from braket.aws import AwsDevice 2 | 3 | device = AwsDevice("arn:aws:braket::us-west-1:device/qpu/rigetti/Ankaa-2") 4 | print(device) 5 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [aliases] 2 | test=pytest 3 | 4 | 5 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from setuptools import find_namespace_packages, setup 15 | 16 | with open("README.md") as fh: 17 | long_description = fh.read() 18 | 19 | with open("src/braket/_sdk/_version.py") as f: 20 | version = f.readlines()[-1].split()[-1].strip("\"'") 21 | 22 | setup( 23 | name="amazon-braket-sdk", 24 | version=version, 25 | license="Apache License 2.0", 26 | python_requires=">= 3.9", 27 | packages=find_namespace_packages(where="src", exclude=("test",)), 28 | package_dir={"": "src"}, 29 | install_requires=[ 30 | "amazon-braket-schemas>=1.23.0", 31 | "amazon-braket-default-simulator>=1.26.0", 32 | "oqpy~=0.3.5", 33 | "backoff", 34 | "boltons", 35 | "boto3>=1.28.53", 36 | # SageMaker pinned cloudpickle==2.2.1 37 | # see https://github.com/aws/sagemaker-python-sdk/issues/4871 38 | "cloudpickle==2.2.1", 39 | "nest-asyncio", 40 | "networkx", 41 | "numpy", 42 | "openpulse", 43 | "openqasm3", 44 | "sympy", 45 | "backports.entry-points-selectable", 46 | ], 47 | extras_require={ 48 | "test": [ 49 | "black", 50 | "botocore", 51 | "flake8", 52 | "isort", 53 | "jsonschema==3.2.0", 54 | "pre-commit", 55 | "pylint", 56 | "pytest", 57 | "pytest-cov", 58 | "pytest-rerunfailures", 59 | "pytest-xdist[psutil]", 60 | "tox", 61 | ], 62 | "docs": [ 63 | "sphinx", 64 | "sphinx-rtd-theme", 65 | "sphinxcontrib-apidoc", 66 | ], 67 | }, 68 | include_package_data=True, 69 | url="https://github.com/amazon-braket/amazon-braket-sdk-python", 70 | author="Amazon Web Services", 71 | description=( 72 | "An open source library for interacting with quantum computing devices on Amazon Braket" 73 | ), 74 | long_description=long_description, 75 | long_description_content_type="text/markdown", 76 | keywords="Amazon AWS Quantum", 77 | classifiers=[ 78 | "Development Status :: 5 - Production/Stable", 79 | "Intended Audience :: Developers", 80 | "Intended Audience :: Education", 81 | "Intended Audience :: Science/Research", 82 | "Natural Language :: English", 83 | "License :: OSI Approved :: Apache Software License", 84 | "Programming Language :: Python", 85 | "Programming Language :: Python :: 3.9", 86 | "Programming Language :: Python :: 3.10", 87 | "Programming Language :: Python :: 3.11", 88 | ], 89 | ) 90 | -------------------------------------------------------------------------------- /src/braket/_sdk/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from ._version import __version__ # noqa: F401 15 | -------------------------------------------------------------------------------- /src/braket/_sdk/_version.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | """Version information. 15 | Version number (major.minor.patch[-label]) 16 | """ 17 | 18 | __version__ = "1.91.3.dev0" 19 | -------------------------------------------------------------------------------- /src/braket/ahs/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket.ahs.analog_hamiltonian_simulation import AnalogHamiltonianSimulation # noqa: F401 15 | from braket.ahs.atom_arrangement import AtomArrangement, AtomArrangementItem, SiteType # noqa: F401 16 | from braket.ahs.discretization_types import DiscretizationProperties # noqa: F401 17 | from braket.ahs.driving_field import DrivingField # noqa: F401 18 | from braket.ahs.field import Field # noqa: F401 19 | from braket.ahs.hamiltonian import Hamiltonian # noqa: F401 20 | from braket.ahs.local_detuning import LocalDetuning # noqa: F401 21 | from braket.ahs.pattern import Pattern # noqa: F401 22 | from braket.ahs.shifting_field import ShiftingField # noqa: F401 23 | -------------------------------------------------------------------------------- /src/braket/ahs/discretization_types.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from dataclasses import dataclass 15 | from typing import Any 16 | 17 | 18 | class DiscretizationError(Exception): 19 | """Raised if the discretization of the numerical values of the AHS program fails.""" 20 | 21 | 22 | @dataclass 23 | class DiscretizationProperties: 24 | """Capabilities of a device that represent the resolution with which the device can 25 | implement the parameters. 26 | 27 | :parameter lattice (Any): configuration values for discretization of the lattice geometry, 28 | including the position resolution. 29 | :parameter rydberg (Any): configuration values for discretization of Rydberg fields. 30 | 31 | Examples: 32 | lattice.geometry.positionResolution = Decimal("1E-7") 33 | rydberg.rydbergGlobal.timeResolution = Decimal("1E-9") 34 | rydberg.rydbergGlobal.phaseResolution = Decimal("5E-7") 35 | """ 36 | 37 | lattice: Any 38 | rydberg: Any 39 | -------------------------------------------------------------------------------- /src/braket/ahs/hamiltonian.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from __future__ import annotations 15 | 16 | from typing import Optional 17 | 18 | from braket.ahs.discretization_types import DiscretizationProperties 19 | 20 | 21 | class Hamiltonian: 22 | def __init__(self, terms: Optional[list[Hamiltonian]] = None): 23 | r"""A Hamiltonian representing a system to be simulated. 24 | 25 | A Hamiltonian :math:`H` may be expressed as a sum of multiple terms 26 | 27 | .. math:: 28 | H = \sum_i H_i 29 | """ 30 | self._terms = terms or [] 31 | 32 | @property 33 | def terms(self) -> list[Hamiltonian]: 34 | """list[Hamiltonian]: The list of terms in this Hamiltonian.""" 35 | return self._terms 36 | 37 | def discretize(self, properties: DiscretizationProperties) -> Hamiltonian: 38 | """Creates a discretized version of the Hamiltonian. 39 | 40 | Args: 41 | properties (DiscretizationProperties): Capabilities of a device that represent the 42 | resolution with which the device can implement the parameters. 43 | 44 | Returns: 45 | Hamiltonian: A new discretized Hamiltonian. 46 | """ 47 | terms = [term.discretize(properties) for term in self.terms] 48 | return Hamiltonian(terms=terms) 49 | 50 | def __iadd__(self, other: Hamiltonian) -> Hamiltonian: 51 | if type(self) is not Hamiltonian: 52 | raise ValueError(f"Unable to modify Hamiltonian of type {type(self)}") 53 | self._terms.extend(other.terms) 54 | return self 55 | 56 | def __add__(self, other: Hamiltonian) -> Hamiltonian: 57 | terms = [] 58 | terms.extend(self.terms) 59 | terms.extend(other.terms) 60 | return Hamiltonian(terms) 61 | -------------------------------------------------------------------------------- /src/braket/ahs/pattern.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from __future__ import annotations 15 | 16 | from decimal import Decimal 17 | from numbers import Number 18 | from typing import Optional 19 | 20 | 21 | class Pattern: 22 | def __init__(self, series: list[Number]): 23 | """Represents the spatial dependence of a Field. 24 | 25 | Args: 26 | series (list[Number]): A series of numbers representing the the local 27 | pattern of real numbers. 28 | """ 29 | self._series = series 30 | 31 | @property 32 | def series(self) -> list[Number]: 33 | """list[Number]: A series of numbers representing the local 34 | pattern of real numbers. 35 | """ 36 | return self._series 37 | 38 | def discretize(self, resolution: Optional[Decimal]) -> Pattern: 39 | """Creates a discretized version of the pattern, 40 | where each value is rounded to the closest multiple 41 | of the resolution. 42 | 43 | Args: 44 | resolution (Optional[Decimal]): Resolution of the discretization 45 | 46 | Returns: 47 | Pattern: The new discretized pattern 48 | """ 49 | if resolution is None: 50 | discretized_series = [Decimal(num) for num in self.series] 51 | else: 52 | discretized_series = [ 53 | round(Decimal(num) / resolution) * resolution for num in self.series 54 | ] 55 | return Pattern(series=discretized_series) 56 | -------------------------------------------------------------------------------- /src/braket/ahs/shifting_field.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket.ahs.local_detuning import LocalDetuning 15 | 16 | # The class `ShiftingField` is deprecated. Please use `LocalDetuning` instead. 17 | # This file and class will be removed in a future version. 18 | # We are retaining this now to avoid breaking backwards compatibility for users already 19 | # utilizing this nomenclature. 20 | ShiftingField = LocalDetuning 21 | -------------------------------------------------------------------------------- /src/braket/annealing/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | # Execute initialization code in circuit module 15 | from braket.annealing.problem import Problem, ProblemType # noqa: F401 16 | -------------------------------------------------------------------------------- /src/braket/aws/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket.aws.aws_device import AwsDevice, AwsDeviceType # noqa: F401 15 | from braket.aws.aws_quantum_job import AwsQuantumJob # noqa: F401 16 | from braket.aws.aws_quantum_task import AwsQuantumTask # noqa: F401 17 | from braket.aws.aws_quantum_task_batch import AwsQuantumTaskBatch # noqa: F401 18 | from braket.aws.aws_session import AwsSession # noqa: F401 19 | from braket.aws.direct_reservations import DirectReservation # noqa: F401 20 | -------------------------------------------------------------------------------- /src/braket/circuits/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket.circuits import ( 15 | circuit, # noqa: F401 16 | compiler_directives, # noqa: F401 17 | gates, # noqa: F401 18 | noises, # noqa: F401 19 | observables, # noqa: F401 20 | result_types, # noqa: F401 21 | ) 22 | from braket.circuits.angled_gate import ( 23 | AngledGate, # noqa: F401 24 | DoubleAngledGate, # noqa: F401 25 | ) 26 | from braket.circuits.circuit import Circuit # noqa: F401 27 | from braket.circuits.circuit_diagram import CircuitDiagram # noqa: F401 28 | from braket.circuits.compiler_directive import CompilerDirective # noqa: F401 29 | from braket.circuits.free_parameter import FreeParameter # noqa: F401 30 | from braket.circuits.free_parameter_expression import FreeParameterExpression # noqa: F401 31 | from braket.circuits.gate import Gate # noqa: F401 32 | from braket.circuits.gate_calibrations import GateCalibrations # noqa: F401 33 | from braket.circuits.instruction import Instruction # noqa: F401 34 | from braket.circuits.moments import Moments, MomentsKey # noqa: F401 35 | from braket.circuits.noise import Noise # noqa: F401 36 | from braket.circuits.observable import ( 37 | Observable, # noqa: F401 38 | StandardObservable, # noqa: F401 39 | ) 40 | from braket.circuits.operator import Operator # noqa: F401 41 | from braket.circuits.parameterizable import Parameterizable # noqa: F401 42 | from braket.circuits.quantum_operator import QuantumOperator # noqa: F401 43 | from braket.circuits.qubit import Qubit, QubitInput # noqa: F401 44 | from braket.circuits.qubit_set import QubitSet, QubitSetInput # noqa: F401 45 | from braket.circuits.result_type import ( 46 | ObservableResultType, # noqa: F401 47 | ResultType, # noqa: F401 48 | ) 49 | from braket.circuits.text_diagram_builders.ascii_circuit_diagram import ( 50 | AsciiCircuitDiagram, # noqa: F401 51 | ) 52 | from braket.circuits.text_diagram_builders.unicode_circuit_diagram import ( 53 | UnicodeCircuitDiagram, # noqa: F401 54 | ) 55 | -------------------------------------------------------------------------------- /src/braket/circuits/ascii_circuit_diagram.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | # Moving ascii_circuit_diagram.py into the text_diagram_builders folder in order 15 | # to group all classes that print circuits in a text format. 16 | from braket.circuits.text_diagram_builders.ascii_circuit_diagram import ( 17 | AsciiCircuitDiagram, # noqa: F401 18 | ) 19 | -------------------------------------------------------------------------------- /src/braket/circuits/basis_state.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from functools import singledispatch 4 | from typing import Optional, Union 5 | 6 | import numpy as np 7 | 8 | 9 | class BasisState: 10 | def __init__(self, state: BasisStateInput, size: Optional[int] = None): 11 | self.state = _as_tuple(state, size) 12 | 13 | @property 14 | def size(self) -> int: 15 | return len(self.state) 16 | 17 | @property 18 | def as_tuple(self) -> tuple: 19 | return self.state 20 | 21 | @property 22 | def as_int(self) -> int: 23 | return 2 ** np.arange(self.size)[::-1] @ self.state 24 | 25 | @property 26 | def as_string(self) -> str: 27 | return "".join(map(str, self.state)) 28 | 29 | def __len__(self) -> int: 30 | return len(self.state) 31 | 32 | def __iter__(self): 33 | return iter(self.state) 34 | 35 | def __eq__(self, other: BasisState): 36 | return self.state == other.state 37 | 38 | def __bool__(self): 39 | return any(self.state) 40 | 41 | def __str__(self): 42 | return self.as_string 43 | 44 | def __repr__(self): 45 | return f'BasisState("{self.as_string}")' 46 | 47 | def __getitem__(self, item: int): 48 | return BasisState(self.state[item]) 49 | 50 | 51 | BasisStateInput = Union[int, list[int], str, BasisState] 52 | 53 | 54 | @singledispatch 55 | def _as_tuple(state: BasisStateInput, size: int) -> tuple: 56 | size = size if size is not None else len(state) 57 | if state and len(state) > size: 58 | raise ValueError( 59 | "State value represents a binary sequence of length greater " 60 | "than the specified number of qubits." 61 | ) 62 | return (0,) * (size - len(state)) + tuple(state) 63 | 64 | 65 | @_as_tuple.register 66 | def _(state: int, size: int): 67 | if size is not None and state >= 2**size: 68 | raise ValueError( 69 | "State value represents a binary sequence of length greater " 70 | "than the specified number of qubits." 71 | ) 72 | return tuple(int(x) for x in np.binary_repr(state, size)) 73 | 74 | 75 | @_as_tuple.register 76 | def _(state: str, size: int): 77 | size = size if size is not None else len(state) 78 | if len(state) > size: 79 | raise ValueError( 80 | "State value represents a binary sequence of length greater " 81 | "than the specified number of qubits." 82 | ) 83 | # left-pad to match state size 84 | return (0,) * (size - len(state)) + tuple(int(x) for x in state) 85 | -------------------------------------------------------------------------------- /src/braket/circuits/circuit_diagram.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from __future__ import annotations 15 | 16 | from abc import ABC, abstractmethod 17 | 18 | import braket.circuits.circuit as cir 19 | 20 | 21 | class CircuitDiagram(ABC): 22 | """A class that builds circuit diagrams.""" 23 | 24 | @staticmethod 25 | @abstractmethod 26 | def build_diagram(circuit: cir.Circuit) -> str: 27 | """Build a diagram for the specified `circuit`. 28 | 29 | Args: 30 | circuit (cir.Circuit): The circuit to build a diagram for. 31 | 32 | Returns: 33 | str: String representation for the circuit diagram. 34 | An empty string is returned for an empty circuit. 35 | """ 36 | -------------------------------------------------------------------------------- /src/braket/circuits/circuit_helpers.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket.circuits import Circuit, ResultType 15 | 16 | 17 | def validate_circuit_and_shots(circuit: Circuit, shots: int) -> None: 18 | """Validates if circuit and shots are correct before running on a device 19 | 20 | Args: 21 | circuit (Circuit): circuit to validate 22 | shots (int): shots to validate 23 | 24 | Raises: 25 | ValueError: If circuit has no instructions; if circuit has a non-gphase instruction; if no 26 | result types specified for circuit and `shots=0`. See `braket.circuit.result_types`; 27 | if circuit has observables that cannot be simultaneously measured and `shots>0`; 28 | or, if `StateVector` or `Amplitude` are specified as result types when `shots>0`. 29 | """ 30 | if not circuit.instructions or all( 31 | not (inst.target or inst.control) for inst in circuit.instructions 32 | ): 33 | raise ValueError("Circuit must have at least one non-zero-qubit gate to run on a device") 34 | if not shots and not circuit.result_types: 35 | raise ValueError( 36 | "No result types specified for circuit and shots=0. See `braket.circuits.result_types`" 37 | ) 38 | if shots and circuit.result_types: 39 | if not circuit.observables_simultaneously_measurable: 40 | raise ValueError("Observables cannot be sampled simultaneously") 41 | for rt in circuit.result_types: 42 | if isinstance(rt, (ResultType.Amplitude, ResultType.StateVector)): 43 | raise ValueError("StateVector or Amplitude cannot be specified when shots>0") # noqa: TRY004 44 | if isinstance(rt, ResultType.Probability): 45 | num_qubits = len(rt.target) or circuit.qubit_count 46 | if num_qubits > 40: 47 | raise ValueError("Probability target must be less than or equal to 40 qubits.") 48 | -------------------------------------------------------------------------------- /src/braket/circuits/compiler_directives.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from typing import Any 15 | 16 | import braket.ir.jaqcd as ir 17 | 18 | from braket.circuits.compiler_directive import CompilerDirective 19 | 20 | 21 | class StartVerbatimBox(CompilerDirective): 22 | """Prevents the compiler from modifying any ensuing instructions 23 | until the appearance of a corresponding ``EndVerbatimBox``. 24 | """ 25 | 26 | def __init__(self): 27 | super().__init__(["StartVerbatim"]) 28 | 29 | def counterpart(self) -> CompilerDirective: 30 | return EndVerbatimBox() 31 | 32 | def _to_jaqcd(self, *args, **kwargs) -> Any: 33 | return ir.StartVerbatimBox.construct() 34 | 35 | def _to_openqasm(self) -> str: 36 | return "#pragma braket verbatim\nbox{" 37 | 38 | 39 | class EndVerbatimBox(CompilerDirective): 40 | """Marks the end of a portion of code following a StartVerbatimBox that prevents the enclosed 41 | instructions from being modified by the compiler. 42 | """ 43 | 44 | def __init__(self): 45 | super().__init__(["EndVerbatim"]) 46 | 47 | def counterpart(self) -> CompilerDirective: 48 | return StartVerbatimBox() 49 | 50 | def _to_jaqcd(self, *args, **kwargs) -> Any: 51 | return ir.EndVerbatimBox.construct() 52 | 53 | def _to_openqasm(self) -> str: 54 | return "}" 55 | -------------------------------------------------------------------------------- /src/braket/circuits/free_parameter.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket.parametric.free_parameter import FreeParameter # noqa: F401 15 | -------------------------------------------------------------------------------- /src/braket/circuits/free_parameter_expression.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket.parametric.free_parameter_expression import FreeParameterExpression # noqa: F401 15 | -------------------------------------------------------------------------------- /src/braket/circuits/noise_model/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket.circuits.noise_model.circuit_instruction_criteria import ( 15 | CircuitInstructionCriteria, # noqa: F401 16 | ) 17 | from braket.circuits.noise_model.criteria import ( 18 | Criteria, # noqa: F401 19 | CriteriaKey, # noqa: F401 20 | CriteriaKeyResult, # noqa: F401 21 | ) 22 | from braket.circuits.noise_model.gate_criteria import GateCriteria # noqa: F401 23 | from braket.circuits.noise_model.initialization_criteria import InitializationCriteria # noqa: F401 24 | from braket.circuits.noise_model.noise_model import ( 25 | NoiseModel, # noqa: F401 26 | NoiseModelInstruction, # noqa: F401 27 | ) 28 | from braket.circuits.noise_model.observable_criteria import ObservableCriteria # noqa: F401 29 | from braket.circuits.noise_model.qubit_initialization_criteria import ( 30 | QubitInitializationCriteria, # noqa: F401 31 | ) 32 | from braket.circuits.noise_model.result_type_criteria import ResultTypeCriteria # noqa: F401 33 | from braket.circuits.noise_model.unitary_gate_criteria import UnitaryGateCriteria # noqa: F401 34 | -------------------------------------------------------------------------------- /src/braket/circuits/noise_model/circuit_instruction_criteria.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from abc import abstractmethod 15 | from typing import Optional, Union 16 | 17 | from braket.circuits.instruction import Instruction 18 | from braket.circuits.noise_model.criteria import Criteria 19 | from braket.registers.qubit_set import QubitSetInput 20 | 21 | 22 | class CircuitInstructionCriteria(Criteria): 23 | """Criteria that implement these methods may be used to determine gate noise.""" 24 | 25 | @abstractmethod 26 | def instruction_matches(self, instruction: Instruction) -> bool: 27 | """Returns True if an Instruction matches the criteria. 28 | 29 | Args: 30 | instruction (Instruction): An Instruction to match. 31 | 32 | Raises: 33 | NotImplementedError: Not implemented. 34 | 35 | Returns: 36 | bool: True if an Instruction matches the criteria. 37 | """ 38 | raise NotImplementedError 39 | 40 | @staticmethod 41 | def _check_target_in_qubits( 42 | qubits: Optional[set[Union[int, tuple[int]]]], target: QubitSetInput 43 | ) -> bool: 44 | """Returns true if the given targets of an instruction match the given qubit input set. 45 | 46 | Args: 47 | qubits (Optional[set[Union[int, tuple[int]]]]): The qubits provided to the criteria. 48 | target (QubitSetInput): Targets of an instruction. 49 | 50 | Returns: 51 | bool: True if the provided target should be matched by the given qubits. 52 | """ 53 | if qubits is None: 54 | return True 55 | target = [int(item) for item in target] 56 | return target[0] in qubits if len(target) == 1 else tuple(target) in qubits 57 | -------------------------------------------------------------------------------- /src/braket/circuits/noise_model/initialization_criteria.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from abc import abstractmethod 15 | 16 | from braket.circuits.noise_model.criteria import Criteria 17 | from braket.registers.qubit_set import QubitSetInput 18 | 19 | 20 | class InitializationCriteria(Criteria): 21 | """Criteria that implement these methods may be used to determine initialization noise.""" 22 | 23 | @abstractmethod 24 | def qubit_intersection(self, qubits: QubitSetInput) -> QubitSetInput: 25 | """Returns subset of passed qubits that match the criteria. 26 | 27 | Args: 28 | qubits (QubitSetInput): A qubit or set of qubits that may match the criteria. 29 | 30 | Returns: 31 | QubitSetInput: The subset of passed qubits that match the criteria. 32 | """ 33 | raise NotImplementedError 34 | -------------------------------------------------------------------------------- /src/braket/circuits/noise_model/result_type_criteria.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from abc import abstractmethod 15 | 16 | from braket.circuits.noise_model.criteria import Criteria 17 | from braket.circuits.result_type import ResultType 18 | 19 | 20 | class ResultTypeCriteria(Criteria): 21 | """Criteria that implement these methods may be used to determine readout noise.""" 22 | 23 | @abstractmethod 24 | def result_type_matches(self, result_type: ResultType) -> bool: 25 | """Returns true if a result type matches the criteria. 26 | 27 | Args: 28 | result_type (ResultType): A result type or list of result types to match. 29 | 30 | Returns: 31 | bool: True if the result type matches the criteria. 32 | """ 33 | raise NotImplementedError 34 | -------------------------------------------------------------------------------- /src/braket/circuits/operator.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from abc import ABC, abstractmethod 15 | from typing import Any 16 | 17 | 18 | class Operator(ABC): 19 | """An operator is the abstract definition of an operation for a quantum device.""" 20 | 21 | @property 22 | @abstractmethod 23 | def name(self) -> str: 24 | """The name of the operator. 25 | 26 | Returns: 27 | str: The name of the operator. 28 | """ 29 | 30 | @abstractmethod 31 | def to_ir(self, *args, **kwargs) -> Any: 32 | """Converts the operator into the canonical intermediate representation. 33 | If the operator is passed in a request, this method is called before it is passed. 34 | 35 | Returns: 36 | Any: The the canonical intermediate representation of the operator. 37 | """ 38 | -------------------------------------------------------------------------------- /src/braket/circuits/parameterizable.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket.parametric.parameterizable import Parameterizable # noqa: F401 15 | -------------------------------------------------------------------------------- /src/braket/circuits/qubit.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket.registers import Qubit, QubitInput # noqa: F401 15 | -------------------------------------------------------------------------------- /src/braket/circuits/qubit_set.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket.registers.qubit_set import QubitSet, QubitSetInput # noqa: F401 15 | -------------------------------------------------------------------------------- /src/braket/circuits/serialization.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from abc import ABC, abstractmethod 15 | from dataclasses import dataclass 16 | from enum import Enum 17 | 18 | 19 | class IRType(str, Enum): 20 | """Defines the available IRTypes for circuit serialization.""" 21 | 22 | OPENQASM = "OPENQASM" 23 | JAQCD = "JAQCD" 24 | 25 | 26 | class QubitReferenceType(str, Enum): 27 | """Defines how qubits should be referenced in the generated OpenQASM string. 28 | See https://qiskit.github.io/openqasm/language/types.html#quantum-types 29 | for details. 30 | """ 31 | 32 | VIRTUAL = "VIRTUAL" 33 | PHYSICAL = "PHYSICAL" 34 | 35 | 36 | class SerializableProgram(ABC): 37 | @abstractmethod 38 | def to_ir( 39 | self, 40 | ir_type: IRType = IRType.OPENQASM, 41 | ) -> str: 42 | """Serializes the program into an intermediate representation. 43 | 44 | Args: 45 | ir_type (IRType): The IRType to use for converting the program to its 46 | IR representation. Defaults to IRType.OPENQASM. 47 | 48 | Raises: 49 | ValueError: Raised if the supplied `ir_type` is not supported. 50 | 51 | Returns: 52 | str: A representation of the program in the `ir_type` format. 53 | """ 54 | 55 | 56 | @dataclass 57 | class OpenQASMSerializationProperties: 58 | """Properties for serializing a circuit to OpenQASM. 59 | 60 | qubit_reference_type (QubitReferenceType): determines whether to use 61 | logical qubits or physical qubits (q[i] vs $i). 62 | """ 63 | 64 | qubit_reference_type: QubitReferenceType = QubitReferenceType.VIRTUAL 65 | 66 | def format_target(self, target: int) -> str: 67 | """Format a target qubit to the appropriate OpenQASM representation. 68 | 69 | Args: 70 | target (int): The target qubit. 71 | 72 | Returns: 73 | str: The OpenQASM representation of the target qubit. 74 | """ 75 | qubit_reference_format = ( 76 | "q[{}]" if self.qubit_reference_type == QubitReferenceType.VIRTUAL else "${}" 77 | ) 78 | return qubit_reference_format.format(target) 79 | 80 | 81 | # Type alias to refer to possible serialization properties. Can be expanded once 82 | # new properties are added. 83 | SerializationProperties = OpenQASMSerializationProperties 84 | -------------------------------------------------------------------------------- /src/braket/devices/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket.devices.device import Device # noqa: F401 15 | from braket.devices.devices import Devices # noqa: F401 16 | from braket.devices.local_simulator import LocalSimulator # noqa: F401 17 | -------------------------------------------------------------------------------- /src/braket/devices/devices.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from enum import Enum 15 | 16 | 17 | class Devices: 18 | class _Amazon(str, Enum): 19 | SV1 = "arn:aws:braket:::device/quantum-simulator/amazon/sv1" 20 | TN1 = "arn:aws:braket:::device/quantum-simulator/amazon/tn1" 21 | DM1 = "arn:aws:braket:::device/quantum-simulator/amazon/dm1" 22 | 23 | class _DWave(str, Enum): 24 | _Advantage1 = "arn:aws:braket:::device/qpu/d-wave/Advantage_system1" 25 | _Advantage3 = "arn:aws:braket:::device/qpu/d-wave/Advantage_system3" 26 | _Advantage4 = "arn:aws:braket:::device/qpu/d-wave/Advantage_system4" 27 | _Advantage6 = "arn:aws:braket:us-west-2::device/qpu/d-wave/Advantage_system6" 28 | _DW2000Q6 = "arn:aws:braket:::device/qpu/d-wave/DW_2000Q_6" 29 | 30 | class _IQM(str, Enum): 31 | Garnet = "arn:aws:braket:eu-north-1::device/qpu/iqm/Garnet" 32 | 33 | class _IonQ(str, Enum): 34 | _Harmony = "arn:aws:braket:us-east-1::device/qpu/ionq/Harmony" 35 | Aria1 = "arn:aws:braket:us-east-1::device/qpu/ionq/Aria-1" 36 | Aria2 = "arn:aws:braket:us-east-1::device/qpu/ionq/Aria-2" 37 | Forte1 = "arn:aws:braket:us-east-1::device/qpu/ionq/Forte-1" 38 | ForteEnterprise1 = "arn:aws:braket:us-east-1::device/qpu/ionq/Forte-Enterprise-1" 39 | 40 | class _OQC(str, Enum): 41 | _Lucy = "arn:aws:braket:eu-west-2::device/qpu/oqc/Lucy" 42 | 43 | class _QuEra(str, Enum): 44 | Aquila = "arn:aws:braket:us-east-1::device/qpu/quera/Aquila" 45 | 46 | class _Rigetti(str, Enum): 47 | _Aspen8 = "arn:aws:braket:::device/qpu/rigetti/Aspen-8" 48 | _Aspen9 = "arn:aws:braket:::device/qpu/rigetti/Aspen-9" 49 | _Aspen10 = "arn:aws:braket:::device/qpu/rigetti/Aspen-10" 50 | _Aspen11 = "arn:aws:braket:::device/qpu/rigetti/Aspen-11" 51 | _AspenM1 = "arn:aws:braket:us-west-1::device/qpu/rigetti/Aspen-M-1" 52 | _AspenM2 = "arn:aws:braket:us-west-1::device/qpu/rigetti/Aspen-M-2" 53 | _AspenM3 = "arn:aws:braket:us-west-1::device/qpu/rigetti/Aspen-M-3" 54 | _Ankaa2 = "arn:aws:braket:us-west-1::device/qpu/rigetti/Ankaa-2" 55 | Ankaa3 = "arn:aws:braket:us-west-1::device/qpu/rigetti/Ankaa-3" 56 | 57 | class _Xanadu(str, Enum): 58 | _Borealis = "arn:aws:braket:us-east-1::device/qpu/xanadu/Borealis" 59 | 60 | Amazon = _Amazon 61 | # DWave = _DWave 62 | IonQ = _IonQ 63 | IQM = _IQM 64 | # OQC = _OQC 65 | QuEra = _QuEra 66 | Rigetti = _Rigetti 67 | # Xanadu = _Xanadu 68 | -------------------------------------------------------------------------------- /src/braket/error_mitigation/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket.error_mitigation.debias import Debias # noqa: F401 15 | from braket.error_mitigation.error_mitigation import ErrorMitigation # noqa: F401 16 | -------------------------------------------------------------------------------- /src/braket/error_mitigation/debias.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket.device_schema import error_mitigation 15 | 16 | from braket.error_mitigation.error_mitigation import ErrorMitigation 17 | 18 | 19 | class Debias(ErrorMitigation): 20 | """The debias error mitigation scheme. This scheme takes no parameters.""" 21 | 22 | def serialize(self) -> list[error_mitigation.Debias]: 23 | return [error_mitigation.Debias()] 24 | -------------------------------------------------------------------------------- /src/braket/error_mitigation/error_mitigation.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket.device_schema import error_mitigation 15 | 16 | 17 | class ErrorMitigation: 18 | def serialize(self) -> list[error_mitigation.ErrorMitigationScheme]: 19 | """This returns a list of service-readable error mitigation 20 | scheme descriptions. 21 | 22 | Returns: 23 | list[ErrorMitigationScheme]: A list of service-readable error 24 | mitigation scheme descriptions. 25 | 26 | Raises: 27 | NotImplementedError: Not implemented in the base class. 28 | """ 29 | raise NotImplementedError("serialize is not implemented.") 30 | -------------------------------------------------------------------------------- /src/braket/ipython_utils.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | import sys 15 | 16 | 17 | def running_in_jupyter() -> bool: 18 | """Determine if running within Jupyter. 19 | 20 | Inspired by https://github.com/ipython/ipython/issues/11694 21 | 22 | Returns: 23 | bool: True if running in Jupyter, else False. 24 | """ 25 | in_ipython = False 26 | # if IPython hasn't been imported, there's nothing to check 27 | if "IPython" in sys.modules: 28 | get_ipython = sys.modules["IPython"].__dict__["get_ipython"] 29 | 30 | ip = get_ipython() 31 | in_ipython = ip is not None 32 | 33 | return getattr(ip, "kernel", None) is not None if in_ipython else False 34 | -------------------------------------------------------------------------------- /src/braket/jobs/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket.jobs.config import ( # noqa: F401 15 | CheckpointConfig, 16 | InstanceConfig, 17 | OutputDataConfig, 18 | S3DataSourceConfig, 19 | StoppingCondition, 20 | ) 21 | from braket.jobs.data_persistence import ( # noqa: F401 22 | load_job_checkpoint, 23 | load_job_result, 24 | save_job_checkpoint, 25 | save_job_result, 26 | ) 27 | from braket.jobs.environment_variables import ( # noqa: F401 28 | get_checkpoint_dir, 29 | get_hyperparameters, 30 | get_input_data_dir, 31 | get_job_device_arn, 32 | get_job_name, 33 | get_results_dir, 34 | ) 35 | from braket.jobs.hybrid_job import hybrid_job # noqa: F401 36 | from braket.jobs.image_uris import Framework, retrieve_image # noqa: F401 37 | -------------------------------------------------------------------------------- /src/braket/jobs/_entry_point_template.py: -------------------------------------------------------------------------------- 1 | run_entry_point = """ 2 | import cloudpickle 3 | import os 4 | from braket.jobs import get_results_dir, save_job_result 5 | from braket.jobs_data import PersistedJobDataFormat 6 | 7 | 8 | # load and run serialized entry point function 9 | recovered = cloudpickle.loads({serialized}) 10 | def {function_name}(): 11 | try: 12 | # set working directory to results dir 13 | os.chdir(get_results_dir()) 14 | 15 | # create symlinks to input data 16 | links = link_input() 17 | 18 | result = recovered() 19 | finally: 20 | clean_links(links) 21 | if result is not None: 22 | save_job_result(result, data_format=PersistedJobDataFormat.PICKLED_V4) 23 | return result 24 | """ 25 | 26 | symlink_input_data = ''' 27 | from pathlib import Path 28 | from braket.jobs import get_input_data_dir 29 | 30 | 31 | def make_link(input_link_path, input_data_path, links): 32 | """ Create symlink from input_link_path to input_data_path. """ 33 | input_link_path.parent.mkdir(parents=True, exist_ok=True) 34 | input_link_path.symlink_to(input_data_path) 35 | print(input_link_path, '->', input_data_path) 36 | links[input_link_path] = input_data_path 37 | 38 | 39 | def link_input(): 40 | links = {{}} 41 | dirs = set() 42 | # map of data sources to lists of matched local files 43 | prefix_matches = {prefix_matches} 44 | 45 | for channel, data in {input_data_items}: 46 | 47 | if channel in {prefix_channels}: 48 | # link all matched files 49 | for input_link_name in prefix_matches[channel]: 50 | input_link_path = Path(input_link_name) 51 | input_data_path = Path(get_input_data_dir(channel)) / input_link_path.name 52 | make_link(input_link_path, input_data_path, links) 53 | 54 | else: 55 | input_link_path = Path(data) 56 | if channel in {directory_channels}: 57 | # link directory source directly to input channel directory 58 | input_data_path = Path(get_input_data_dir(channel)) 59 | else: 60 | # link file source to file within input channel directory 61 | input_data_path = Path(get_input_data_dir(channel), Path(data).name) 62 | make_link(input_link_path, input_data_path, links) 63 | 64 | return links 65 | 66 | 67 | def clean_links(links): 68 | for link, target in links.items(): 69 | if link.is_symlink and link.readlink() == target: 70 | link.unlink() 71 | 72 | if link.is_relative_to(Path()): 73 | for dir in link.parents[:-1]: 74 | try: 75 | dir.rmdir() 76 | except: 77 | # directory not empty 78 | pass 79 | ''' 80 | -------------------------------------------------------------------------------- /src/braket/jobs/config.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from __future__ import annotations 15 | 16 | from dataclasses import dataclass 17 | 18 | 19 | @dataclass 20 | class CheckpointConfig: 21 | """Configuration that specifies the location where checkpoint data is stored.""" 22 | 23 | localPath: str = "/opt/jobs/checkpoints" 24 | s3Uri: str | None = None 25 | 26 | 27 | @dataclass 28 | class InstanceConfig: 29 | """Configuration of the instance(s) used to run the hybrid job.""" 30 | 31 | instanceType: str = "ml.m5.large" 32 | volumeSizeInGb: int = 30 33 | instanceCount: int = 1 34 | 35 | 36 | @dataclass 37 | class OutputDataConfig: 38 | """Configuration that specifies the location for the output of the hybrid job.""" 39 | 40 | s3Path: str | None = None 41 | kmsKeyId: str | None = None 42 | 43 | 44 | @dataclass 45 | class StoppingCondition: 46 | """Conditions that specify when the hybrid job should be forcefully stopped.""" 47 | 48 | maxRuntimeInSeconds: int = 5 * 24 * 60 * 60 49 | 50 | 51 | @dataclass 52 | class DeviceConfig: 53 | device: str 54 | 55 | 56 | class S3DataSourceConfig: 57 | """Data source for data that lives on S3. 58 | 59 | Attributes: 60 | config (dict[str, dict]): config passed to the Braket API 61 | """ 62 | 63 | def __init__( 64 | self, 65 | s3_data: str, 66 | content_type: str | None = None, 67 | ): 68 | """Create a definition for input data used by a Braket Hybrid job. 69 | 70 | Args: 71 | s3_data (str): Defines the location of s3 data to train on. 72 | content_type (str | None): MIME type of the input data (default: None). 73 | """ 74 | self.config = { 75 | "dataSource": { 76 | "s3DataSource": { 77 | "s3Uri": s3_data, 78 | } 79 | } 80 | } 81 | 82 | if content_type is not None: 83 | self.config["contentType"] = content_type 84 | -------------------------------------------------------------------------------- /src/braket/jobs/environment_variables.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | import json 15 | import os 16 | 17 | 18 | def get_job_name() -> str: 19 | """Get the name of the current job. 20 | 21 | Returns: 22 | str: The name of the job if in a job, else an empty string. 23 | """ 24 | return os.getenv("AMZN_BRAKET_JOB_NAME", "") 25 | 26 | 27 | def get_job_device_arn() -> str: 28 | """Get the device ARN of the current job. If not in a job, default to "local:none/none". 29 | 30 | Returns: 31 | str: The device ARN of the current job or "local:none/none". 32 | """ 33 | return os.getenv("AMZN_BRAKET_DEVICE_ARN", "local:none/none") 34 | 35 | 36 | def get_input_data_dir(channel: str = "input") -> str: 37 | """Get the job input data directory. 38 | 39 | Args: 40 | channel (str): The name of the input channel. Default value 41 | corresponds to the default input channel name, `input`. 42 | 43 | Returns: 44 | str: The input directory, defaulting to current working directory. 45 | """ 46 | input_dir = os.getenv("AMZN_BRAKET_INPUT_DIR", ".") 47 | return f"{input_dir}/{channel}" if input_dir != "." else input_dir 48 | 49 | 50 | def get_results_dir() -> str: 51 | """Get the job result directory. 52 | 53 | Returns: 54 | str: The results directory, defaulting to current working directory. 55 | """ 56 | return os.getenv("AMZN_BRAKET_JOB_RESULTS_DIR", ".") 57 | 58 | 59 | def get_checkpoint_dir() -> str: 60 | """Get the job checkpoint directory. 61 | 62 | Returns: 63 | str: The checkpoint directory, defaulting to current working directory. 64 | """ 65 | return os.getenv("AMZN_BRAKET_CHECKPOINT_DIR", ".") 66 | 67 | 68 | def get_hyperparameters() -> dict[str, str]: 69 | """Get the job hyperparameters as a dict, with the values stringified. 70 | 71 | Returns: 72 | dict[str, str]: The hyperparameters of the job. 73 | """ 74 | if "AMZN_BRAKET_HP_FILE" in os.environ: 75 | with open(os.getenv("AMZN_BRAKET_HP_FILE"), encoding="utf-8") as f: 76 | return json.load(f) 77 | return {} 78 | -------------------------------------------------------------------------------- /src/braket/jobs/image_uri_config/base.json: -------------------------------------------------------------------------------- 1 | { 2 | "registry": "292282985366", 3 | "repository": "amazon-braket-base-jobs", 4 | "supported_regions": [ 5 | "us-east-1", 6 | "us-west-1", 7 | "us-west-2", 8 | "eu-west-2", 9 | "eu-north-1" 10 | ] 11 | } 12 | -------------------------------------------------------------------------------- /src/braket/jobs/image_uri_config/pl_pytorch.json: -------------------------------------------------------------------------------- 1 | { 2 | "registry": "292282985366", 3 | "repository": "amazon-braket-pytorch-jobs", 4 | "supported_regions": [ 5 | "us-east-1", 6 | "us-west-1", 7 | "us-west-2", 8 | "eu-west-2", 9 | "eu-north-1" 10 | ] 11 | } 12 | -------------------------------------------------------------------------------- /src/braket/jobs/image_uri_config/pl_tensorflow.json: -------------------------------------------------------------------------------- 1 | { 2 | "registry": "292282985366", 3 | "repository": "amazon-braket-tensorflow-jobs", 4 | "supported_regions": [ 5 | "us-east-1", 6 | "us-west-1", 7 | "us-west-2", 8 | "eu-west-2", 9 | "eu-north-1" 10 | ] 11 | } 12 | -------------------------------------------------------------------------------- /src/braket/jobs/local/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket.jobs.local.local_job import LocalQuantumJob # noqa: F401 15 | -------------------------------------------------------------------------------- /src/braket/jobs/metrics.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | from __future__ import annotations 14 | 15 | import time 16 | 17 | 18 | def log_metric( 19 | metric_name: str, 20 | value: float, 21 | timestamp: float | None = None, 22 | iteration_number: int | None = None, 23 | ) -> None: 24 | """Records Braket Hybrid Job metrics. 25 | 26 | Args: 27 | metric_name (str): The name of the metric. 28 | 29 | value (float): The value of the metric. 30 | 31 | timestamp (float | None): The time the metric data was received, expressed 32 | as the number of seconds since the epoch. Default: Current system time. 33 | 34 | iteration_number (int | None): The iteration number of the metric. 35 | """ 36 | logged_timestamp = timestamp or time.time() 37 | metric_list = [f"Metrics - timestamp={logged_timestamp}; {metric_name}={value};"] 38 | if iteration_number is not None: 39 | metric_list.append(f" iteration_number={iteration_number};") 40 | metric_line = "".join(metric_list) 41 | print(metric_line) 42 | -------------------------------------------------------------------------------- /src/braket/jobs/metrics_data/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket.jobs.metrics_data.cwl_metrics_fetcher import CwlMetricsFetcher # noqa: F401 15 | from braket.jobs.metrics_data.definitions import MetricPeriod, MetricStatistic # noqa: F401 16 | from braket.jobs.metrics_data.exceptions import MetricsRetrievalError # noqa: F401 17 | from braket.jobs.metrics_data.log_metrics_parser import LogMetricsParser # noqa: F401 18 | -------------------------------------------------------------------------------- /src/braket/jobs/metrics_data/definitions.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | from enum import Enum, unique 14 | 15 | 16 | @unique 17 | class MetricPeriod(Enum): 18 | """Period over which the cloudwatch metric is aggregated.""" 19 | 20 | ONE_MINUTE: int = 60 21 | 22 | 23 | @unique 24 | class MetricStatistic(Enum): 25 | """Metric data aggregation to use over the specified period.""" 26 | 27 | MIN: str = "Min" 28 | MAX: str = "Max" 29 | 30 | 31 | @unique 32 | class MetricType(Enum): 33 | """Metric type.""" 34 | 35 | TIMESTAMP: str = "Timestamp" 36 | ITERATION_NUMBER: str = "IterationNumber" 37 | -------------------------------------------------------------------------------- /src/braket/jobs/metrics_data/exceptions.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | 15 | class MetricsRetrievalError(Exception): 16 | """Raised when retrieving metrics fails.""" 17 | -------------------------------------------------------------------------------- /src/braket/jobs/serialization.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | import codecs 15 | import pickle 16 | from typing import Any 17 | 18 | from braket.jobs_data import PersistedJobDataFormat 19 | 20 | 21 | def serialize_values( 22 | data_dictionary: dict[str, Any], data_format: PersistedJobDataFormat 23 | ) -> dict[str, Any]: 24 | """Serializes the `data_dictionary` values to the format specified by `data_format`. 25 | 26 | Args: 27 | data_dictionary (dict[str, Any]): Dict whose values are to be serialized. 28 | data_format (PersistedJobDataFormat): The data format used to serialize the 29 | values. Note that for `PICKLED` data formats, the values are base64 encoded 30 | after serialization, so that they represent valid UTF-8 text and are compatible 31 | with `PersistedJobData.json()`. 32 | 33 | Returns: 34 | dict[str, Any]: Dict with same keys as `data_dictionary` and values serialized to 35 | the specified `data_format`. 36 | """ 37 | return ( 38 | { 39 | k: codecs.encode(pickle.dumps(v, protocol=4), "base64").decode() 40 | for k, v in data_dictionary.items() 41 | } 42 | if data_format == PersistedJobDataFormat.PICKLED_V4 43 | else data_dictionary 44 | ) 45 | 46 | 47 | def deserialize_values( 48 | data_dictionary: dict[str, Any], data_format: PersistedJobDataFormat 49 | ) -> dict[str, Any]: 50 | """Deserializes the `data_dictionary` values from the format specified by `data_format`. 51 | 52 | Args: 53 | data_dictionary (dict[str, Any]): Dict whose values are to be deserialized. 54 | data_format (PersistedJobDataFormat): The data format that the `data_dictionary` values 55 | are currently serialized with. 56 | 57 | Returns: 58 | dict[str, Any]: Dict with same keys as `data_dictionary` and values deserialized from 59 | the specified `data_format` to plaintext. 60 | """ 61 | return ( 62 | {k: pickle.loads(codecs.decode(v.encode(), "base64")) for k, v in data_dictionary.items()} # noqa: S301 63 | if data_format == PersistedJobDataFormat.PICKLED_V4 64 | else data_dictionary 65 | ) 66 | -------------------------------------------------------------------------------- /src/braket/parametric/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | 15 | from braket.parametric.free_parameter import FreeParameter # noqa: F401 16 | from braket.parametric.free_parameter_expression import FreeParameterExpression # noqa: F401 17 | from braket.parametric.parameterizable import Parameterizable # noqa: F401 18 | -------------------------------------------------------------------------------- /src/braket/parametric/parameterizable.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from __future__ import annotations 15 | 16 | from abc import ABC, abstractmethod 17 | from typing import Any 18 | 19 | from braket.parametric.free_parameter import FreeParameter 20 | from braket.parametric.free_parameter_expression import FreeParameterExpression 21 | 22 | 23 | class Parameterizable(ABC): 24 | """A parameterized object is the abstract definition of an object 25 | that can take in FreeParameterExpressions. 26 | """ 27 | 28 | @property 29 | @abstractmethod 30 | def parameters(self) -> list[FreeParameterExpression | FreeParameter | float]: 31 | """Get the parameters. 32 | 33 | Returns: 34 | list[Union[FreeParameterExpression, FreeParameter, float]]: The parameters associated 35 | with the object, either unbound free parameter expressions or bound values. The order 36 | of the parameters is determined by the subclass. 37 | """ 38 | 39 | @abstractmethod 40 | def bind_values(self, **kwargs: FreeParameter | str) -> Any: 41 | """Takes in parameters and returns an object with specified parameters 42 | replaced with their values. 43 | 44 | Args: 45 | **kwargs (Union[FreeParameter, str]): Arbitrary keyword arguments. 46 | 47 | Returns: 48 | Any: The result object will depend on the implementation of the object being bound. 49 | """ 50 | -------------------------------------------------------------------------------- /src/braket/pulse/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket.pulse.frame import Frame # noqa: F401 15 | from braket.pulse.port import Port # noqa: F401 16 | from braket.pulse.pulse_sequence import PulseSequence # noqa: F401 17 | from braket.pulse.waveforms import ( 18 | ArbitraryWaveform, # noqa: F401 19 | ConstantWaveform, # noqa: F401 20 | DragGaussianWaveform, # noqa: F401 21 | ErfSquareWaveform, # noqa: F401 22 | GaussianWaveform, # noqa: F401 23 | ) 24 | -------------------------------------------------------------------------------- /src/braket/pulse/ast/qasm_parser.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | import io 15 | 16 | from openpulse import ast 17 | from openpulse.printer import Printer 18 | from openqasm3.printer import PrinterState 19 | 20 | 21 | class _PulsePrinter(Printer): 22 | """Walks the AST and prints it to an OpenQASM3 string.""" 23 | 24 | def __init__(self, *args, **kwargs): 25 | super().__init__(*args, **kwargs) 26 | 27 | def visit_Identifier(self, node: ast.Identifier, context: PrinterState) -> None: 28 | """Visit an Identifier. 29 | Args: 30 | node (ast.Identifier): The identifier. 31 | context (PrinterState): The printer state context. 32 | """ 33 | self.stream.write(str(node.name)) 34 | 35 | def visit_ClassicalDeclaration( 36 | self, node: ast.ClassicalDeclaration, context: PrinterState 37 | ) -> None: 38 | """Visit a Classical Declaration. 39 | node.type, node.identifier, node.init_expression 40 | angle[20] a = 1+2; 41 | waveform wf = []; 42 | port a; 43 | 44 | Args: 45 | node (ast.ClassicalDeclaration): The classical declaration. 46 | context (PrinterState): The printer state context. 47 | """ 48 | # Skip port declarations in output 49 | if not isinstance(node.type, ast.PortType): 50 | super().visit_ClassicalDeclaration(node, context) 51 | 52 | 53 | def ast_to_qasm(ast: ast.Program) -> str: 54 | """Converts an AST program to OpenQASM 55 | 56 | Args: 57 | ast (ast.Program): The AST program. 58 | 59 | Returns: 60 | str: a str representing the OpenPulse program encoding the program. 61 | """ 62 | out = io.StringIO() 63 | _PulsePrinter(out, indent=" ").visit(ast) 64 | return out.getvalue().strip() 65 | -------------------------------------------------------------------------------- /src/braket/pulse/ast/qasm_transformer.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from typing import Any, Optional 15 | 16 | from openpulse import ast 17 | from openqasm3.visitor import QASMTransformer 18 | 19 | 20 | class _IRQASMTransformer(QASMTransformer): 21 | """QASMTransformer which walks the AST and makes the necessary modifications needed 22 | for IR generation. Currently, it performs the following operations: 23 | * Replaces capture_v0 function calls with assignment statements, assigning the 24 | readout value to a bit register element. 25 | """ 26 | 27 | def __init__(self, register_identifier: Optional[str] = None): 28 | self._register_identifier = register_identifier 29 | self._capture_v0_count = 0 30 | super().__init__() 31 | 32 | def visit_ExpressionStatement(self, expression_statement: ast.ExpressionStatement) -> Any: 33 | """Visit an Expression. 34 | 35 | Args: 36 | expression_statement (ast.ExpressionStatement): The expression statement. 37 | 38 | Returns: 39 | Any: The expression statement. 40 | """ 41 | if ( 42 | not isinstance(expression_statement.expression, ast.FunctionCall) 43 | or expression_statement.expression.name.name != "capture_v0" 44 | or not self._register_identifier 45 | ): 46 | return expression_statement 47 | # For capture_v0 nodes, it replaces it with classical assignment statements 48 | # of the form: 49 | # b[0] = capture_v0(...) 50 | # b[1] = capture_v0(...) 51 | new_val = ast.ClassicalAssignment( 52 | # Ideally should use IndexedIdentifier here, but this works since it is just 53 | # for printing. 54 | ast.Identifier(name=f"{self._register_identifier}[{self._capture_v0_count}]"), 55 | ast.AssignmentOperator["="], 56 | expression_statement.expression, 57 | ) 58 | self._capture_v0_count += 1 59 | return new_val 60 | -------------------------------------------------------------------------------- /src/braket/pulse/frame.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from __future__ import annotations 15 | 16 | import math 17 | from typing import Any 18 | 19 | from oqpy import FrameVar as OQFrame 20 | from oqpy.base import OQPyExpression 21 | 22 | from braket.pulse.port import Port 23 | 24 | 25 | class Frame: 26 | """Frame tracks the frame of reference, when interacting with the qubits, throughout the 27 | execution of a program. See https://openqasm.com/language/openpulse.html#frames for more 28 | details. 29 | """ 30 | 31 | def __init__( 32 | self, 33 | frame_id: str, 34 | port: Port, 35 | frequency: float, 36 | phase: float = 0, 37 | is_predefined: bool = False, 38 | properties: dict[str, Any] | None = None, 39 | ): 40 | """Initializes a Frame. 41 | 42 | Args: 43 | frame_id (str): str identifying a unique frame. 44 | port (Port): port that this frame is attached to. 45 | frequency (float): frequency to which this frame should be initialized. 46 | phase (float): phase to which this frame should be initialized. Defaults to 0. 47 | is_predefined (bool): bool indicating whether this is a predefined frame on 48 | the device. Defaults to False. 49 | properties (Optional[dict[str, Any]]): Dict containing properties of this frame. 50 | Defaults to None. 51 | """ 52 | self._frame_id = frame_id 53 | self.port = port 54 | self.frequency = frequency 55 | self.phase = phase 56 | self.is_predefined = is_predefined 57 | self.properties = properties 58 | 59 | @property 60 | def id(self) -> str: 61 | """Returns a str indicating the frame id.""" 62 | return self._frame_id 63 | 64 | def __eq__(self, other: Frame) -> bool: 65 | return ( 66 | ( 67 | (self.id == other.id) 68 | and (self.port == other.port) 69 | and math.isclose(self.frequency, other.frequency) 70 | and math.isclose(self.phase, other.phase) 71 | ) 72 | if isinstance(other, Frame) 73 | else False 74 | ) 75 | 76 | def _to_oqpy_expression(self) -> OQPyExpression: 77 | return OQFrame( 78 | port=self.port._to_oqpy_expression(), 79 | frequency=self.frequency, 80 | phase=self.phase, 81 | name=self.id, 82 | needs_declaration=not self.is_predefined, 83 | ) 84 | -------------------------------------------------------------------------------- /src/braket/pulse/port.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from __future__ import annotations 15 | 16 | from typing import Any 17 | 18 | from oqpy import PortVar 19 | from oqpy.base import OQPyExpression 20 | 21 | 22 | class Port: 23 | """Ports represent any input or output component meant to manipulate and observe qubits on 24 | a device. See https://openqasm.com/language/openpulse.html#ports for more details. 25 | """ 26 | 27 | def __init__(self, port_id: str, dt: float, properties: dict[str, Any] | None = None): 28 | """Initializes a Port. 29 | 30 | Args: 31 | port_id (str): str identifying a unique port on the device. 32 | dt (float): The smallest time step that may be used on the control hardware. 33 | properties (Optional[dict[str, Any]]): Dict containing properties of 34 | this port. Defaults to None. 35 | """ 36 | self._port_id = port_id 37 | self._dt = dt 38 | self.properties = properties 39 | 40 | @property 41 | def id(self) -> str: 42 | """Returns a str indicating the port id.""" 43 | return self._port_id 44 | 45 | @property 46 | def dt(self) -> float: 47 | """Returns the smallest time step that may be used on the control hardware.""" 48 | return self._dt 49 | 50 | def __eq__(self, other: Port) -> bool: 51 | return self.id == other.id if isinstance(other, Port) else False 52 | 53 | def _to_oqpy_expression(self) -> OQPyExpression: 54 | return PortVar(name=self.id) 55 | -------------------------------------------------------------------------------- /src/braket/pulse/pulse_sequence_trace.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from __future__ import annotations 15 | 16 | from dataclasses import dataclass 17 | 18 | from braket.timings.time_series import TimeSeries 19 | 20 | 21 | @dataclass 22 | class PulseSequenceTrace: 23 | """This class encapsulates the data representing the PulseSequence execution. It contains 24 | the trace of amplitude, frequency and phase information for each frame in the 25 | PulseSequence. 26 | 27 | Args: 28 | amplitudes (dict): A dictionary of frame ID to a TimeSeries of complex values specifying 29 | the waveform amplitude. 30 | frequencies (dict):A dictionary of frame ID to a TimeSeries of float values specifying 31 | the waveform frequency. 32 | phases (dict):A dictionary of frame ID to a TimeSeries of float values specifying 33 | the waveform phase. 34 | """ 35 | 36 | amplitudes: dict[str, TimeSeries] 37 | frequencies: dict[str, TimeSeries] 38 | phases: dict[str, TimeSeries] 39 | -------------------------------------------------------------------------------- /src/braket/quantum_information/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket.quantum_information.pauli_string import PauliString # noqa: F401 15 | -------------------------------------------------------------------------------- /src/braket/registers/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket.registers.qubit import Qubit, QubitInput # noqa: F401 15 | from braket.registers.qubit_set import QubitSet, QubitSetInput # noqa: F401 16 | -------------------------------------------------------------------------------- /src/braket/registers/qubit.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from __future__ import annotations 15 | 16 | import numbers 17 | from typing import Union 18 | 19 | QubitInput = Union["Qubit", int] 20 | 21 | 22 | class Qubit(int): 23 | """A quantum bit index. The index of this qubit is locally scoped towards the contained 24 | circuit. This may not be the exact qubit index on the quantum device. 25 | """ 26 | 27 | def __new__(cls, index: int) -> Qubit: 28 | """Creates a new `Qubit`. 29 | 30 | Args: 31 | index (int): Index of the qubit. 32 | 33 | Raises: 34 | ValueError: If `index` is less than zero. 35 | 36 | Returns: 37 | Qubit: Returns a new Qubit object. 38 | 39 | Examples: 40 | >>> Qubit(0) 41 | >>> Qubit(1) 42 | """ 43 | if not isinstance(index, numbers.Integral): 44 | raise TypeError(f"Supplied qubit index, {index}, must be an integer.") 45 | if index < 0: 46 | raise ValueError(f"Supplied qubit index, {index}, cannot be less than zero.") 47 | return super().__new__(cls, index) 48 | 49 | def __repr__(self): 50 | return f"Qubit({super().__repr__()})" 51 | 52 | def __str__(self): 53 | return self.__repr__() 54 | 55 | @staticmethod 56 | def new(qubit: QubitInput) -> Qubit: 57 | """Helper constructor - if input is a `Qubit` it returns the same value, 58 | else a new `Qubit` is constructed. 59 | 60 | Args: 61 | qubit (QubitInput): `Qubit` index. If `type == Qubit` then the `qubit` is returned. 62 | 63 | Returns: 64 | Qubit: The qubit. 65 | """ 66 | return qubit if isinstance(qubit, Qubit) else Qubit(qubit) 67 | -------------------------------------------------------------------------------- /src/braket/tasks/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket import ipython_utils 15 | from braket.tasks.analog_hamiltonian_simulation_quantum_task_result import ( # noqa: F401 16 | AnalogHamiltonianSimulationQuantumTaskResult, 17 | AnalogHamiltonianSimulationShotStatus, 18 | ) 19 | from braket.tasks.annealing_quantum_task_result import AnnealingQuantumTaskResult # noqa: F401 20 | from braket.tasks.gate_model_quantum_task_result import GateModelQuantumTaskResult # noqa: F401 21 | from braket.tasks.photonic_model_quantum_task_result import ( 22 | PhotonicModelQuantumTaskResult, # noqa: F401 23 | ) 24 | from braket.tasks.quantum_task import QuantumTask # noqa: F401 25 | from braket.tasks.quantum_task_batch import QuantumTaskBatch # noqa: F401 26 | 27 | # Apply nest_asyncio if currently running within Jupyter. This ensures anything that uses 28 | # asyncio will run in Jupyter without any issues. 29 | # 30 | # Inspired by https://github.com/ipython/ipython/issues/11694 and 31 | # https://github.com/jupyter/notebook/issues/3397#issuecomment-419386811 32 | if ipython_utils.running_in_jupyter(): 33 | import nest_asyncio 34 | 35 | nest_asyncio.apply() 36 | -------------------------------------------------------------------------------- /src/braket/tasks/local_quantum_task.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | from __future__ import annotations 14 | 15 | import asyncio 16 | 17 | from braket.tasks import ( 18 | AnnealingQuantumTaskResult, 19 | GateModelQuantumTaskResult, 20 | PhotonicModelQuantumTaskResult, 21 | QuantumTask, 22 | ) 23 | 24 | 25 | class LocalQuantumTask(QuantumTask): 26 | """A quantum task containing the results of a local simulation. 27 | 28 | Since this class is instantiated with the results, cancel() and run_async() are unsupported. 29 | """ 30 | 31 | def __init__( 32 | self, 33 | result: GateModelQuantumTaskResult 34 | | AnnealingQuantumTaskResult 35 | | PhotonicModelQuantumTaskResult, 36 | ): 37 | self._id = result.task_metadata.id 38 | self._result = result 39 | 40 | @property 41 | def id(self) -> str: 42 | """Gets the task ID. 43 | 44 | Returns: 45 | str: The ID of the task. 46 | """ 47 | return str(self._id) 48 | 49 | def cancel(self) -> None: 50 | """Cancel the quantum task.""" 51 | raise NotImplementedError("Cannot cancel completed local task") 52 | 53 | def state(self) -> str: 54 | """Gets the state of the task. 55 | 56 | Returns: 57 | str: Returns COMPLETED 58 | """ 59 | return "COMPLETED" 60 | 61 | def result( 62 | self, 63 | ) -> GateModelQuantumTaskResult | AnnealingQuantumTaskResult | PhotonicModelQuantumTaskResult: 64 | return self._result 65 | 66 | def async_result(self) -> asyncio.Task: 67 | """Get the quantum task result asynchronously. 68 | 69 | Raises: 70 | NotImplementedError: Asynchronous local simulation unsupported 71 | 72 | Returns: 73 | asyncio.Task: Get the quantum task result asynchronously. 74 | """ 75 | # TODO: Allow for asynchronous simulation 76 | raise NotImplementedError("Asynchronous local simulation unsupported") 77 | 78 | def __repr__(self) -> str: 79 | return f"LocalQuantumTask('id':{self.id})" 80 | -------------------------------------------------------------------------------- /src/braket/tasks/local_quantum_task_batch.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from typing import Union 15 | 16 | from braket.tasks import ( 17 | AnnealingQuantumTaskResult, 18 | GateModelQuantumTaskResult, 19 | PhotonicModelQuantumTaskResult, 20 | QuantumTaskBatch, 21 | ) 22 | 23 | 24 | class LocalQuantumTaskBatch(QuantumTaskBatch): 25 | """Executes a batch of quantum tasks in parallel. 26 | 27 | Since this class is instantiated with the results, cancel() and run_async() are unsupported. 28 | """ 29 | 30 | def __init__( 31 | self, 32 | results: list[ 33 | Union[ 34 | GateModelQuantumTaskResult, 35 | AnnealingQuantumTaskResult, 36 | PhotonicModelQuantumTaskResult, 37 | ] 38 | ], 39 | ): 40 | self._results = results 41 | 42 | def results( 43 | self, 44 | ) -> list[ 45 | Union[ 46 | GateModelQuantumTaskResult, AnnealingQuantumTaskResult, PhotonicModelQuantumTaskResult 47 | ] 48 | ]: 49 | return self._results 50 | -------------------------------------------------------------------------------- /src/braket/tasks/photonic_model_quantum_task_result.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from __future__ import annotations 15 | 16 | from dataclasses import dataclass 17 | 18 | import numpy as np 19 | from braket.task_result import AdditionalMetadata, PhotonicModelTaskResult, TaskMetadata 20 | 21 | 22 | @dataclass 23 | class PhotonicModelQuantumTaskResult: 24 | task_metadata: TaskMetadata 25 | additional_metadata: AdditionalMetadata 26 | measurements: np.ndarray = None 27 | 28 | def __eq__(self, other: PhotonicModelQuantumTaskResult) -> bool: 29 | if isinstance(other, PhotonicModelQuantumTaskResult): 30 | return self.task_metadata.id == other.task_metadata.id 31 | return NotImplemented 32 | 33 | @staticmethod 34 | def from_object(result: PhotonicModelTaskResult) -> PhotonicModelQuantumTaskResult: 35 | """Create PhotonicModelQuantumTaskResult from PhotonicModelTaskResult object. 36 | 37 | Args: 38 | result (PhotonicModelTaskResult): PhotonicModelTaskResult object 39 | 40 | Returns: 41 | PhotonicModelQuantumTaskResult: A PhotonicModelQuantumTaskResult based on the given dict 42 | 43 | Raises: 44 | ValueError: If "measurements" is not a key in the result dict 45 | """ 46 | return PhotonicModelQuantumTaskResult._from_object_internal(result) 47 | 48 | @staticmethod 49 | def from_string(result: str) -> PhotonicModelQuantumTaskResult: 50 | return PhotonicModelQuantumTaskResult._from_object_internal( 51 | PhotonicModelTaskResult.parse_raw(result) 52 | ) 53 | 54 | @classmethod 55 | def _from_object_internal( 56 | cls, result: PhotonicModelTaskResult 57 | ) -> PhotonicModelQuantumTaskResult: 58 | task_metadata = result.taskMetadata 59 | additional_metadata = result.additionalMetadata 60 | if result.measurements is not None: 61 | measurements = np.asarray(result.measurements, dtype=int) 62 | else: 63 | measurements = None 64 | return cls( 65 | task_metadata=task_metadata, 66 | additional_metadata=additional_metadata, 67 | measurements=measurements, 68 | ) 69 | -------------------------------------------------------------------------------- /src/braket/tasks/quantum_task.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | import asyncio 15 | from abc import ABC, abstractmethod 16 | from typing import Any, Union 17 | 18 | from braket.tasks.annealing_quantum_task_result import AnnealingQuantumTaskResult 19 | from braket.tasks.gate_model_quantum_task_result import GateModelQuantumTaskResult 20 | from braket.tasks.photonic_model_quantum_task_result import PhotonicModelQuantumTaskResult 21 | 22 | 23 | class QuantumTask(ABC): 24 | """An abstraction over a quantum task on a quantum device.""" 25 | 26 | @property 27 | @abstractmethod 28 | def id(self) -> str: 29 | """Get the quantum task ID. 30 | 31 | Returns: 32 | str: The quantum task ID. 33 | """ 34 | 35 | @abstractmethod 36 | def cancel(self) -> None: 37 | """Cancel the quantum task.""" 38 | 39 | @abstractmethod 40 | def state(self) -> str: 41 | """Get the state of the quantum task. 42 | 43 | Returns: 44 | str: State of the quantum task. 45 | """ 46 | 47 | @abstractmethod 48 | def result( 49 | self, 50 | ) -> Union[ 51 | GateModelQuantumTaskResult, AnnealingQuantumTaskResult, PhotonicModelQuantumTaskResult 52 | ]: 53 | """Get the quantum task result. 54 | 55 | Returns: 56 | Union[GateModelQuantumTaskResult, AnnealingQuantumTaskResult, PhotonicModelQuantumTaskResult]: Get 57 | the quantum task result. Call async_result if you want the result in an 58 | asynchronous way. 59 | """ # noqa: E501 60 | 61 | @abstractmethod 62 | def async_result(self) -> asyncio.Task: 63 | """Get the quantum task result asynchronously. 64 | 65 | Returns: 66 | asyncio.Task: Get the quantum task result asynchronously. 67 | """ 68 | 69 | def metadata(self, use_cached_value: bool = False) -> dict[str, Any]: # noqa: B027 70 | """Get task metadata. 71 | 72 | Args: 73 | use_cached_value (bool): If True, uses the value retrieved from the previous 74 | request. Default is False. 75 | 76 | Returns: 77 | dict[str, Any]: The metadata regarding the quantum task. If `use_cached_value` is True, 78 | then the value retrieved from the most recent request is used. 79 | """ 80 | -------------------------------------------------------------------------------- /src/braket/tasks/quantum_task_batch.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from abc import ABC, abstractmethod 15 | from typing import Union 16 | 17 | from braket.tasks.annealing_quantum_task_result import AnnealingQuantumTaskResult 18 | from braket.tasks.gate_model_quantum_task_result import GateModelQuantumTaskResult 19 | from braket.tasks.photonic_model_quantum_task_result import PhotonicModelQuantumTaskResult 20 | 21 | 22 | class QuantumTaskBatch(ABC): 23 | """An abstraction over a quantum task batch on a quantum device.""" 24 | 25 | @abstractmethod 26 | def results( 27 | self, 28 | ) -> list[ 29 | Union[ 30 | GateModelQuantumTaskResult, AnnealingQuantumTaskResult, PhotonicModelQuantumTaskResult 31 | ] 32 | ]: 33 | """Get the quantum task results. 34 | 35 | Returns: 36 | list[Union[GateModelQuantumTaskResult, AnnealingQuantumTaskResult, PhotonicModelQuantumTaskResult]]: Get 37 | the quantum task results. 38 | """ # noqa: E501 39 | -------------------------------------------------------------------------------- /src/braket/timings/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket.timings.time_series import TimeSeries, TimeSeriesItem # noqa: F401 15 | -------------------------------------------------------------------------------- /src/braket/tracking/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket.tracking.tracker import Tracker # noqa: F401 15 | -------------------------------------------------------------------------------- /src/braket/tracking/pricing.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from __future__ import annotations 15 | 16 | import csv 17 | import io 18 | import os 19 | from functools import lru_cache 20 | 21 | import urllib3 22 | 23 | 24 | class Pricing: 25 | def __init__(self): 26 | self._price_list = [] 27 | 28 | def get_prices(self) -> None: 29 | """Retrieves the price list.""" 30 | # Using AWS Pricing Bulk API. Format for the response is described at 31 | # https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/reading-an-offer.html 32 | 33 | http = urllib3.PoolManager() 34 | price_url = os.environ.get( 35 | "BRAKET_PRICE_OFFERS_URL", 36 | "https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonBraket/current/index.csv", 37 | ) 38 | response = http.request( 39 | "GET", 40 | price_url, 41 | preload_content=False, 42 | ) 43 | response.auto_close = False 44 | 45 | text_response = io.TextIOWrapper(response, encoding="utf-8") 46 | 47 | # Data starts on line 6 48 | # 49 | # > The first five rows of the CSV are the metadata for the offer file. The sixth row has 50 | # > all the column names for the products and their attributes... 51 | # https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/reading-an-offer.html#csv 52 | for _ in range(5): 53 | text_response.readline() 54 | self._price_list = list(csv.DictReader(text_response)) 55 | 56 | @lru_cache # noqa: B019 57 | def price_search(self, **kwargs: str) -> list[dict[str, str]]: 58 | """Searches the price list for a given set of parameters. 59 | 60 | Args: 61 | **kwargs (str): Arbitrary keyword arguments. 62 | 63 | Returns: 64 | list[dict[str, str]]: The price list. 65 | """ 66 | if not self._price_list: 67 | self.get_prices() 68 | return [ 69 | entry for entry in self._price_list if all(entry[k] == v for k, v in kwargs.items()) 70 | ] 71 | 72 | 73 | _pricing = Pricing() 74 | price_search = _pricing.price_search 75 | -------------------------------------------------------------------------------- /src/braket/tracking/tracking_context.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from __future__ import annotations 15 | 16 | 17 | class TrackingContext: 18 | def __init__(self): 19 | self._trackers = set() 20 | 21 | def register_tracker(self, tracker: Tracker) -> None: # noqa: F821 22 | """Registers a tracker. 23 | 24 | Args: 25 | tracker (Tracker): The tracker. 26 | """ 27 | self._trackers.add(tracker) 28 | 29 | def deregister_tracker(self, tracker: Tracker) -> None: # noqa: F821 30 | """Deregisters a tracker. 31 | 32 | Args: 33 | tracker (Tracker): The tracker. 34 | """ 35 | self._trackers.remove(tracker) 36 | 37 | def broadcast_event(self, event: _TrackingEvent) -> None: # noqa: F821 38 | """Broadcasts an event to all trackers. 39 | 40 | Args: 41 | event (_TrackingEvent): The event to broadcast. 42 | """ 43 | for tracker in self._trackers: 44 | tracker.receive_event(event) 45 | 46 | def active_trackers(self) -> set: 47 | """Gets the active trackers. 48 | 49 | Returns: 50 | set: The set of active trackers. 51 | """ 52 | return self._trackers 53 | 54 | 55 | _tracking_context = TrackingContext() 56 | register_tracker = _tracking_context.register_tracker 57 | deregister_tracker = _tracking_context.deregister_tracker 58 | broadcast_event = _tracking_context.broadcast_event 59 | active_trackers = _tracking_context.active_trackers 60 | -------------------------------------------------------------------------------- /src/braket/tracking/tracking_events.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from __future__ import annotations 15 | 16 | from dataclasses import dataclass 17 | 18 | 19 | @dataclass 20 | class _TrackingEvent: 21 | arn: str 22 | 23 | 24 | @dataclass 25 | class _TaskCreationEvent(_TrackingEvent): 26 | shots: int 27 | is_job_task: bool 28 | device: str 29 | 30 | 31 | @dataclass 32 | class _TaskCompletionEvent(_TrackingEvent): 33 | execution_duration: float | None 34 | status: str 35 | has_reservation_arn: bool = False 36 | 37 | 38 | @dataclass 39 | class _TaskStatusEvent(_TrackingEvent): 40 | status: str 41 | -------------------------------------------------------------------------------- /test/integ_tests/job_test_module/job_test_submodule/job_test_submodule_file.py: -------------------------------------------------------------------------------- 1 | def submodule_helper(): 2 | print("import successful!") 3 | return {"status": "SUCCESS"} 4 | -------------------------------------------------------------------------------- /test/integ_tests/job_test_module/job_test_submodule/requirements.txt: -------------------------------------------------------------------------------- 1 | pytest 2 | -------------------------------------------------------------------------------- /test/integ_tests/job_test_script.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from braket.aws import AwsDevice 15 | from braket.circuits import Circuit 16 | from braket.jobs import ( 17 | get_hyperparameters, 18 | get_job_device_arn, 19 | save_job_checkpoint, 20 | save_job_result, 21 | ) 22 | from braket.jobs_data import PersistedJobDataFormat 23 | 24 | 25 | def start_here(): 26 | hyperparameters = get_hyperparameters() 27 | 28 | if hyperparameters["test_case"] == "completed": 29 | completed_job_script() 30 | else: 31 | failed_job_script() 32 | 33 | 34 | def failed_job_script(): 35 | print("Test job started!!!!!") 36 | open("fake_file") 37 | 38 | 39 | def completed_job_script(): 40 | print("Test job started!!!!!") 41 | 42 | # Use the device declared in the Orchestration Script 43 | device = AwsDevice(get_job_device_arn()) 44 | 45 | bell = Circuit().h(0).cnot(0, 1) 46 | for _ in range(3): 47 | task = device.run(bell, shots=10) 48 | print(task.result().measurement_counts) 49 | save_job_result({"converged": True, "energy": -0.2}) 50 | save_job_checkpoint({"some_data": "abc"}, checkpoint_file_suffix="plain_data") 51 | save_job_checkpoint({"some_data": "abc"}, data_format=PersistedJobDataFormat.PICKLED_V4) 52 | 53 | print("Test job completed!!!!!") 54 | 55 | 56 | def job_helper(): 57 | print("import successful!") 58 | return {"status": "SUCCESS"} 59 | -------------------------------------------------------------------------------- /test/integ_tests/job_testing_utils.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | import re 15 | 16 | from braket.aws import AwsSession 17 | from braket.jobs import Framework, retrieve_image 18 | 19 | 20 | def decorator_python_version(): 21 | aws_session = AwsSession() 22 | image_uri = retrieve_image(Framework.BASE, aws_session.region) 23 | tag = aws_session.get_full_image_tag(image_uri) 24 | major_version, minor_version = re.search(r"-py(\d)(\d+)-", tag).groups() 25 | return int(major_version), int(minor_version) 26 | -------------------------------------------------------------------------------- /test/integ_tests/requirements.txt: -------------------------------------------------------------------------------- 1 | pytest 2 | -------------------------------------------------------------------------------- /test/integ_tests/test_aws_session_s3.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | import json 15 | 16 | import pytest 17 | 18 | TEST_S3_OBJ_CONTENTS = { 19 | "TaskMetadata": { 20 | "Id": "blah", 21 | "Status": "COMPLETED", 22 | } 23 | } 24 | 25 | 26 | @pytest.fixture() 27 | def s3_key(s3_resource, s3_bucket, s3_prefix): 28 | obj = s3_resource.Object(s3_bucket, f"{s3_prefix}/test_task_reading.json") 29 | 30 | try: 31 | obj_body = obj.get()["Body"].read().decode("utf-8") 32 | assert obj_body == json.dumps(TEST_S3_OBJ_CONTENTS) 33 | except s3_resource.meta.client.exceptions.NoSuchKey: 34 | # Put s3 object 35 | obj.put(ACL="private", Body=json.dumps(TEST_S3_OBJ_CONTENTS, indent=4)) 36 | except AssertionError: 37 | # Put s3 object 38 | obj.put(ACL="private", Body=json.dumps(TEST_S3_OBJ_CONTENTS, indent=4)) 39 | 40 | return obj.key 41 | 42 | 43 | def test_retrieve_s3_object_body(aws_session, s3_bucket, s3_key): 44 | obj_body = aws_session.retrieve_s3_object_body(s3_bucket, s3_key) 45 | assert obj_body == json.dumps(TEST_S3_OBJ_CONTENTS, indent=4) 46 | -------------------------------------------------------------------------------- /test/integ_tests/test_density_matrix_simulator.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | import numpy as np 4 | import pytest 5 | from gate_model_device_testing_utils import get_tol 6 | 7 | from braket.aws import AwsDevice 8 | from braket.circuits import Circuit, Noise, Observable 9 | 10 | SHOTS = 500 11 | DM1_ARN = "arn:aws:braket:::device/quantum-simulator/amazon/dm1" 12 | SIMULATOR_ARNS = [DM1_ARN] 13 | 14 | 15 | @pytest.mark.parametrize("simulator_arn", SIMULATOR_ARNS) 16 | def test_mixed_states(simulator_arn, aws_session, s3_destination_folder): 17 | num_qubits = 10 18 | circuit = _mixed_states(num_qubits) 19 | device = AwsDevice(simulator_arn, aws_session) 20 | 21 | tol = get_tol(SHOTS) 22 | result = device.run(circuit, shots=SHOTS, s3_destination_folder=s3_destination_folder).result() 23 | probabilities = result.measurement_probabilities 24 | probability_sum = 0 25 | for bitstring in probabilities: 26 | assert probabilities[bitstring] >= 0 27 | probability_sum += probabilities[bitstring] 28 | assert math.isclose(probability_sum, 1, rel_tol=tol["rtol"], abs_tol=tol["atol"]) 29 | assert len(result.measurements) == SHOTS 30 | 31 | 32 | def _mixed_states(n_qubits: int) -> Circuit: 33 | noise = Noise.PhaseFlip(probability=0.2) 34 | circ = Circuit() 35 | for qubit in range(0, n_qubits - 2, 3): 36 | circ.x(qubit).y(qubit + 1).cnot(qubit, qubit + 2).x(qubit + 1).z(qubit + 2) 37 | circ.apply_gate_noise(noise, target_qubits=[qubit, qubit + 2]) 38 | 39 | # attach the result types 40 | circ.probability() 41 | circ.expectation(observable=Observable.Z(), target=0) 42 | 43 | return circ 44 | 45 | 46 | @pytest.mark.parametrize("simulator_arn", SIMULATOR_ARNS) 47 | def test_density_matrix_result_type(simulator_arn): 48 | circ = Circuit().bit_flip(0, 0.2).density_matrix() 49 | device = AwsDevice(simulator_arn) 50 | density_matrix_result = device.run(circ).result().result_types[0].value 51 | assert np.allclose( 52 | density_matrix_result, 53 | [[[0.8, 0.0], [0.0, 0.0]], [[0.0, 0.0], [0.2, 0.0]]], 54 | ) 55 | -------------------------------------------------------------------------------- /test/integ_tests/test_queue_information.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | 15 | from braket.aws import AwsDevice 16 | from braket.aws.queue_information import ( 17 | HybridJobQueueInfo, 18 | QuantumTaskQueueInfo, 19 | QueueDepthInfo, 20 | QueueType, 21 | ) 22 | from braket.circuits import Circuit 23 | from braket.devices import Devices 24 | 25 | 26 | def test_task_queue_position(): 27 | device = AwsDevice(Devices.Amazon.SV1) 28 | 29 | bell = Circuit().h(0).cnot(0, 1) 30 | task = device.run(bell, shots=10) 31 | 32 | # call the queue_position method. 33 | queue_information = task.queue_position() 34 | 35 | # data type validations 36 | assert isinstance(queue_information, QuantumTaskQueueInfo) 37 | assert isinstance(queue_information.queue_type, QueueType) 38 | assert isinstance(queue_information.queue_position, (str, type(None))) 39 | 40 | # assert queue priority 41 | assert queue_information.queue_type in [QueueType.NORMAL, QueueType.PRIORITY] 42 | 43 | # assert message 44 | if queue_information.queue_position is None: 45 | assert queue_information.message is not None 46 | assert isinstance(queue_information.message, (str, type(None))) 47 | else: 48 | assert queue_information.message is None 49 | 50 | 51 | def test_job_queue_position(aws_session, completed_quantum_job): 52 | job = completed_quantum_job 53 | 54 | # Check the job is complete 55 | job.result() 56 | 57 | # call the queue_position method. 58 | queue_information = job.queue_position() 59 | 60 | # data type validations 61 | assert isinstance(queue_information, HybridJobQueueInfo) 62 | 63 | # assert message 64 | assert queue_information.queue_position is None 65 | assert isinstance(queue_information.message, str) 66 | 67 | 68 | def test_queue_depth(): 69 | device = AwsDevice(Devices.Amazon.SV1) 70 | 71 | # call the queue_depth method. 72 | queue_information = device.queue_depth() 73 | 74 | # data type validations 75 | assert isinstance(queue_information, QueueDepthInfo) 76 | assert isinstance(queue_information.quantum_tasks, dict) 77 | assert isinstance(queue_information.jobs, str) 78 | 79 | for key, value in queue_information.quantum_tasks.items(): 80 | assert isinstance(key, QueueType) 81 | assert isinstance(value, str) 82 | -------------------------------------------------------------------------------- /test/integ_tests/test_reservation_arn.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | import sys 15 | 16 | import pytest 17 | from botocore.exceptions import ClientError 18 | from job_testing_utils import decorator_python_version 19 | 20 | from braket.aws import AwsDevice, DirectReservation 21 | from braket.circuits import Circuit 22 | from braket.devices import Devices 23 | from braket.jobs import get_job_device_arn, hybrid_job 24 | 25 | 26 | @pytest.fixture 27 | def reservation_arn(aws_session): 28 | return ( 29 | f"arn:aws:braket:{aws_session.region}" 30 | f":{aws_session.account_id}:reservation/a1b123cd-45e6-789f-gh01-i234567jk8l9" 31 | ) 32 | 33 | 34 | def test_create_task_via_invalid_reservation_arn_on_qpu(reservation_arn): 35 | circuit = Circuit().h(0) 36 | device = AwsDevice(Devices.IonQ.Aria1) 37 | 38 | with pytest.raises(ClientError, match="Reservation arn is invalid"): 39 | device.run(circuit, shots=10, reservation_arn=reservation_arn) 40 | 41 | with pytest.raises(ClientError, match="Reservation arn is invalid"): 42 | with DirectReservation(device, reservation_arn=reservation_arn): 43 | device.run(circuit, shots=10) 44 | 45 | 46 | def test_create_task_via_reservation_arn_on_simulator(reservation_arn): 47 | circuit = Circuit().h(0) 48 | device = AwsDevice(Devices.Amazon.SV1) 49 | 50 | with pytest.raises(ClientError, match="Braket Direct is not supported for"): 51 | device.run(circuit, shots=10, reservation_arn=reservation_arn) 52 | 53 | with pytest.raises(ClientError, match="Braket Direct is not supported for"): 54 | with DirectReservation(device, reservation_arn=reservation_arn): 55 | device.run(circuit, shots=10) 56 | 57 | 58 | @pytest.mark.xfail( 59 | (sys.version_info.major, sys.version_info.minor) != decorator_python_version(), 60 | raises=RuntimeError, 61 | reason="Python version mismatch", 62 | ) 63 | def test_create_job_with_decorator_via_invalid_reservation_arn(reservation_arn): 64 | with pytest.raises(ClientError, match="Reservation arn is invalid"): 65 | 66 | @hybrid_job( 67 | device=Devices.IQM.Garnet, 68 | reservation_arn=reservation_arn, 69 | ) 70 | def hello_job(): 71 | device = AwsDevice(get_job_device_arn()) 72 | bell = Circuit().h(0).cnot(0, 1) 73 | task = device.run(bell, shots=10) 74 | measurements = task.result().measurements 75 | return measurements 76 | 77 | hello_job() 78 | -------------------------------------------------------------------------------- /test/integ_tests/test_user_agents.py: -------------------------------------------------------------------------------- 1 | from botocore import awsrequest 2 | 3 | import braket._schemas as braket_schemas 4 | import braket._sdk as braket_sdk 5 | 6 | 7 | def test_default_user_agent(aws_session): 8 | braket_agents = [ 9 | f"BraketSdk/{braket_sdk.__version__}", 10 | f"BraketSchemas/{braket_schemas.__version__}", 11 | "NotebookInstance/", 12 | ] 13 | 14 | def assert_in_user_agent(request: awsrequest.AWSPreparedRequest, **kwargs): 15 | user_agent = request.headers.get("User-Agent") 16 | for agent in braket_agents: 17 | assert bytes(agent, "utf8") in user_agent 18 | 19 | aws_session.braket_client.meta.events.register("before-send.braket", assert_in_user_agent) 20 | 21 | aws_session.search_devices() 22 | 23 | 24 | def test_add_user_agent(aws_session): 25 | aws_session.add_braket_user_agent("foo/1.0") 26 | 27 | def assert_in_user_agent(request: awsrequest.AWSPreparedRequest, **kwargs): 28 | user_agent = request.headers.get("User-Agent") 29 | assert b"foo/1.0" in user_agent 30 | 31 | aws_session.braket_client.meta.events.register("before-send.braket", assert_in_user_agent) 32 | 33 | aws_session.search_devices() 34 | -------------------------------------------------------------------------------- /test/unit_tests/braket/ahs/test_hamiltonian.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from unittest.mock import Mock 15 | 16 | from braket.ahs.hamiltonian import Hamiltonian 17 | 18 | 19 | def test_create(): 20 | hamiltonian = Hamiltonian() 21 | assert hamiltonian.terms == [] 22 | 23 | 24 | def test_add(): 25 | mocks = [Mock(), Mock(), Mock(), Mock()] 26 | result = Hamiltonian([mocks[0], mocks[1], mocks[2]]) + Hamiltonian([mocks[3]]) 27 | assert result.terms == mocks 28 | 29 | 30 | def test_iadd(): 31 | mocks = [Mock(), Mock(), Mock(), Mock()] 32 | hamiltonian = Hamiltonian([mocks[0]]) 33 | hamiltonian += Hamiltonian([mocks[1], mocks[2], mocks[3]]) 34 | assert hamiltonian.terms == mocks 35 | 36 | 37 | def test_discretize(): 38 | mocks = [Mock(), Mock(), Mock()] 39 | mock_properties = Mock() 40 | hamiltonian = Hamiltonian(mocks) 41 | discretized_hamiltonian = hamiltonian.discretize(mock_properties) 42 | for index in range(len(mocks)): 43 | mocks[index].discretize.assert_called_with(mock_properties) 44 | assert discretized_hamiltonian.terms[index] == mocks[index].discretize.return_value 45 | assert hamiltonian is not discretized_hamiltonian 46 | -------------------------------------------------------------------------------- /test/unit_tests/braket/annealing/test_problem.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | import braket.ir.annealing as ir 15 | from braket.annealing.problem import Problem, ProblemType 16 | 17 | 18 | def test_creation(): 19 | problem = Problem(ProblemType.ISING, linear={1: 3.14}, quadratic={(1, 2): 10.08}) 20 | assert problem.problem_type == ProblemType.ISING 21 | assert problem.linear == {1: 3.14} 22 | assert problem.quadratic == {(1, 2): 10.08} 23 | 24 | 25 | def test_add_linear_term(): 26 | problem = Problem(ProblemType.QUBO) 27 | problem.add_linear_term(1, 3.14) 28 | assert problem.linear == {1: 3.14} 29 | 30 | 31 | def test_add_linear_terms(): 32 | problem = Problem(ProblemType.QUBO) 33 | problem.add_linear_terms({1: 3.14}) 34 | assert problem.linear == {1: 3.14} 35 | 36 | 37 | def test_add_quadratic_term(): 38 | problem = Problem(ProblemType.QUBO) 39 | problem.add_quadratic_term((1, 2), 10.08) 40 | assert problem.quadratic == {(1, 2): 10.08} 41 | 42 | 43 | def test_add_quadratic_terms(): 44 | problem = Problem(ProblemType.QUBO) 45 | problem.add_quadratic_terms({(1, 2): 10.08}) 46 | assert problem.quadratic == {(1, 2): 10.08} 47 | 48 | 49 | def test__to_ir(): 50 | problem = Problem(ProblemType.QUBO).add_linear_term(1, 3.14).add_quadratic_term((1, 2), 10.08) 51 | assert problem.to_ir() == ir.Problem( 52 | type=ir.ProblemType.QUBO, linear={1: 3.14}, quadratic={"1,2": 10.08} 53 | ) 54 | -------------------------------------------------------------------------------- /test/unit_tests/braket/circuits/test_basis_state.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from braket.circuits.basis_state import BasisState 4 | 5 | 6 | @pytest.mark.parametrize( 7 | "basis_state_input, size, as_tuple, as_int, as_string", 8 | ( 9 | ( 10 | [1, 0, 1], 11 | None, 12 | (1, 0, 1), 13 | 5, 14 | "101", 15 | ), 16 | ( 17 | [1, 0, 1], 18 | 5, 19 | (0, 0, 1, 0, 1), 20 | 5, 21 | "00101", 22 | ), 23 | ( 24 | "1", 25 | 3, 26 | (0, 0, 1), 27 | 1, 28 | "001", 29 | ), 30 | ( 31 | "101", 32 | None, 33 | (1, 0, 1), 34 | 5, 35 | "101", 36 | ), 37 | ( 38 | 5, 39 | None, 40 | (1, 0, 1), 41 | 5, 42 | "101", 43 | ), 44 | ( 45 | 5, 46 | 4, 47 | (0, 1, 0, 1), 48 | 5, 49 | "0101", 50 | ), 51 | ), 52 | ) 53 | def test_as_props(basis_state_input, size, as_tuple, as_int, as_string): 54 | basis_state = BasisState(basis_state_input, size) 55 | assert basis_state.as_tuple == as_tuple 56 | assert basis_state.as_int == as_int 57 | assert basis_state.as_string == as_string == str(basis_state) 58 | assert repr(basis_state) == f'BasisState("{as_string}")' 59 | 60 | 61 | @pytest.mark.parametrize( 62 | "basis_state_input, index, substate_input", 63 | ( 64 | ( 65 | "1001", 66 | slice(None), 67 | "1001", 68 | ), 69 | ( 70 | "1001", 71 | 3, 72 | "1", 73 | ), 74 | ( 75 | "1010", 76 | slice(None, None, 2), 77 | "11", 78 | ), 79 | ( 80 | "1010", 81 | slice(1, None, 2), 82 | "00", 83 | ), 84 | ( 85 | "1010", 86 | slice(None, -2), 87 | "10", 88 | ), 89 | ( 90 | "1010", 91 | -1, 92 | "0", 93 | ), 94 | ), 95 | ) 96 | def test_indexing(basis_state_input, index, substate_input): 97 | assert BasisState(basis_state_input)[index] == BasisState(substate_input) 98 | 99 | 100 | def test_bool(): 101 | assert all([ 102 | BasisState("100"), 103 | BasisState("111"), 104 | BasisState("1"), 105 | ]) 106 | assert not BasisState("0") 107 | -------------------------------------------------------------------------------- /test/unit_tests/braket/circuits/test_compiler_directive.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | import pytest 15 | 16 | from braket.circuits import Operator 17 | from braket.circuits.compiler_directive import CompilerDirective 18 | from braket.circuits.serialization import IRType 19 | 20 | 21 | @pytest.fixture 22 | def ascii_symbols(): 23 | return ["foo"] 24 | 25 | 26 | @pytest.fixture 27 | def compiler_directive(ascii_symbols): 28 | return CompilerDirective(ascii_symbols=ascii_symbols) 29 | 30 | 31 | def test_is_operator(compiler_directive): 32 | assert isinstance(compiler_directive, Operator) 33 | 34 | 35 | def test_ascii_symbols(compiler_directive, ascii_symbols): 36 | assert compiler_directive.ascii_symbols == tuple(ascii_symbols) 37 | 38 | 39 | def test_none_ascii(): 40 | with pytest.raises(ValueError): 41 | CompilerDirective(ascii_symbols=None) 42 | 43 | 44 | def test_name(compiler_directive): 45 | expected = compiler_directive.__class__.__name__ 46 | assert compiler_directive.name == expected 47 | 48 | 49 | def test_counterpart_not_implemented_by_default(compiler_directive): 50 | with pytest.raises(NotImplementedError): 51 | compiler_directive.counterpart() 52 | 53 | 54 | def test_str(compiler_directive): 55 | assert str(compiler_directive) == compiler_directive.name 56 | 57 | 58 | @pytest.mark.parametrize( 59 | "ir_type, serialization_properties, expected_exception, expected_message", 60 | [ 61 | (IRType.JAQCD, None, NotImplementedError, "to_jaqcd has not been implemented yet."), 62 | (IRType.OPENQASM, None, NotImplementedError, "to_openqasm has not been implemented yet."), 63 | ("invalid-ir-type", None, ValueError, "Supplied ir_type invalid-ir-type is not supported."), 64 | ], 65 | ) 66 | def test_compiler_directive_to_ir( 67 | ir_type, serialization_properties, expected_exception, expected_message, compiler_directive 68 | ): 69 | with pytest.raises(expected_exception) as exc: 70 | compiler_directive.to_ir(0, ir_type, serialization_properties=serialization_properties) 71 | assert exc.value.args[0] == expected_message 72 | -------------------------------------------------------------------------------- /test/unit_tests/braket/circuits/test_compiler_directives.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | import pytest 15 | 16 | import braket.ir.jaqcd as ir 17 | from braket.circuits import compiler_directives 18 | from braket.circuits.compiler_directive import CompilerDirective 19 | from braket.circuits.serialization import IRType 20 | 21 | testdata = [ 22 | ( 23 | compiler_directives.StartVerbatimBox, 24 | ir.StartVerbatimBox, 25 | "#pragma braket verbatim\nbox{", 26 | compiler_directives.EndVerbatimBox, 27 | ), 28 | ( 29 | compiler_directives.EndVerbatimBox, 30 | ir.EndVerbatimBox, 31 | "}", 32 | compiler_directives.StartVerbatimBox, 33 | ), 34 | ] 35 | 36 | 37 | @pytest.mark.parametrize("testclass,irclass,openqasm_str,counterpart", testdata) 38 | def test_counterpart(testclass, irclass, openqasm_str, counterpart): 39 | assert testclass().counterpart() == counterpart() 40 | 41 | 42 | @pytest.mark.parametrize("testclass,irclass,openqasm_str,counterpart", testdata) 43 | def test_to_ir(testclass, irclass, openqasm_str, counterpart): 44 | assert testclass().to_ir(ir_type=IRType.JAQCD) == irclass() 45 | assert testclass().to_ir(ir_type=IRType.OPENQASM) == openqasm_str 46 | 47 | 48 | @pytest.mark.parametrize("testclass,irclass,openqasm_str,counterpart", testdata) 49 | def test_equality(testclass, irclass, openqasm_str, counterpart): 50 | op1 = testclass() 51 | op2 = testclass() 52 | assert op1 == op2 53 | assert op1 is not op2 54 | assert op1 != CompilerDirective(ascii_symbols=["foo"]) 55 | assert op1 != "not a directive" 56 | -------------------------------------------------------------------------------- /test/unit_tests/braket/circuits/test_measure.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | import pytest 15 | 16 | from braket.circuits.measure import Measure 17 | from braket.circuits.quantum_operator import QuantumOperator 18 | from braket.circuits.serialization import ( 19 | IRType, 20 | OpenQASMSerializationProperties, 21 | QubitReferenceType, 22 | ) 23 | 24 | 25 | @pytest.fixture 26 | def measure(): 27 | return Measure() 28 | 29 | 30 | def test_is_operator(measure): 31 | assert isinstance(measure, QuantumOperator) 32 | 33 | 34 | def test_equality(): 35 | measure1 = Measure() 36 | measure2 = Measure() 37 | non_measure = "non measure" 38 | 39 | assert measure1 == measure2 40 | assert measure1 is not measure2 41 | assert measure1 != non_measure 42 | 43 | 44 | def test_ascii_symbols(measure): 45 | assert measure.ascii_symbols == ("M",) 46 | 47 | 48 | def test_str(measure): 49 | assert str(measure) == measure.name 50 | 51 | 52 | @pytest.mark.parametrize( 53 | "ir_type, serialization_properties, expected_exception, expected_message", 54 | [ 55 | ( 56 | IRType.JAQCD, 57 | None, 58 | NotImplementedError, 59 | "measure instructions are not supported with JAQCD.", 60 | ), 61 | ("invalid-ir-type", None, ValueError, "supplied ir_type invalid-ir-type is not supported."), 62 | ], 63 | ) 64 | def test_measure_to_ir( 65 | ir_type, serialization_properties, expected_exception, expected_message, measure 66 | ): 67 | with pytest.raises(expected_exception) as exc: 68 | measure.to_ir(ir_type=ir_type, serialization_properties=serialization_properties) 69 | assert exc.value.args[0] == expected_message 70 | 71 | 72 | @pytest.mark.parametrize( 73 | "measure, target, serialization_properties, expected_ir", 74 | [ 75 | ( 76 | Measure(), 77 | [0], 78 | OpenQASMSerializationProperties(qubit_reference_type=QubitReferenceType.VIRTUAL), 79 | "b[0] = measure q[0];", 80 | ), 81 | ( 82 | Measure(), 83 | [1, 4], 84 | OpenQASMSerializationProperties(qubit_reference_type=QubitReferenceType.PHYSICAL), 85 | "\n".join([ 86 | "b[0] = measure $1;", 87 | "b[1] = measure $4;", 88 | ]), 89 | ), 90 | ], 91 | ) 92 | def test_measure_to_ir_openqasm(measure, target, serialization_properties, expected_ir): 93 | assert ( 94 | measure.to_ir( 95 | target, ir_type=IRType.OPENQASM, serialization_properties=serialization_properties 96 | ) 97 | == expected_ir 98 | ) 99 | -------------------------------------------------------------------------------- /test/unit_tests/braket/jobs/job_module.py: -------------------------------------------------------------------------------- 1 | def some_helper(): 2 | return "success" 3 | -------------------------------------------------------------------------------- /test/unit_tests/braket/jobs/test_environment_variables.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | import tempfile 4 | from pathlib import Path 5 | from unittest.mock import patch 6 | 7 | from braket.jobs import ( 8 | get_checkpoint_dir, 9 | get_hyperparameters, 10 | get_input_data_dir, 11 | get_job_device_arn, 12 | get_job_name, 13 | get_results_dir, 14 | ) 15 | 16 | 17 | def test_job_name(): 18 | assert get_job_name() == "" 19 | job_name = "my_job_name" 20 | with patch.dict(os.environ, {"AMZN_BRAKET_JOB_NAME": job_name}): 21 | assert get_job_name() == job_name 22 | 23 | 24 | def test_job_device_arn(): 25 | assert get_job_device_arn() == "local:none/none" 26 | device_arn = "my_device_arn" 27 | with patch.dict(os.environ, {"AMZN_BRAKET_DEVICE_ARN": device_arn}): 28 | assert get_job_device_arn() == device_arn 29 | 30 | 31 | def test_input_data_dir(): 32 | assert get_input_data_dir() == "." 33 | input_path = "my/input/path" 34 | with patch.dict(os.environ, {"AMZN_BRAKET_INPUT_DIR": input_path}): 35 | assert get_input_data_dir() == f"{input_path}/input" 36 | channel_name = "my_channel" 37 | assert get_input_data_dir(channel_name) == f"{input_path}/{channel_name}" 38 | 39 | 40 | def test_results_dir(): 41 | assert get_results_dir() == "." 42 | results_dir = "my_results_dir" 43 | with patch.dict(os.environ, {"AMZN_BRAKET_JOB_RESULTS_DIR": results_dir}): 44 | assert get_results_dir() == results_dir 45 | 46 | 47 | def test_checkpoint_dir(): 48 | assert get_checkpoint_dir() == "." 49 | checkpoint_dir = "my_checkpoint_dir" 50 | with patch.dict(os.environ, {"AMZN_BRAKET_CHECKPOINT_DIR": checkpoint_dir}): 51 | assert get_checkpoint_dir() == checkpoint_dir 52 | 53 | 54 | def test_hyperparameters(): 55 | assert get_hyperparameters() == {} 56 | hp_file = "my_hyperparameters.json" 57 | hyperparameters = { 58 | "a": "a_val", 59 | "b": 2, 60 | } 61 | with ( 62 | tempfile.TemporaryDirectory() as temp_dir, 63 | patch.dict(os.environ, {"AMZN_BRAKET_HP_FILE": str(Path(temp_dir) / hp_file)}), 64 | ): 65 | with open(str(Path(temp_dir) / hp_file), "w") as f: 66 | json.dump(hyperparameters, f) 67 | assert get_hyperparameters() == hyperparameters 68 | -------------------------------------------------------------------------------- /test/unit_tests/braket/jobs/test_image_uris.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | import pytest 15 | 16 | from braket.jobs.image_uris import Framework, retrieve_image 17 | 18 | 19 | @pytest.mark.parametrize( 20 | "region, framework, expected_uri", 21 | [ 22 | ( 23 | "us-west-1", 24 | Framework.BASE, 25 | "292282985366.dkr.ecr.us-west-1.amazonaws.com/amazon-braket-base-jobs:latest", 26 | ), 27 | ( 28 | "us-east-1", 29 | Framework.PL_TENSORFLOW, 30 | "292282985366.dkr.ecr.us-east-1.amazonaws.com/amazon-braket-tensorflow-jobs:latest", 31 | ), 32 | ( 33 | "us-west-2", 34 | Framework.PL_PYTORCH, 35 | "292282985366.dkr.ecr.us-west-2.amazonaws.com/amazon-braket-pytorch-jobs:latest", 36 | ), 37 | ], 38 | ) 39 | def test_retrieve_image_default_version(region, framework, expected_uri): 40 | assert retrieve_image(framework, region) == expected_uri 41 | 42 | 43 | @pytest.mark.parametrize( 44 | "region, framework", 45 | [ 46 | ("eu-west-1", Framework.BASE), 47 | (None, Framework.BASE), 48 | ("us-west-1", None), 49 | ("us-west-1", "foo"), 50 | ], 51 | ) 52 | @pytest.mark.xfail(raises=ValueError) 53 | def test_retrieve_image_incorrect_input(region, framework): 54 | retrieve_image(framework, region) 55 | -------------------------------------------------------------------------------- /test/unit_tests/braket/jobs/test_metrics.py: -------------------------------------------------------------------------------- 1 | from unittest.mock import patch 2 | 3 | import pytest 4 | 5 | from braket.jobs.metrics import log_metric 6 | 7 | 8 | @pytest.mark.parametrize( 9 | "test_value, test_timestamp, test_iteration, result_string", 10 | [ 11 | # Happy case 12 | (0.1, 1, 2, "Metrics - timestamp=1; TestName=0.1; iteration_number=2;"), 13 | # We handle exponent values 14 | (3.14e-22, 1, 2, "Metrics - timestamp=1; TestName=3.14e-22; iteration_number=2;"), 15 | # When iteration number is not provided, we don't print it 16 | (5, 1, None, "Metrics - timestamp=1; TestName=5;"), 17 | # When iteration number is 0, we do print it 18 | (5, 1, 0, "Metrics - timestamp=1; TestName=5; iteration_number=0;"), 19 | # When timestamp is not provided, we use time.time() 20 | (-3.14, None, 2, "Metrics - timestamp=time_mocked; TestName=-3.14; iteration_number=2;"), 21 | ], 22 | ) 23 | @patch("time.time") 24 | @patch("builtins.print") 25 | def test_log_metric( 26 | print_mock, time_mock, test_value, test_timestamp, test_iteration, result_string 27 | ): 28 | time_mock.return_value = "time_mocked" 29 | log_metric( 30 | metric_name="TestName", 31 | value=test_value, 32 | timestamp=test_timestamp, 33 | iteration_number=test_iteration, 34 | ) 35 | print_mock.assert_called_with(result_string) 36 | -------------------------------------------------------------------------------- /test/unit_tests/braket/jobs/test_serialization.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | 15 | import pytest 16 | 17 | from braket.jobs.serialization import deserialize_values, serialize_values 18 | from braket.jobs_data import PersistedJobDataFormat 19 | 20 | 21 | @pytest.mark.parametrize( 22 | "data_format, submitted_data, expected_serialized_data", 23 | [ 24 | ( 25 | PersistedJobDataFormat.PLAINTEXT, 26 | {"converged": True, "energy": -0.2}, 27 | {"converged": True, "energy": -0.2}, 28 | ), 29 | ( 30 | PersistedJobDataFormat.PICKLED_V4, 31 | {"converged": True, "energy": -0.2}, 32 | {"converged": "gASILg==\n", "energy": "gASVCgAAAAAAAABHv8mZmZmZmZou\n"}, 33 | ), 34 | ], 35 | ) 36 | def test_job_serialize_data(data_format, submitted_data, expected_serialized_data): 37 | serialized_data = serialize_values(submitted_data, data_format) 38 | assert serialized_data == expected_serialized_data 39 | 40 | 41 | @pytest.mark.parametrize( 42 | "data_format, submitted_data, expected_deserialized_data", 43 | [ 44 | ( 45 | PersistedJobDataFormat.PLAINTEXT, 46 | {"converged": True, "energy": -0.2}, 47 | {"converged": True, "energy": -0.2}, 48 | ), 49 | ( 50 | PersistedJobDataFormat.PICKLED_V4, 51 | {"converged": "gASILg==\n", "energy": "gASVCgAAAAAAAABHv8mZmZmZmZou\n"}, 52 | {"converged": True, "energy": -0.2}, 53 | ), 54 | ], 55 | ) 56 | def test_job_deserialize_data(data_format, submitted_data, expected_deserialized_data): 57 | deserialized_data = deserialize_values(submitted_data, data_format) 58 | assert deserialized_data == expected_deserialized_data 59 | -------------------------------------------------------------------------------- /test/unit_tests/braket/parametric/test_free_parameter.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | import pytest 15 | 16 | from braket.parametric import FreeParameter 17 | 18 | 19 | @pytest.fixture 20 | def free_parameter(): 21 | return FreeParameter("theta") 22 | 23 | 24 | def test_bad_input(): 25 | with pytest.raises(ValueError, match="FreeParameter names must be non empty"): 26 | FreeParameter("") 27 | with pytest.raises(TypeError, match="FreeParameter names must be strings"): 28 | FreeParameter(6) 29 | with pytest.raises( 30 | ValueError, match="FreeParameter names must start with a letter or an underscore" 31 | ): 32 | FreeParameter(".2") 33 | 34 | 35 | def test_is_free_param(free_parameter): 36 | assert isinstance(free_parameter, FreeParameter) 37 | 38 | 39 | def test_equality(): 40 | param_1 = FreeParameter("theta") 41 | param_2 = FreeParameter("theta") 42 | other_param = FreeParameter("phi") 43 | non_param = "non circuit" 44 | 45 | assert param_1 == param_2 46 | assert param_1 is not param_2 47 | assert param_1 != other_param 48 | assert param_1 != non_param 49 | 50 | 51 | def test_str(free_parameter): 52 | expected = "theta" 53 | assert str(free_parameter) == expected 54 | 55 | 56 | def test_hash(free_parameter): 57 | assert hash(free_parameter) == hash(tuple(free_parameter.name)) 58 | 59 | 60 | def test_rep(free_parameter): 61 | assert repr(free_parameter) == free_parameter.name 62 | 63 | 64 | def test_sub_successful(free_parameter): 65 | assert free_parameter.subs({"theta": 1}) == 1 66 | 67 | 68 | def test_sub_wrong_param(free_parameter): 69 | assert free_parameter.subs({"alpha": 1}) == FreeParameter("theta") 70 | 71 | 72 | @pytest.mark.parametrize("param_name", ["for", "qubit"]) 73 | def test_error_raised_when_reserved_keyword_used(param_name): 74 | with pytest.raises( 75 | ValueError, 76 | match="FreeParameter names must not be one of the OpenQASM or OpenPulse keywords: ", 77 | ): 78 | FreeParameter(param_name) 79 | 80 | 81 | @pytest.mark.parametrize("param_name", ["b", "q"]) 82 | def test_error_raised_when_predefined_variable_used(param_name): 83 | with pytest.raises( 84 | ValueError, 85 | match="FreeParameter names must not be one of the Braket reserved variable names: ", 86 | ): 87 | FreeParameter(param_name) 88 | -------------------------------------------------------------------------------- /test/unit_tests/braket/pulse/test_frame.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | import pytest 15 | from oqpy import FrameVar as OQpyFrame 16 | from oqpy import PortVar 17 | from oqpy.base import expr_matches 18 | 19 | from braket.pulse import Frame, Port 20 | 21 | 22 | @pytest.fixture 23 | def port(): 24 | return Port("test_port_ff", dt=1e-9) 25 | 26 | 27 | @pytest.fixture 28 | def frame_id(): 29 | return "test_frame_rf" 30 | 31 | 32 | def test_frame_no_properties(frame_id, port): 33 | frame = Frame(frame_id, port, 1e6, is_predefined=True) 34 | assert frame.id == frame_id 35 | assert frame.port == port 36 | assert frame.frequency == 1e6 37 | assert frame.phase == 0 38 | assert frame.is_predefined 39 | assert frame.properties is None 40 | 41 | 42 | def test_frame_to_oqpy_expression(port, frame_id): 43 | frequency = 4e7 44 | phase = 1.57 45 | frame = Frame(frame_id, port, frequency, phase, True, {"dummy_property": "foo"}) 46 | expected_expression = OQpyFrame( 47 | port=PortVar(port.id), 48 | frequency=frequency, 49 | phase=phase, 50 | name=frame_id, 51 | needs_declaration=False, 52 | ) 53 | oq_expression = frame._to_oqpy_expression() 54 | assert expr_matches(oq_expression, expected_expression) 55 | 56 | 57 | def test_frame_equality(frame_id, port): 58 | f = Frame(frame_id, port, 1e4, 0.57) 59 | uneqs = [ 60 | Frame("wrong_id", port, f.frequency, f.phase, {"foo": "bar"}), 61 | Frame(f.id, Port("foo", dt=1e-9), f.frequency, f.phase), 62 | Frame(f.id, f.port, 1e5, f.phase), 63 | Frame(f.id, f.port, f.frequency, 0.23), 64 | ] 65 | eqs = [ 66 | Frame(f.id, f.port, f.frequency, f.phase, {"a": "b"}), 67 | Frame(f.id, f.port, f.frequency, f.phase), 68 | ] 69 | for x in uneqs: 70 | assert f != x 71 | for x in eqs: 72 | assert f == x 73 | -------------------------------------------------------------------------------- /test/unit_tests/braket/pulse/test_port.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | import pytest 15 | from oqpy import PortVar 16 | from oqpy.base import expr_matches 17 | 18 | from braket.pulse import Port 19 | 20 | 21 | @pytest.fixture 22 | def port_id(): 23 | return "test_port_ff" 24 | 25 | 26 | @pytest.fixture 27 | def port_time_resolution(): 28 | return 1e-9 29 | 30 | 31 | @pytest.fixture 32 | def port_properties(): 33 | return {"dt": 1e-6, "direction": "tx"} 34 | 35 | 36 | @pytest.fixture 37 | def port(port_id, port_time_resolution, port_properties): 38 | return Port(port_id, port_time_resolution, port_properties) 39 | 40 | 41 | def test_port_no_properties(port_id, port_time_resolution): 42 | port = Port(port_id, port_time_resolution) 43 | assert port.id == port_id 44 | assert port.dt == port_time_resolution 45 | assert port.properties is None 46 | 47 | 48 | def test_port_to_oqpy_expression(port, port_id): 49 | expected_expression = PortVar(port_id) 50 | assert expr_matches(port._to_oqpy_expression(), expected_expression) 51 | 52 | 53 | def test_port_equality(port, port_time_resolution): 54 | p2 = Port(port.id, port_time_resolution) 55 | p3 = Port("random_id", port_time_resolution, properties=port.properties) 56 | p4 = Port(port.id, port_time_resolution, properties={"random_property": "foo"}) 57 | p5 = Port(port.id, 0) 58 | assert port == p2 59 | assert port == p4 60 | assert port == p5 61 | assert port != p3 62 | -------------------------------------------------------------------------------- /test/unit_tests/braket/registers/test_qubit.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | import numpy as np 15 | import pytest 16 | 17 | from braket.registers import Qubit 18 | 19 | 20 | @pytest.fixture 21 | def qubit(): 22 | return Qubit(5) 23 | 24 | 25 | def test_index_lt_zero(): 26 | with pytest.raises(ValueError): 27 | Qubit(-1) 28 | 29 | 30 | @pytest.mark.parametrize("qubit_arg", ("not a number", 0.5)) 31 | def test_index_non_int(qubit_arg): 32 | with pytest.raises(TypeError): 33 | Qubit(qubit_arg) 34 | 35 | 36 | @pytest.mark.parametrize("qubit_index", (0, 5, np.int64(5))) 37 | def test_index_gte_zero(qubit_index): 38 | Qubit(qubit_index) 39 | 40 | 41 | def test_str(qubit): 42 | expected = f"Qubit({int(qubit)})" 43 | assert str(qubit) == expected 44 | 45 | 46 | def test_new_with_qubit(): 47 | qubit = Qubit(0) 48 | qubit_new = Qubit.new(qubit) 49 | assert qubit_new == qubit 50 | assert qubit_new is qubit 51 | 52 | 53 | def test_new_with_int(): 54 | qubit = 0 55 | qubit_new = Qubit.new(qubit) 56 | assert qubit_new == qubit 57 | assert qubit_new is not qubit 58 | -------------------------------------------------------------------------------- /test/unit_tests/braket/registers/test_qubit_set.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | import pytest 15 | 16 | from braket.registers import Qubit, QubitSet 17 | 18 | 19 | @pytest.fixture 20 | def qubits(): 21 | return QubitSet([0, Qubit(1)]) 22 | 23 | 24 | def test_qubit_set_is_ordered_set(): 25 | qubits = QubitSet([1, 2, 3, 1, 2, 3]) 26 | assert qubits == QubitSet([1, 2, 3]) 27 | 28 | 29 | def test_default_input(): 30 | assert QubitSet() == QubitSet([]) 31 | 32 | 33 | def test_with_single(): 34 | assert QubitSet(0) == (Qubit(0),) 35 | 36 | 37 | def test_with_iterable(): 38 | assert QubitSet([0, 1]) == (Qubit(0), Qubit(1)) 39 | 40 | 41 | def test_with_nested_iterable(): 42 | assert QubitSet([0, 1, [2, 3]]) == (Qubit(0), Qubit(1), Qubit(2), Qubit(3)) 43 | 44 | 45 | def test_with_qubit_set(): 46 | qubits = QubitSet([0, 1]) 47 | assert QubitSet([qubits, [2, 3]]) == (Qubit(0), Qubit(1), Qubit(2), Qubit(3)) 48 | 49 | 50 | def test_flattening_does_not_recurse_infinitely(): 51 | with pytest.raises(TypeError): # str instead of expected int 52 | QubitSet("kaboom") 53 | 54 | 55 | def test_map_creates_new_object(qubits): 56 | mapped_qubits = qubits.map({}) 57 | assert mapped_qubits == qubits 58 | assert mapped_qubits is not qubits 59 | 60 | 61 | def test_map_happy_case(): 62 | mapping = {Qubit(0): Qubit(11), Qubit(1): Qubit(5)} 63 | qubits = QubitSet([0, 1]) 64 | mapped_qubits = qubits.map(mapping) 65 | 66 | assert mapped_qubits == QubitSet([11, 5]) 67 | 68 | 69 | def test_hash(qubits): 70 | assert hash(qubits) == hash(tuple(qubits)) 71 | -------------------------------------------------------------------------------- /test/unit_tests/braket/tasks/test_local_quantum_task.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | import uuid 15 | 16 | import numpy as np 17 | import pytest 18 | 19 | from braket.task_result import TaskMetadata 20 | from braket.tasks import GateModelQuantumTaskResult 21 | from braket.tasks.local_quantum_task import LocalQuantumTask 22 | 23 | RESULT = GateModelQuantumTaskResult( 24 | task_metadata=TaskMetadata(**{"id": str(uuid.uuid4()), "deviceId": "default", "shots": 100}), 25 | additional_metadata=None, 26 | measurements=np.array([[0, 1], [1, 0]]), 27 | measured_qubits=[0, 1], 28 | result_types=None, 29 | values=None, 30 | ) 31 | 32 | TASK = LocalQuantumTask(RESULT) 33 | 34 | 35 | def test_id(): 36 | # Task ID is valid UUID 37 | uuid.UUID(TASK.id) 38 | 39 | 40 | def test_state(): 41 | assert TASK.state() == "COMPLETED" 42 | 43 | 44 | def test_result(): 45 | assert RESULT.task_metadata.id == TASK.id 46 | assert TASK.result() == RESULT 47 | 48 | 49 | @pytest.mark.xfail(raises=NotImplementedError) 50 | def test_cancel(): 51 | TASK.cancel() 52 | 53 | 54 | @pytest.mark.xfail(raises=NotImplementedError) 55 | def test_async(): 56 | TASK.async_result() 57 | 58 | 59 | def test_str(): 60 | expected = f"LocalQuantumTask('id':{TASK.id})" 61 | assert str(TASK) == expected 62 | -------------------------------------------------------------------------------- /test/unit_tests/braket/tasks/test_local_quantum_task_batch.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | import uuid 15 | 16 | import numpy as np 17 | 18 | from braket.task_result import TaskMetadata 19 | from braket.tasks import GateModelQuantumTaskResult 20 | from braket.tasks.local_quantum_task_batch import LocalQuantumTaskBatch 21 | 22 | RESULTS = [ 23 | GateModelQuantumTaskResult( 24 | task_metadata=TaskMetadata(**{ 25 | "id": str(uuid.uuid4()), 26 | "deviceId": "default", 27 | "shots": 100, 28 | }), 29 | additional_metadata=None, 30 | measurements=np.array([[0, 1], [1, 0]]), 31 | measured_qubits=[0, 1], 32 | result_types=None, 33 | values=None, 34 | ) 35 | ] 36 | 37 | TASK_BATCH = LocalQuantumTaskBatch(RESULTS) 38 | 39 | 40 | def test_results(): 41 | assert TASK_BATCH.results() == RESULTS 42 | assert len(TASK_BATCH.results()) == 1 43 | -------------------------------------------------------------------------------- /test/unit_tests/braket/tasks/test_photonic_model_quantum_task_result.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | import pytest 15 | 16 | from braket.ir.blackbird import Program as BlackbirdProgram 17 | from braket.task_result import ( 18 | AdditionalMetadata, 19 | PhotonicModelTaskResult, 20 | TaskMetadata, 21 | XanaduMetadata, 22 | ) 23 | from braket.tasks import PhotonicModelQuantumTaskResult 24 | 25 | 26 | @pytest.fixture 27 | def task_metadata(): 28 | return TaskMetadata(**{"id": "task_arn", "deviceId": "arn1", "shots": 100}) 29 | 30 | 31 | @pytest.fixture 32 | def xanadu_metadata(): 33 | return XanaduMetadata(compiledProgram="DECLARE ro BIT[2];") 34 | 35 | 36 | @pytest.fixture 37 | def blackbird_program(): 38 | return BlackbirdProgram(source="Vac | q[0]") 39 | 40 | 41 | @pytest.fixture 42 | def additional_metadata(blackbird_program, xanadu_metadata): 43 | return AdditionalMetadata(action=blackbird_program, xanaduMetadata=xanadu_metadata) 44 | 45 | 46 | @pytest.fixture 47 | def measurements(): 48 | return [[[1, 2, 3, 4]], [[4, 3, 2, 1]], [[0, 0, 0, 0]]] 49 | 50 | 51 | @pytest.fixture 52 | def result_1(measurements, task_metadata, additional_metadata): 53 | return PhotonicModelTaskResult( 54 | measurements=measurements, 55 | taskMetadata=task_metadata, 56 | additionalMetadata=additional_metadata, 57 | ) 58 | 59 | 60 | @pytest.fixture 61 | def result_1_str(result_1): 62 | return result_1.json() 63 | 64 | 65 | @pytest.fixture 66 | def empty_result(task_metadata, additional_metadata): 67 | updated_metadata = task_metadata.copy() 68 | updated_metadata.id = "empty_arn" 69 | return PhotonicModelTaskResult( 70 | taskMetadata=updated_metadata, additionalMetadata=additional_metadata 71 | ) 72 | 73 | 74 | def test_from_object_equals_from_string(result_1, result_1_str): 75 | assert PhotonicModelQuantumTaskResult.from_object( 76 | result_1 77 | ) == PhotonicModelQuantumTaskResult.from_string(result_1_str) 78 | 79 | 80 | def test_equality(result_1, empty_result): 81 | quantum_result1 = PhotonicModelQuantumTaskResult.from_object(result_1) 82 | quantum_empty = PhotonicModelQuantumTaskResult.from_object(empty_result) 83 | non_result = "not a quantum task result" 84 | 85 | assert quantum_result1 == quantum_result1 86 | assert quantum_result1 != quantum_empty 87 | assert quantum_result1 != non_result 88 | -------------------------------------------------------------------------------- /test/unit_tests/braket/tasks/test_tasks_init.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | import importlib 15 | import sys 16 | from unittest.mock import patch 17 | 18 | import braket.tasks 19 | 20 | 21 | @patch("braket.ipython_utils.running_in_jupyter") 22 | def test_nest_asyncio_not_applied(running_in_jupyter): 23 | running_in_jupyter.return_value = False 24 | importlib.reload(braket.tasks) 25 | assert "nest_asyncio" not in sys.modules 26 | 27 | 28 | @patch("braket.ipython_utils.running_in_jupyter") 29 | def test_nest_asyncio_is_applied(running_in_jupyter): 30 | running_in_jupyter.return_value = True 31 | importlib.reload(braket.tasks) 32 | assert "nest_asyncio" in sys.modules 33 | -------------------------------------------------------------------------------- /test/unit_tests/braket/test_imports.py: -------------------------------------------------------------------------------- 1 | import importlib 2 | import multiprocessing 3 | import os 4 | import pathlib 5 | 6 | import pytest 7 | 8 | 9 | def test_for_import_cycles(): 10 | # Note, because of all the multiprocessing in this test, when running 'tox', the process 11 | # threads may be made to wait as other tests are running in parallel, making it seems like 12 | # this test is much slower than it actually is. However, splitting the test into a 13 | # parameterized version wasn't able to correctly detect some circular imports when running tox. 14 | modules = get_modules_to_test() 15 | processes = [] 16 | multiprocessing.set_start_method("spawn", force=True) 17 | for module in modules: 18 | # We create a separate process to make sure the imports do not interfere with each-other. 19 | process = multiprocessing.Process(target=import_module, args=(module,)) 20 | processes.append(process) 21 | process.start() 22 | 23 | for index, process in enumerate(processes): 24 | process.join() 25 | if process.exitcode != 0: 26 | pytest.fail( 27 | f"Unable to import '{modules[index]}'." 28 | " If all other tests are passing, check for cyclical dependencies." 29 | ) 30 | 31 | 32 | def get_modules_to_test(): 33 | curr_path = pathlib.Path(__file__).resolve() 34 | while "test" in str(curr_path): 35 | curr_path = curr_path.parent 36 | curr_path = curr_path.joinpath("src") 37 | curr_path_len = len(str(curr_path)) + len(os.sep) 38 | modules = [] 39 | for dir_, temp, files in os.walk(curr_path): 40 | # Rather than testing every single python file we just test modules, for now. 41 | if "__init__.py" in files: 42 | braket_module = dir_[curr_path_len:].replace(os.sep, ".") 43 | modules.append(braket_module) 44 | return modules 45 | 46 | 47 | def import_module(module): 48 | importlib.import_module(module) 49 | -------------------------------------------------------------------------------- /test/unit_tests/braket/test_ipython_utils.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | import sys 15 | from unittest.mock import Mock 16 | 17 | import braket.ipython_utils as ipython_utils 18 | 19 | 20 | def test_running_in_jupyter(): 21 | assert not ipython_utils.running_in_jupyter() 22 | 23 | 24 | def test_ipython_imported_but_ipython_none(): 25 | _mock_ipython(None) 26 | assert not ipython_utils.running_in_jupyter() 27 | 28 | 29 | def test_ipython_imported_but_not_in_jupyter(): 30 | _mock_ipython(MockIPython(None)) 31 | assert not ipython_utils.running_in_jupyter() 32 | 33 | 34 | def test_ipython_imported_and_in_jupyter(): 35 | _mock_ipython(MockIPython("non empty kernel")) 36 | assert ipython_utils.running_in_jupyter() 37 | 38 | 39 | def get_ipython(): 40 | pass 41 | 42 | 43 | def _mock_ipython(get_ipython_result): 44 | module = sys.modules["test_ipython_utils"] 45 | sys.modules["IPython"] = module 46 | 47 | get_ipython = Mock(return_value=get_ipython_result) 48 | sys.modules["IPython"].__dict__["get_ipython"] = get_ipython 49 | 50 | 51 | class MockIPython: 52 | def __init__(self, kernel): 53 | self.kernel = kernel 54 | -------------------------------------------------------------------------------- /test/unit_tests/braket/tracking/test_pricing.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | 15 | import io 16 | from unittest.mock import patch 17 | 18 | import pytest 19 | 20 | from braket.tracking.pricing import Pricing 21 | 22 | 23 | @pytest.fixture 24 | def mock_http(): 25 | with patch("urllib3.PoolManager") as http_mock: 26 | http_mock().request.return_value = io.BytesIO( 27 | b"""line1 28 | line2 29 | line3 30 | line4 31 | line5 32 | A,B 33 | 1,1 34 | 1,2 35 | """ 36 | ) 37 | yield http_mock() 38 | 39 | 40 | def test_search_prices(mock_http): 41 | pricer = Pricing() 42 | assert pricer.price_search(A="0") == [] 43 | assert pricer.price_search(A="1", B="1") == [{"A": "1", "B": "1"}] 44 | assert pricer.price_search(A="1") == [{"A": "1", "B": "1"}, {"A": "1", "B": "2"}] 45 | 46 | 47 | @patch.dict("os.environ", {"BRAKET_PRICE_OFFERS_URL": "https://myurl"}) 48 | def test_price_offer_env_var(mock_http): 49 | pricer = Pricing() 50 | pricer.get_prices() 51 | 52 | mock_http.request.assert_called_with("GET", "https://myurl", preload_content=False) 53 | -------------------------------------------------------------------------------- /test/unit_tests/braket/tracking/test_tracking_context.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You 4 | # may not use this file except in compliance with the License. A copy of 5 | # the License is located at 6 | # 7 | # http://aws.amazon.com/apache2.0/ 8 | # 9 | # or in the "license" file accompanying this file. This file is 10 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 | # ANY KIND, either express or implied. See the License for the specific 12 | # language governing permissions and limitations under the License. 13 | 14 | from unittest.mock import Mock 15 | 16 | from braket.tracking.tracking_context import ( 17 | active_trackers, 18 | broadcast_event, 19 | deregister_tracker, 20 | register_tracker, 21 | ) 22 | 23 | 24 | def test_tracking_context(): 25 | assert active_trackers() == set() 26 | 27 | 28 | def test_register_deregister_tracker(): 29 | register_tracker("foo") 30 | assert active_trackers() == {"foo"} 31 | register_tracker("bar") 32 | register_tracker("bar") 33 | assert active_trackers() == {"foo", "bar"} 34 | deregister_tracker("foo") 35 | assert active_trackers() == {"bar"} 36 | deregister_tracker("bar") 37 | 38 | 39 | def test_broadcast_event(): 40 | tracker = Mock() 41 | register_tracker(tracker) 42 | broadcast_event("EVENT") 43 | tracker.receive_event.assert_called_with("EVENT") 44 | deregister_tracker(tracker) 45 | --------------------------------------------------------------------------------