diff --git a/.github/workflows/check-format.yml b/.github/workflows/check-format.yml index 1795135e7..8f6807b5e 100644 --- a/.github/workflows/check-format.yml +++ b/.github/workflows/check-format.yml @@ -23,8 +23,7 @@ jobs: python-version: '3.9' - name: Install dependencies run: | - pip install --upgrade pip - pip install -e .[test] + pip install tox - name: Run code format checks run: | tox -e linters_check diff --git a/pydoclint-baseline.txt b/pydoclint-baseline.txt new file mode 100644 index 000000000..816c4265a --- /dev/null +++ b/pydoclint-baseline.txt @@ -0,0 +1,233 @@ +src/braket/aws/aws_device.py + DOC101: Method `AwsDevice.run_batch`: Docstring contains fewer arguments than in function signature. + DOC103: Method `AwsDevice.run_batch`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [**aws_quantum_task_kwargs: , *aws_quantum_task_args: ]. +-------------------- +src/braket/aws/aws_quantum_job.py + DOC502: Method `AwsQuantumJob.create` has a "Raises" section in the docstring, but there are not "raise" statements in the body + DOC101: Method `AwsQuantumJob._is_valid_aws_session_region_for_job_arn`: Docstring contains fewer arguments than in function signature. + DOC109: Method `AwsQuantumJob._is_valid_aws_session_region_for_job_arn`: The option `--arg-type-hints-in-docstring` is `True` but there are no type hints in the docstring arg list + DOC103: Method `AwsQuantumJob._is_valid_aws_session_region_for_job_arn`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [aws_session: AwsSession, job_arn: str]. + DOC502: Method `AwsQuantumJob.logs` has a "Raises" section in the docstring, but there are not "raise" statements in the body + DOC502: Method `AwsQuantumJob.cancel` has a "Raises" section in the docstring, but there are not "raise" statements in the body +-------------------- +src/braket/aws/aws_quantum_task.py + DOC101: Method `AwsQuantumTask.create`: Docstring contains fewer arguments than in function signature. + DOC103: Method `AwsQuantumTask.create`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [**kwargs: , *args: ]. + DOC501: Method `AwsQuantumTask.create` has "raise" statements, but the docstring does not have a "Raises" section + DOC101: Method `AwsQuantumTask._aws_session_for_task_arn`: Docstring contains fewer arguments than in function signature. + DOC109: Method `AwsQuantumTask._aws_session_for_task_arn`: The option `--arg-type-hints-in-docstring` is `True` but there are no type hints in the docstring arg list + DOC103: Method `AwsQuantumTask._aws_session_for_task_arn`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [task_arn: str]. + DOC501: Function `_create_annealing_device_params` has "raise" statements, but the docstring does not have a "Raises" section +-------------------- +src/braket/aws/aws_quantum_task_batch.py + DOC501: Method `AwsQuantumTaskBatch.results` has "raise" statements, but the docstring does not have a "Raises" section + DOC501: Method `AwsQuantumTaskBatch.retry_unsuccessful_tasks` has "raise" statements, but the docstring does not have a "Raises" section +-------------------- +src/braket/aws/aws_session.py + DOC106: Method `AwsSession.create_quantum_task`: The option `--arg-type-hints-in-signature` is `True` but there are no argument type hints in the signature + DOC109: Method `AwsSession.create_quantum_task`: The option `--arg-type-hints-in-docstring` is `True` but there are no type hints in the docstring arg list + DOC106: Method `AwsSession.create_job`: The option `--arg-type-hints-in-signature` is `True` but there are no argument type hints in the signature + DOC109: Method `AwsSession.create_job`: The option `--arg-type-hints-in-docstring` is `True` but there are no type hints in the docstring arg list + DOC001: Function/method `parse_s3_uri`: Potential formatting errors in docstring. Error message: Expected a colon in 'a valid S3 URI.'. + DOC101: Method `AwsSession.parse_s3_uri`: Docstring contains fewer arguments than in function signature. + DOC109: Method `AwsSession.parse_s3_uri`: The option `--arg-type-hints-in-docstring` is `True` but there are no type hints in the docstring arg list + DOC103: Method `AwsSession.parse_s3_uri`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [s3_uri: str]. + DOC201: Method `AwsSession.parse_s3_uri` does not have a return section in docstring + DOC203: Method `AwsSession.parse_s3_uri` return type(s) in docstring not consistent with the return annotation. Return annotation has 1 type(s); docstring return section has 0 type(s). + DOC501: Method `AwsSession.parse_s3_uri` has "raise" statements, but the docstring does not have a "Raises" section + DOC001: Function/method `construct_s3_uri`: Potential formatting errors in docstring. Error message: Expected a colon in 'valid to generate an S3 URI'. + DOC101: Method `AwsSession.construct_s3_uri`: Docstring contains fewer arguments than in function signature. + DOC109: Method `AwsSession.construct_s3_uri`: The option `--arg-type-hints-in-docstring` is `True` but there are no type hints in the docstring arg list + DOC103: Method `AwsSession.construct_s3_uri`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [*dirs: str, bucket: str]. + DOC201: Method `AwsSession.construct_s3_uri` does not have a return section in docstring + DOC203: Method `AwsSession.construct_s3_uri` return type(s) in docstring not consistent with the return annotation. Return annotation has 1 type(s); docstring return section has 0 type(s). + DOC501: Method `AwsSession.construct_s3_uri` has "raise" statements, but the docstring does not have a "Raises" section + DOC501: Method `AwsSession.get_full_image_tag` has "raise" statements, but the docstring does not have a "Raises" section +-------------------- +src/braket/circuits/angled_gate.py + DOC101: Method `AngledGate.bind_values`: Docstring contains fewer arguments than in function signature. + DOC106: Method `AngledGate.bind_values`: The option `--arg-type-hints-in-signature` is `True` but there are no argument type hints in the signature + DOC109: Method `AngledGate.bind_values`: The option `--arg-type-hints-in-docstring` is `True` but there are no type hints in the docstring arg list + DOC103: Method `AngledGate.bind_values`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [**kwargs: ]. + DOC501: Method `DoubleAngledGate.adjoint` has "raise" statements, but the docstring does not have a "Raises" section + DOC501: Method `TripleAngledGate.adjoint` has "raise" statements, but the docstring does not have a "Raises" section +-------------------- +src/braket/circuits/braket_program_context.py + DOC101: Method `BraketProgramContext.add_gate_instruction`: Docstring contains fewer arguments than in function signature. + DOC103: Method `BraketProgramContext.add_gate_instruction`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [*params: ]. +-------------------- +src/braket/circuits/circuit.py + DOC101: Method `Circuit.__init__`: Docstring contains fewer arguments than in function signature. + DOC103: Method `Circuit.__init__`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [**kwargs: , *args: ]. + DOC502: Method `Circuit.__init__` has a "Raises" section in the docstring, but there are not "raise" statements in the body + DOC105: Method `Circuit.apply_gate_noise`: Argument names match, but type hints do not match + DOC001: Function/method `_validate_parameters`: Potential formatting errors in docstring. Error message: No specification for "Raises": "" + DOC101: Method `Circuit._validate_parameters`: Docstring contains fewer arguments than in function signature. + DOC109: Method `Circuit._validate_parameters`: The option `--arg-type-hints-in-docstring` is `True` but there are no type hints in the docstring arg list + DOC103: Method `Circuit._validate_parameters`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [parameter_values: dict[str, Number]]. + DOC501: Method `Circuit._validate_parameters` has "raise" statements, but the docstring does not have a "Raises" section + DOC101: Method `Circuit.add`: Docstring contains fewer arguments than in function signature. + DOC103: Method `Circuit.add`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [**kwargs: , *args: ]. + DOC502: Method `Circuit.to_unitary` has a "Raises" section in the docstring, but there are not "raise" statements in the body +-------------------- +src/braket/circuits/compiler_directive.py + DOC501: Method `CompilerDirective.__init__` has "raise" statements, but the docstring does not have a "Raises" section + DOC101: Method `CompilerDirective.to_ir`: Docstring contains fewer arguments than in function signature. + DOC103: Method `CompilerDirective.to_ir`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [**kwargs: ]. + DOC501: Method `CompilerDirective.counterpart` has "raise" statements, but the docstring does not have a "Raises" section +-------------------- +src/braket/circuits/gate.py + DOC502: Method `Gate.__init__` has a "Raises" section in the docstring, but there are not "raise" statements in the body + DOC501: Method `Gate.adjoint` has "raise" statements, but the docstring does not have a "Raises" section + DOC001: Function/method `to_ir`: Potential formatting errors in docstring. Error message: Expected a colon in "properties don't correspond to the `ir_type`.". + DOC101: Method `Gate.to_ir`: Docstring contains fewer arguments than in function signature. + DOC109: Method `Gate.to_ir`: The option `--arg-type-hints-in-docstring` is `True` but there are no type hints in the docstring arg list + DOC103: Method `Gate.to_ir`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [control: Optional[QubitSet], control_state: Optional[BasisStateInput], ir_type: IRType, power: float, serialization_properties: Optional[SerializationProperties], target: QubitSet]. + DOC201: Method `Gate.to_ir` does not have a return section in docstring + DOC203: Method `Gate.to_ir` return type(s) in docstring not consistent with the return annotation. Return annotation has 1 type(s); docstring return section has 0 type(s). + DOC501: Method `Gate.to_ir` has "raise" statements, but the docstring does not have a "Raises" section + DOC501: Method `Gate._to_jaqcd` has "raise" statements, but the docstring does not have a "Raises" section +-------------------- +src/braket/circuits/gates.py + DOC105: Method `Unitary.__init__`: Argument names match, but type hints do not match + DOC105: Method `Unitary.unitary`: Argument names match, but type hints do not match + DOC501: Method `PulseGate.__init__` has "raise" statements, but the docstring does not have a "Raises" section + DOC101: Method `PulseGate.bind_values`: Docstring contains fewer arguments than in function signature. + DOC106: Method `PulseGate.bind_values`: The option `--arg-type-hints-in-signature` is `True` but there are no argument type hints in the signature + DOC109: Method `PulseGate.bind_values`: The option `--arg-type-hints-in-docstring` is `True` but there are no type hints in the docstring arg list + DOC103: Method `PulseGate.bind_values`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [**kwargs: ]. +-------------------- +src/braket/circuits/noise.py + DOC502: Method `Noise.__init__` has a "Raises" section in the docstring, but there are not "raise" statements in the body + DOC001: Function/method `to_ir`: Potential formatting errors in docstring. Error message: Expected a colon in "properties don't correspond to the `ir_type`.". + DOC101: Method `Noise.to_ir`: Docstring contains fewer arguments than in function signature. + DOC109: Method `Noise.to_ir`: The option `--arg-type-hints-in-docstring` is `True` but there are no type hints in the docstring arg list + DOC103: Method `Noise.to_ir`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [ir_type: IRType, serialization_properties: SerializationProperties | None, target: QubitSet]. + DOC201: Method `Noise.to_ir` does not have a return section in docstring + DOC203: Method `Noise.to_ir` return type(s) in docstring not consistent with the return annotation. Return annotation has 1 type(s); docstring return section has 0 type(s). + DOC501: Method `Noise.to_ir` has "raise" statements, but the docstring does not have a "Raises" section + DOC501: Method `Noise._to_jaqcd` has "raise" statements, but the docstring does not have a "Raises" section + DOC501: Method `Noise._to_openqasm` has "raise" statements, but the docstring does not have a "Raises" section + DOC101: Method `Noise.to_matrix`: Docstring contains fewer arguments than in function signature. + DOC106: Method `Noise.to_matrix`: The option `--arg-type-hints-in-signature` is `True` but there are no argument type hints in the signature + DOC109: Method `Noise.to_matrix`: The option `--arg-type-hints-in-docstring` is `True` but there are no type hints in the docstring arg list + DOC103: Method `Noise.to_matrix`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [**kwargs: , *args: ]. + DOC203: Method `Noise.to_matrix` return type(s) in docstring not consistent with the return annotation. Return annotation types: ['Iterable[np.ndarray]']; docstring return section types: ['Iterable[ndarray]'] + DOC501: Method `Noise.to_matrix` has "raise" statements, but the docstring does not have a "Raises" section + DOC501: Method `Noise.from_dict` has "raise" statements, but the docstring does not have a "Raises" section + DOC502: Method `SingleProbabilisticNoise.__init__` has a "Raises" section in the docstring, but there are not "raise" statements in the body + DOC101: Method `SingleProbabilisticNoise.bind_values`: Docstring contains fewer arguments than in function signature. + DOC106: Method `SingleProbabilisticNoise.bind_values`: The option `--arg-type-hints-in-signature` is `True` but there are no argument type hints in the signature + DOC109: Method `SingleProbabilisticNoise.bind_values`: The option `--arg-type-hints-in-docstring` is `True` but there are no type hints in the docstring arg list + DOC103: Method `SingleProbabilisticNoise.bind_values`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [**kwargs: ]. + DOC502: Method `SingleProbabilisticNoise_34.__init__` has a "Raises" section in the docstring, but there are not "raise" statements in the body + DOC502: Method `SingleProbabilisticNoise_1516.__init__` has a "Raises" section in the docstring, but there are not "raise" statements in the body + DOC101: Method `MultiQubitPauliNoise.bind_values`: Docstring contains fewer arguments than in function signature. + DOC106: Method `MultiQubitPauliNoise.bind_values`: The option `--arg-type-hints-in-signature` is `True` but there are no argument type hints in the signature + DOC109: Method `MultiQubitPauliNoise.bind_values`: The option `--arg-type-hints-in-docstring` is `True` but there are no type hints in the docstring arg list + DOC103: Method `MultiQubitPauliNoise.bind_values`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [**kwargs: ]. + DOC203: Method `PauliNoise.probX` return type(s) in docstring not consistent with the return annotation. Return annotation types: ['Union[FreeParameterExpression, float]']; docstring return section types: [''] + DOC203: Method `PauliNoise.probY` return type(s) in docstring not consistent with the return annotation. Return annotation types: ['Union[FreeParameterExpression, float]']; docstring return section types: [''] + DOC203: Method `PauliNoise.probZ` return type(s) in docstring not consistent with the return annotation. Return annotation types: ['Union[FreeParameterExpression, float]']; docstring return section types: [''] + DOC101: Method `PauliNoise.bind_values`: Docstring contains fewer arguments than in function signature. + DOC106: Method `PauliNoise.bind_values`: The option `--arg-type-hints-in-signature` is `True` but there are no argument type hints in the signature + DOC109: Method `PauliNoise.bind_values`: The option `--arg-type-hints-in-docstring` is `True` but there are no type hints in the docstring arg list + DOC103: Method `PauliNoise.bind_values`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [**kwargs: ]. + DOC502: Method `DampingNoise.__init__` has a "Raises" section in the docstring, but there are not "raise" statements in the body + DOC101: Method `DampingNoise.bind_values`: Docstring contains fewer arguments than in function signature. + DOC106: Method `DampingNoise.bind_values`: The option `--arg-type-hints-in-signature` is `True` but there are no argument type hints in the signature + DOC109: Method `DampingNoise.bind_values`: The option `--arg-type-hints-in-docstring` is `True` but there are no type hints in the docstring arg list + DOC103: Method `DampingNoise.bind_values`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [**kwargs: ]. + DOC502: Method `GeneralizedAmplitudeDampingNoise.__init__` has a "Raises" section in the docstring, but there are not "raise" statements in the body + DOC501: Function `_validate_param_value` has "raise" statements, but the docstring does not have a "Raises" section +-------------------- +src/braket/circuits/noise_helpers.py + DOC501: Function `check_noise_target_gates` has "raise" statements, but the docstring does not have a "Raises" section + DOC105: Function `check_noise_target_unitary`: Argument names match, but type hints do not match + DOC501: Function `check_noise_target_unitary` has "raise" statements, but the docstring does not have a "Raises" section + DOC501: Function `check_noise_target_qubits` has "raise" statements, but the docstring does not have a "Raises" section + DOC105: Function `apply_noise_to_gates`: Argument names match, but type hints do not match + DOC502: Function `apply_noise_to_gates` has a "Raises" section in the docstring, but there are not "raise" statements in the body +-------------------- +src/braket/circuits/noise_model/criteria.py + DOC501: Method `Criteria.applicable_key_types` has "raise" statements, but the docstring does not have a "Raises" section + DOC501: Method `Criteria.get_keys` has "raise" statements, but the docstring does not have a "Raises" section + DOC501: Method `Criteria.to_dict` has "raise" statements, but the docstring does not have a "Raises" section + DOC501: Method `Criteria.from_dict` has "raise" statements, but the docstring does not have a "Raises" section +-------------------- +src/braket/circuits/noise_model/criteria_input_parsing.py + DOC501: Function `parse_operator_input` has "raise" statements, but the docstring does not have a "Raises" section + DOC501: Function `parse_qubit_input` has "raise" statements, but the docstring does not have a "Raises" section +-------------------- +src/braket/circuits/noise_model/initialization_criteria.py + DOC501: Method `InitializationCriteria.qubit_intersection` has "raise" statements, but the docstring does not have a "Raises" section +-------------------- +src/braket/circuits/noise_model/result_type_criteria.py + DOC501: Method `ResultTypeCriteria.result_type_matches` has "raise" statements, but the docstring does not have a "Raises" section +-------------------- +src/braket/circuits/noises.py + DOC101: Method `PauliChannel.bind_values`: Docstring contains fewer arguments than in function signature. + DOC106: Method `PauliChannel.bind_values`: The option `--arg-type-hints-in-signature` is `True` but there are no argument type hints in the signature + DOC109: Method `PauliChannel.bind_values`: The option `--arg-type-hints-in-docstring` is `True` but there are no type hints in the docstring arg list + DOC103: Method `PauliChannel.bind_values`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [**kwargs: ]. + DOC101: Method `Depolarizing.bind_values`: Docstring contains fewer arguments than in function signature. + DOC106: Method `Depolarizing.bind_values`: The option `--arg-type-hints-in-signature` is `True` but there are no argument type hints in the signature + DOC109: Method `Depolarizing.bind_values`: The option `--arg-type-hints-in-docstring` is `True` but there are no type hints in the docstring arg list + DOC103: Method `Depolarizing.bind_values`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [**kwargs: ]. + DOC101: Method `TwoQubitDepolarizing.bind_values`: Docstring contains fewer arguments than in function signature. + DOC106: Method `TwoQubitDepolarizing.bind_values`: The option `--arg-type-hints-in-signature` is `True` but there are no argument type hints in the signature + DOC109: Method `TwoQubitDepolarizing.bind_values`: The option `--arg-type-hints-in-docstring` is `True` but there are no type hints in the docstring arg list + DOC103: Method `TwoQubitDepolarizing.bind_values`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [**kwargs: ]. + DOC101: Method `TwoQubitDephasing.bind_values`: Docstring contains fewer arguments than in function signature. + DOC106: Method `TwoQubitDephasing.bind_values`: The option `--arg-type-hints-in-signature` is `True` but there are no argument type hints in the signature + DOC109: Method `TwoQubitDephasing.bind_values`: The option `--arg-type-hints-in-docstring` is `True` but there are no type hints in the docstring arg list + DOC103: Method `TwoQubitDephasing.bind_values`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [**kwargs: ]. + DOC101: Method `TwoQubitPauliChannel.bind_values`: Docstring contains fewer arguments than in function signature. + DOC106: Method `TwoQubitPauliChannel.bind_values`: The option `--arg-type-hints-in-signature` is `True` but there are no argument type hints in the signature + DOC109: Method `TwoQubitPauliChannel.bind_values`: The option `--arg-type-hints-in-docstring` is `True` but there are no type hints in the docstring arg list + DOC103: Method `TwoQubitPauliChannel.bind_values`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [**kwargs: ]. + DOC101: Method `AmplitudeDamping.bind_values`: Docstring contains fewer arguments than in function signature. + DOC106: Method `AmplitudeDamping.bind_values`: The option `--arg-type-hints-in-signature` is `True` but there are no argument type hints in the signature + DOC109: Method `AmplitudeDamping.bind_values`: The option `--arg-type-hints-in-docstring` is `True` but there are no type hints in the docstring arg list + DOC103: Method `AmplitudeDamping.bind_values`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [**kwargs: ]. + DOC101: Method `GeneralizedAmplitudeDamping.bind_values`: Docstring contains fewer arguments than in function signature. + DOC106: Method `GeneralizedAmplitudeDamping.bind_values`: The option `--arg-type-hints-in-signature` is `True` but there are no argument type hints in the signature + DOC109: Method `GeneralizedAmplitudeDamping.bind_values`: The option `--arg-type-hints-in-docstring` is `True` but there are no type hints in the docstring arg list + DOC103: Method `GeneralizedAmplitudeDamping.bind_values`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [**kwargs: ]. + DOC101: Method `PhaseDamping.bind_values`: Docstring contains fewer arguments than in function signature. + DOC106: Method `PhaseDamping.bind_values`: The option `--arg-type-hints-in-signature` is `True` but there are no argument type hints in the signature + DOC109: Method `PhaseDamping.bind_values`: The option `--arg-type-hints-in-docstring` is `True` but there are no type hints in the docstring arg list + DOC103: Method `PhaseDamping.bind_values`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [**kwargs: ]. + DOC501: Method `Kraus.kraus` has "raise" statements, but the docstring does not have a "Raises" section + DOC501: Method `Kraus.to_dict` has "raise" statements, but the docstring does not have a "Raises" section + DOC501: Method `Kraus.from_dict` has "raise" statements, but the docstring does not have a "Raises" section +-------------------- +src/braket/circuits/observable.py + DOC501: Method `Observable._to_openqasm` has "raise" statements, but the docstring does not have a "Raises" section + DOC501: Method `Observable.basis_rotation_gates` has "raise" statements, but the docstring does not have a "Raises" section + DOC501: Method `Observable.eigenvalues` has "raise" statements, but the docstring does not have a "Raises" section + DOC501: Method `Observable.eigenvalue` has "raise" statements, but the docstring does not have a "Raises" section +-------------------- +src/braket/circuits/observables.py + DOC501: Method `TensorProduct.__init__` has "raise" statements, but the docstring does not have a "Raises" section + DOC501: Method `TensorProduct.eigenvalue` has "raise" statements, but the docstring does not have a "Raises" section +-------------------- +src/braket/circuits/operator.py + DOC101: Method `Operator.to_ir`: Docstring contains fewer arguments than in function signature. + DOC106: Method `Operator.to_ir`: The option `--arg-type-hints-in-signature` is `True` but there are no argument type hints in the signature + DOC109: Method `Operator.to_ir`: The option `--arg-type-hints-in-docstring` is `True` but there are no type hints in the docstring arg list + DOC103: Method `Operator.to_ir`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [**kwargs: , *args: ]. +-------------------- +src/braket/circuits/result_type.py + DOC101: Method `ResultType.to_ir`: Docstring contains fewer arguments than in function signature. + DOC103: Method `ResultType.to_ir`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [**kwargs: ]. +-------------------- +src/braket/devices/local_simulator.py + DOC101: Method `LocalSimulator.run_batch`: Docstring contains fewer arguments than in function signature. + DOC103: Method `LocalSimulator.run_batch`: Docstring arguments are different from function arguments. (Or could be other formatting issues: https://jsh9.github.io/pydoclint/violation_codes.html#notes-on-doc103 ). Arguments in the function signature but not in the docstring: [**kwargs: , *args: ]. + DOC501: Method `LocalSimulator.run_batch` has "raise" statements, but the docstring does not have a "Raises" section +-------------------- +src/braket/tasks/gate_model_quantum_task_result.py + DOC502: Method `GateModelQuantumTaskResult.from_object` has a "Raises" section in the docstring, but there are not "raise" statements in the body + DOC502: Method `GateModelQuantumTaskResult.from_string` has a "Raises" section in the docstring, but there are not "raise" statements in the body +-------------------- diff --git a/setup.cfg b/setup.cfg index 3bad103a3..d9dbb5b62 100644 --- a/setup.cfg +++ b/setup.cfg @@ -39,6 +39,3 @@ exclude = bin build venv -rst-roles = - # Python programming language: - py:func,py:mod,mod diff --git a/src/braket/_sdk/_version.py b/src/braket/_sdk/_version.py index af639799b..fc41f12eb 100644 --- a/src/braket/_sdk/_version.py +++ b/src/braket/_sdk/_version.py @@ -12,7 +12,7 @@ # language governing permissions and limitations under the License. """Version information. - Version number (major.minor.patch[-label]) +Version number (major.minor.patch[-label]) """ __version__ = "1.70.3.dev0" diff --git a/src/braket/ahs/analog_hamiltonian_simulation.py b/src/braket/ahs/analog_hamiltonian_simulation.py index b02091d4f..8d8cce10f 100644 --- a/src/braket/ahs/analog_hamiltonian_simulation.py +++ b/src/braket/ahs/analog_hamiltonian_simulation.py @@ -54,7 +54,7 @@ def to_ir(self) -> ir.Program: representation. Returns: - Program: A representation of the circuit in the IR format. + ir.Program: A representation of the circuit in the IR format. """ return ir.Program( setup=ir.Setup(ahs_register=self._register_to_ir()), @@ -77,7 +77,7 @@ def _hamiltonian_to_ir(self) -> ir.Hamiltonian: shiftingFields=terms[AnalogHamiltonianSimulation.SHIFTING_FIELDS_PROPERTY], ) - def discretize(self, device) -> AnalogHamiltonianSimulation: # noqa + def discretize(self, device: AwsDevice) -> AnalogHamiltonianSimulation: # noqa """Creates a new AnalogHamiltonianSimulation with all numerical values represented as Decimal objects with fixed precision based on the capabilities of the device. @@ -88,9 +88,8 @@ def discretize(self, device) -> AnalogHamiltonianSimulation: # noqa AnalogHamiltonianSimulation: A discretized version of this program. Raises: - DiscretizeError: If unable to discretize the program. + DiscretizationError: If unable to discretize the program. """ - required_action_schema = DeviceActionType.AHS if (required_action_schema not in device.properties.action) or ( device.properties.action[required_action_schema].actionType != required_action_schema diff --git a/src/braket/ahs/atom_arrangement.py b/src/braket/ahs/atom_arrangement.py index bb7088347..1d47a66b8 100644 --- a/src/braket/ahs/atom_arrangement.py +++ b/src/braket/ahs/atom_arrangement.py @@ -73,6 +73,7 @@ def add( atom (in meters). The coordinates can be a numpy array of shape (2,) or a tuple of int, float, Decimal site_type (SiteType): The type of site. Optional. Default is FILLED. + Returns: AtomArrangement: returns self (to allow for chaining). """ @@ -109,6 +110,9 @@ def discretize(self, properties: DiscretizationProperties) -> AtomArrangement: properties (DiscretizationProperties): Capabilities of a device that represent the resolution with which the device can implement the parameters. + Raises: + DiscretizationError: If unable to discretize the program. + Returns: AtomArrangement: A new discretized atom arrangement. """ @@ -117,7 +121,7 @@ def discretize(self, properties: DiscretizationProperties) -> AtomArrangement: discretized_arrangement = AtomArrangement() for site in self._sites: new_coordinates = tuple( - (round(Decimal(c) / position_res) * position_res for c in site.coordinate) + round(Decimal(c) / position_res) * position_res for c in site.coordinate ) discretized_arrangement.add(new_coordinates, site.site_type) return discretized_arrangement diff --git a/src/braket/ahs/driving_field.py b/src/braket/ahs/driving_field.py index 02c8bd276..f6c6430f2 100644 --- a/src/braket/ahs/driving_field.py +++ b/src/braket/ahs/driving_field.py @@ -104,7 +104,6 @@ def stitch( Returns: DrivingField: The stitched DrivingField object. """ - amplitude = self.amplitude.time_series.stitch(other.amplitude.time_series, boundary) detuning = self.detuning.time_series.stitch(other.detuning.time_series, boundary) phase = self.phase.time_series.stitch(other.phase.time_series, boundary) @@ -143,8 +142,7 @@ def discretize(self, properties: DiscretizationProperties) -> DrivingField: def from_lists( times: list[float], amplitudes: list[float], detunings: list[float], phases: list[float] ) -> DrivingField: - """ - Builds DrivingField Hamiltonian from lists defining time evolution + """Builds DrivingField Hamiltonian from lists defining time evolution of Hamiltonian parameters (Rabi frequency, detuning, phase). The values of the parameters at each time points are global for all atoms. @@ -154,6 +152,9 @@ def from_lists( detunings (list[float]): The values of the detuning phases (list[float]): The values of the phase + Raises: + ValueError: If any of the input args length is different from the rest. + Returns: DrivingField: DrivingField Hamiltonian. """ diff --git a/src/braket/ahs/pattern.py b/src/braket/ahs/pattern.py index 17e40a36f..462f0e369 100644 --- a/src/braket/ahs/pattern.py +++ b/src/braket/ahs/pattern.py @@ -30,7 +30,8 @@ def __init__(self, series: list[Number]): @property def series(self) -> list[Number]: """list[Number]: A series of numbers representing the local - pattern of real numbers.""" + pattern of real numbers. + """ return self._series def discretize(self, resolution: Decimal) -> Pattern: diff --git a/src/braket/ahs/shifting_field.py b/src/braket/ahs/shifting_field.py index 846d7ad2e..7bed1fe8a 100644 --- a/src/braket/ahs/shifting_field.py +++ b/src/braket/ahs/shifting_field.py @@ -56,7 +56,8 @@ def terms(self) -> list[Hamiltonian]: def magnitude(self) -> Field: r"""Field: containing the global magnitude time series :math:`\Delta(t)`, where time is measured in seconds (s) and values measured in rad/s) - and the local pattern :math:`h_k` of dimensionless real numbers between 0 and 1.""" + and the local pattern :math:`h_k` of dimensionless real numbers between 0 and 1. + """ return self._magnitude @staticmethod @@ -68,6 +69,9 @@ def from_lists(times: list[float], values: list[float], pattern: list[float]) -> values (list[float]): The values of the shifting field pattern (list[float]): The pattern of the shifting field + Raises: + ValueError: If the length of times and values differs. + Returns: ShiftingField: The shifting field obtained """ @@ -99,6 +103,9 @@ def stitch( - "left" - use the last value from the left time series as the boundary point. - "right" - use the first value from the right time series as the boundary point. + Raises: + ValueError: The ShiftingField patterns differ. + Returns: ShiftingField: The stitched ShiftingField object. diff --git a/src/braket/annealing/problem.py b/src/braket/annealing/problem.py index d8b40c372..d55de4e6e 100644 --- a/src/braket/annealing/problem.py +++ b/src/braket/annealing/problem.py @@ -14,7 +14,6 @@ from __future__ import annotations from enum import Enum -from typing import Dict, Tuple import braket.ir.annealing as ir @@ -37,16 +36,16 @@ class Problem: def __init__( self, problem_type: ProblemType, - linear: Dict[int, float] | None = None, - quadratic: Dict[Tuple[int, int], float] | None = None, + linear: dict[int, float] | None = None, + quadratic: dict[tuple[int, int], float] | None = None, ): - """ + """Initialzes a `Problem`. Args: problem_type (ProblemType): The type of annealing problem - linear (Dict[int, float] | None): The linear terms of this problem, + linear (dict[int, float] | None): The linear terms of this problem, as a map of variable to coefficient - quadratic (Dict[Tuple[int, int], float] | None): The quadratic terms of this problem, + quadratic (dict[tuple[int, int], float] | None): The quadratic terms of this problem, as a map of variables to coefficient Examples: @@ -71,20 +70,20 @@ def problem_type(self) -> ProblemType: return self._problem_type @property - def linear(self) -> Dict[int, float]: + def linear(self) -> dict[int, float]: """The linear terms of this problem. Returns: - Dict[int, float]: The linear terms of this problem, as a map of variable to coefficient + dict[int, float]: The linear terms of this problem, as a map of variable to coefficient """ return self._linear @property - def quadratic(self) -> Dict[Tuple[int, int], float]: + def quadratic(self) -> dict[tuple[int, int], float]: """The quadratic terms of this problem. Returns: - Dict[Tuple[int, int], float]: The quadratic terms of this problem, + dict[tuple[int, int], float]: The quadratic terms of this problem, as a map of variables to coefficient """ return self._quadratic @@ -102,11 +101,11 @@ def add_linear_term(self, term: int, coefficient: float) -> Problem: self._linear[term] = coefficient return self - def add_linear_terms(self, coefficients: Dict[int, float]) -> Problem: + def add_linear_terms(self, coefficients: dict[int, float]) -> Problem: """Adds linear terms to the problem. Args: - coefficients (Dict[int, float]): A map of variable to coefficient + coefficients (dict[int, float]): A map of variable to coefficient Returns: Problem: This problem object @@ -114,11 +113,11 @@ def add_linear_terms(self, coefficients: Dict[int, float]) -> Problem: self._linear.update(coefficients) return self - def add_quadratic_term(self, term: Tuple[int, int], coefficient: float) -> Problem: + def add_quadratic_term(self, term: tuple[int, int], coefficient: float) -> Problem: """Adds a quadratic term to the problem. Args: - term (Tuple[int, int]): The variables of the quadratic term + term (tuple[int, int]): The variables of the quadratic term coefficient (float): The coefficient of the quadratic term Returns: @@ -127,11 +126,11 @@ def add_quadratic_term(self, term: Tuple[int, int], coefficient: float) -> Probl self._quadratic[term] = coefficient return self - def add_quadratic_terms(self, coefficients: Dict[Tuple[int, int], float]) -> Problem: + def add_quadratic_terms(self, coefficients: dict[tuple[int, int], float]) -> Problem: """Adds quadratic terms to the problem. Args: - coefficients (Dict[Tuple[int, int], float]): A map of variables to coefficient + coefficients (dict[tuple[int, int], float]): A map of variables to coefficient Returns: Problem: This problem object diff --git a/src/braket/aws/aws_device.py b/src/braket/aws/aws_device.py index ee9c4128b..43780aa38 100644 --- a/src/braket/aws/aws_device.py +++ b/src/braket/aws/aws_device.py @@ -20,7 +20,7 @@ import warnings from datetime import datetime from enum import Enum -from typing import Optional, Union +from typing import Any, ClassVar, Optional, Union from botocore.errorfactory import ClientError from networkx import DiGraph, complete_graph, from_edgelist @@ -36,9 +36,9 @@ from braket.circuits.noise_model import NoiseModel from braket.device_schema import DeviceCapabilities, ExecutionDay, GateModelQpuParadigmProperties from braket.device_schema.dwave import DwaveProviderProperties -from braket.device_schema.pulse.pulse_device_action_properties_v1 import ( # noqa TODO: Remove device_action module once this is added to init in the schemas repo - PulseDeviceActionProperties, -) + +# TODO: Remove device_action module once this is added to init in the schemas repo +from braket.device_schema.pulse.pulse_device_action_properties_v1 import PulseDeviceActionProperties from braket.devices.device import Device from braket.ir.blackbird import Program as BlackbirdProgram from braket.ir.openqasm import Program as OpenQasmProgram @@ -57,8 +57,7 @@ class AwsDeviceType(str, Enum): class AwsDevice(Device): - """ - Amazon Braket implementation of a device. + """Amazon Braket implementation of a device. Use this class to retrieve the latest metadata about the device and to run a quantum task on the device. """ @@ -71,7 +70,7 @@ class AwsDevice(Device): _GET_DEVICES_ORDER_BY_KEYS = frozenset({"arn", "name", "type", "provider_name", "status"}) - _RIGETTI_GATES_TO_BRAKET = { + _RIGETTI_GATES_TO_BRAKET: ClassVar[dict[str, str | None]] = { # Rx_12 does not exist in the Braket SDK, it is a gate between |1> and |2>. "Rx_12": None, "Cz": "CZ", @@ -85,7 +84,8 @@ def __init__( aws_session: Optional[AwsSession] = None, noise_model: Optional[NoiseModel] = None, ): - """ + """Initializes an `AwsDevice`. + Args: arn (str): The ARN of the device aws_session (Optional[AwsSession]): An AWS session object. Default is `None`. @@ -134,15 +134,14 @@ def run( inputs: Optional[dict[str, float]] = None, gate_definitions: Optional[dict[tuple[Gate, QubitSet], PulseSequence]] = None, reservation_arn: str | None = None, - *aws_quantum_task_args, - **aws_quantum_task_kwargs, + *aws_quantum_task_args: Any, + **aws_quantum_task_kwargs: Any, ) -> AwsQuantumTask: - """ - Run a quantum task specification on this device. A quantum task can be a circuit or an + """Run a quantum task specification on this device. A quantum task can be a circuit or an annealing problem. Args: - task_specification (Union[Circuit, Problem, OpenQasmProgram, BlackbirdProgram, PulseSequence, AnalogHamiltonianSimulation]): # noqa + task_specification (Union[Circuit, Problem, OpenQasmProgram, BlackbirdProgram, PulseSequence, AnalogHamiltonianSimulation]): Specification of quantum task (circuit, OpenQASM program or AHS program) to run on device. s3_destination_folder (Optional[S3DestinationFolder]): The S3 location to @@ -168,6 +167,8 @@ def run( Note: If you are creating tasks in a job that itself was created reservation ARN, those tasks do not need to be created with the reservation ARN. Default: None. + *aws_quantum_task_args (Any): Arbitrary arguments. + **aws_quantum_task_kwargs (Any): Arbitrary keyword arguments. Returns: AwsQuantumTask: An AwsQuantumTask that tracks the execution on the device. @@ -200,7 +201,7 @@ def run( See Also: `braket.aws.aws_quantum_task.AwsQuantumTask.create()` - """ + """ # noqa E501 if self._noise_model: task_specification = self._apply_noise_model_to_circuit(task_specification) return AwsQuantumTask.create( @@ -297,7 +298,7 @@ def run_batch( See Also: `braket.aws.aws_quantum_task_batch.AwsQuantumTaskBatch` - """ + """ # noqa E501 if self._noise_model: task_specifications = [ self._apply_noise_model_to_circuit(task_specification) @@ -327,9 +328,7 @@ def run_batch( ) def refresh_metadata(self) -> None: - """ - Refresh the `AwsDevice` object with the most recent Device metadata. - """ + """Refresh the `AwsDevice` object with the most recent Device metadata.""" self._populate_properties(self._aws_session) def _get_session_and_initialize(self, session: AwsSession) -> AwsSession: @@ -417,8 +416,7 @@ def arn(self) -> str: @property def gate_calibrations(self) -> Optional[GateCalibrations]: - """ - Calibration data for a QPU. Calibration data is shown for gates on particular gubits. + """Calibration data for a QPU. Calibration data is shown for gates on particular gubits. If a QPU does not expose these calibrations, None is returned. Returns: @@ -432,6 +430,7 @@ def gate_calibrations(self) -> Optional[GateCalibrations]: @property def is_available(self) -> bool: """Returns true if the device is currently available. + Returns: bool: Return if the device is currently available. """ @@ -493,7 +492,8 @@ def properties(self) -> DeviceCapabilities: Please see `braket.device_schema` in amazon-braket-schemas-python_ - .. _amazon-braket-schemas-python: https://github.com/aws/amazon-braket-schemas-python""" + .. _amazon-braket-schemas-python: https://github.com/aws/amazon-braket-schemas-python + """ return self._properties @property @@ -519,8 +519,7 @@ def topology_graph(self) -> DiGraph: return self._topology_graph def _construct_topology_graph(self) -> DiGraph: - """ - Construct topology graph. If no such metadata is available, return `None`. + """Construct topology graph. If no such metadata is available, return `None`. Returns: DiGraph: topology of QPU as a networkx `DiGraph` object. @@ -557,9 +556,9 @@ def _default_max_parallel(self) -> int: return AwsDevice.DEFAULT_MAX_PARALLEL def __repr__(self): - return "Device('name': {}, 'arn': {})".format(self.name, self.arn) + return f"Device('name': {self.name}, 'arn': {self.arn})" - def __eq__(self, other): + def __eq__(self, other: AwsDevice): if isinstance(other, AwsDevice): return self.arn == other.arn return NotImplemented @@ -567,16 +566,18 @@ def __eq__(self, other): @property def frames(self) -> dict[str, Frame]: """Returns a dict mapping frame ids to the frame objects for predefined frames - for this device.""" + for this device. + """ self._update_pulse_properties() - return self._frames or dict() + return self._frames or {} @property def ports(self) -> dict[str, Port]: """Returns a dict mapping port ids to the port objects for predefined ports - for this device.""" + for this device. + """ self._update_pulse_properties() - return self._ports or dict() + return self._ports or {} @staticmethod def get_devices( @@ -588,8 +589,7 @@ def get_devices( order_by: str = "name", aws_session: Optional[AwsSession] = None, ) -> list[AwsDevice]: - """ - Get devices based on filters and desired ordering. The result is the AND of + """Get devices based on filters and desired ordering. The result is the AND of all the filters `arns`, `names`, `types`, `statuses`, `provider_names`. Examples: @@ -612,17 +612,17 @@ def get_devices( aws_session (Optional[AwsSession]): An AWS session object. Default is `None`. + Raises: + ValueError: order_by not in ['arn', 'name', 'type', 'provider_name', 'status'] + Returns: list[AwsDevice]: list of AWS devices """ - if order_by not in AwsDevice._GET_DEVICES_ORDER_BY_KEYS: raise ValueError( f"order_by '{order_by}' must be in {AwsDevice._GET_DEVICES_ORDER_BY_KEYS}" ) - types = ( - frozenset(types) if types else frozenset({device_type for device_type in AwsDeviceType}) - ) + types = frozenset(types or AwsDeviceType) aws_session = aws_session if aws_session else AwsSession() device_map = {} session_region = aws_session.boto_session.region_name @@ -662,7 +662,8 @@ def get_devices( warnings.warn( f"{error_code}: Unable to search region '{region}' for devices." " Please check your settings or try again later." - f" Continuing without devices in '{region}'." + f" Continuing without devices in '{region}'.", + stacklevel=1, ) devices = list(device_map.values()) @@ -674,14 +675,14 @@ def _update_pulse_properties(self) -> None: self.properties.pulse, PulseDeviceActionProperties ): if self._ports is None: - self._ports = dict() + self._ports = {} port_data = self.properties.pulse.ports for port_id, port in port_data.items(): self._ports[port_id] = Port( port_id=port_id, dt=port.dt, properties=json.loads(port.json()) ) if self._frames is None: - self._frames = dict() + self._frames = {} frame_data = self.properties.pulse.frames if frame_data: for frame_id, frame in frame_data.items(): @@ -697,6 +698,7 @@ def _update_pulse_properties(self) -> None: @staticmethod def get_device_region(device_arn: str) -> str: """Gets the region from a device arn. + Args: device_arn (str): The device ARN. @@ -715,8 +717,7 @@ def get_device_region(device_arn: str) -> str: ) def queue_depth(self) -> QueueDepthInfo: - """ - Task queue depth refers to the total number of quantum tasks currently waiting + """Task queue depth refers to the total number of quantum tasks currently waiting to run on a particular device. Returns: @@ -763,8 +764,7 @@ def queue_depth(self) -> QueueDepthInfo: return QueueDepthInfo(**queue_info) def refresh_gate_calibrations(self) -> Optional[GateCalibrations]: - """ - Refreshes the gate calibration data upon request. + """Refreshes the gate calibration data upon request. If the device does not have calibration data, None is returned. @@ -796,7 +796,7 @@ def refresh_gate_calibrations(self) -> Optional[GateCalibrations]: return None def _parse_waveforms(self, waveforms_json: dict) -> dict: - waveforms = dict() + waveforms = {} for waveform in waveforms_json: parsed_waveform = _parse_waveform_from_calibration_schema(waveforms_json[waveform]) waveforms[parsed_waveform.id] = parsed_waveform @@ -810,8 +810,7 @@ def _parse_pulse_sequence( def _parse_calibration_json( self, calibration_data: dict ) -> dict[tuple[Gate, QubitSet], PulseSequence]: - """ - Takes the json string from the device calibration URL and returns a structured dictionary of + """Takes the json string from the device calibration URL and returns a structured dictionary of corresponding `dict[tuple[Gate, QubitSet], PulseSequence]` to represent the calibration data. Args: diff --git a/src/braket/aws/aws_quantum_job.py b/src/braket/aws/aws_quantum_job.py index 31347311e..711aeab1b 100644 --- a/src/braket/aws/aws_quantum_job.py +++ b/src/braket/aws/aws_quantum_job.py @@ -20,7 +20,7 @@ from enum import Enum from logging import Logger, getLogger from pathlib import Path -from typing import Any +from typing import Any, ClassVar import boto3 from botocore.exceptions import ClientError @@ -49,12 +49,14 @@ class AwsQuantumJob(QuantumJob): """Amazon Braket implementation of a quantum job.""" - TERMINAL_STATES = {"CANCELLED", "COMPLETED", "FAILED"} + TERMINAL_STATES: ClassVar[set[str]] = {"CANCELLED", "COMPLETED", "FAILED"} RESULTS_FILENAME = "results.json" RESULTS_TAR_FILENAME = "model.tar.gz" LOG_GROUP = "/aws/braket/jobs" class LogState(Enum): + """Log state enum.""" + TAILING = "tailing" JOB_COMPLETE = "job_complete" COMPLETE = "complete" @@ -223,7 +225,8 @@ def create( return job def __init__(self, arn: str, aws_session: AwsSession | None = None, quiet: bool = False): - """ + """Initializes an `AwsQuantumJob`. + Args: arn (str): The ARN of the hybrid job. aws_session (AwsSession | None): The `AwsSession` for connecting to AWS services. @@ -231,6 +234,9 @@ def __init__(self, arn: str, aws_session: AwsSession | None = None, quiet: bool region of the hybrid job. quiet (bool): Sets the verbosity of the logger to low and does not report queue position. Default is `False`. + + Raises: + ValueError: Supplied region and session region do not match. """ self._arn: str = arn self._quiet = quiet @@ -246,8 +252,11 @@ def __init__(self, arn: str, aws_session: AwsSession | None = None, quiet: bool @staticmethod def _is_valid_aws_session_region_for_job_arn(aws_session: AwsSession, job_arn: str) -> bool: - """ - bool: `True` when the aws_session region matches the job_arn region; otherwise `False`. + """Checks whether the job region and session region match. + + Returns: + bool: `True` when the aws_session region matches the job_arn region; otherwise + `False`. """ job_region = job_arn.split(":")[3] return job_region == aws_session.region @@ -285,6 +294,7 @@ def state(self, use_cached_value: bool = False) -> str: value from the Amazon Braket `GetJob` operation. If `False`, calls the `GetJob` operation to retrieve metadata, which also updates the cached value. Default = `False`. + Returns: str: The value of `status` in `metadata()`. This is the value of the `status` key in the Amazon Braket `GetJob` operation. @@ -295,8 +305,7 @@ def state(self, use_cached_value: bool = False) -> str: return self.metadata(use_cached_value).get("status") def queue_position(self) -> HybridJobQueueInfo: - """ - The queue position details for the hybrid job. + """The queue position details for the hybrid job. Returns: HybridJobQueueInfo: Instance of HybridJobQueueInfo class representing @@ -413,6 +422,7 @@ def metadata(self, use_cached_value: bool = False) -> dict[str, Any]: from the Amazon Braket `GetJob` operation, if it exists; if does not exist, `GetJob` is called to retrieve the metadata. If `False`, always calls `GetJob`, which also updates the cached value. Default: `False`. + Returns: dict[str, Any]: Dict that specifies the hybrid job metadata defined in Amazon Braket. """ @@ -441,7 +451,7 @@ def metrics( when there is a conflict. Default: MetricStatistic.MAX. Returns: - dict[str, list[Any]] : The metrics data. + dict[str, list[Any]]: The metrics data. """ fetcher = CwlInsightsMetricsFetcher(self._aws_session) metadata = self.metadata(True) @@ -471,7 +481,7 @@ def result( poll_timeout_seconds: float = QuantumJob.DEFAULT_RESULTS_POLL_TIMEOUT, poll_interval_seconds: float = QuantumJob.DEFAULT_RESULTS_POLL_INTERVAL, ) -> dict[str, Any]: - """Retrieves the hybrid job result persisted using save_job_result() function. + """Retrieves the hybrid job result persisted using the `save_job_result` function. Args: poll_timeout_seconds (float): The polling timeout, in seconds, for `result()`. @@ -486,7 +496,6 @@ def result( RuntimeError: if hybrid job is in a FAILED or CANCELLED state. TimeoutError: if hybrid job execution exceeds the polling timeout period. """ - with tempfile.TemporaryDirectory() as temp_dir: job_name = self.metadata(True)["jobName"] @@ -526,7 +535,6 @@ def download_result( RuntimeError: if hybrid job is in a FAILED or CANCELLED state. TimeoutError: if hybrid job execution exceeds the polling timeout period. """ - extract_to = extract_to or Path.cwd() timeout_time = time.time() + poll_timeout_seconds @@ -576,7 +584,7 @@ def _extract_tar_file(extract_path: str) -> None: def __repr__(self) -> str: return f"AwsQuantumJob('arn':'{self.arn}')" - def __eq__(self, other) -> bool: + def __eq__(self, other: AwsQuantumJob) -> bool: if isinstance(other, AwsQuantumJob): return self.arn == other.arn return False diff --git a/src/braket/aws/aws_quantum_task.py b/src/braket/aws/aws_quantum_task.py index 34f22ae17..c6ad36b27 100644 --- a/src/braket/aws/aws_quantum_task.py +++ b/src/braket/aws/aws_quantum_task.py @@ -17,7 +17,7 @@ import time from functools import singledispatch from logging import Logger, getLogger -from typing import Any, Optional, Union +from typing import Any, ClassVar, Optional, Union import boto3 @@ -75,12 +75,13 @@ class AwsQuantumTask(QuantumTask): """Amazon Braket implementation of a quantum task. A quantum task can be a circuit, - an OpenQASM program or an AHS program.""" + an OpenQASM program or an AHS program. + """ # TODO: Add API documentation that defines these states. Make it clear this is the contract. - NO_RESULT_TERMINAL_STATES = {"FAILED", "CANCELLED"} - RESULTS_READY_STATES = {"COMPLETED"} - TERMINAL_STATES = RESULTS_READY_STATES.union(NO_RESULT_TERMINAL_STATES) + NO_RESULT_TERMINAL_STATES: ClassVar[set[str]] = {"FAILED", "CANCELLED"} + RESULTS_READY_STATES: ClassVar[set[str]] = {"COMPLETED"} + TERMINAL_STATES: ClassVar[set[str]] = RESULTS_READY_STATES.union(NO_RESULT_TERMINAL_STATES) DEFAULT_RESULTS_POLL_TIMEOUT = 432000 DEFAULT_RESULTS_POLL_INTERVAL = 1 @@ -174,7 +175,7 @@ def create( See Also: `braket.aws.aws_quantum_simulator.AwsQuantumSimulator.run()` `braket.aws.aws_qpu.AwsQpu.run()` - """ + """ # noqa E501 if len(s3_destination_folder) != 2: raise ValueError( "s3_destination_folder must be of size 2 with a 'bucket' and 'key' respectively." @@ -207,7 +208,7 @@ def create( unbounded_parameters = param_names - set(inputs.keys()) if unbounded_parameters: raise ValueError( - f"Cannot execute circuit with unbound parameters: " f"{unbounded_parameters}" + f"Cannot execute circuit with unbound parameters: {unbounded_parameters}" ) return _create_internal( @@ -233,7 +234,8 @@ def __init__( logger: Logger = getLogger(__name__), quiet: bool = False, ): - """ + """Initializes an `AwsQuantumTask`. + Args: arn (str): The ARN of the quantum task. aws_session (AwsSession | None): The `AwsSession` for connecting to AWS services. @@ -258,7 +260,6 @@ def __init__( >>> result = task.result() GateModelQuantumTaskResult(...) """ - self._arn: str = arn self._aws_session: AwsSession = aws_session or AwsQuantumTask._aws_session_for_task_arn( task_arn=arn @@ -276,9 +277,8 @@ def __init__( @staticmethod def _aws_session_for_task_arn(task_arn: str) -> AwsSession: - """ - Get an AwsSession for the Quantum Task ARN. The AWS session should be in the region of the - quantum task. + """Get an AwsSession for the Quantum Task ARN. The AWS session should be in the region of + the quantum task. Returns: AwsSession: `AwsSession` object with default `boto_session` in quantum task's region. @@ -302,19 +302,20 @@ def _cancel_future(self) -> None: def cancel(self) -> None: """Cancel the quantum task. This cancels the future and the quantum task in Amazon - Braket.""" + Braket. + """ self._cancel_future() self._aws_session.cancel_quantum_task(self._arn) def metadata(self, use_cached_value: bool = False) -> dict[str, Any]: - """ - Get quantum task metadata defined in Amazon Braket. + """Get quantum task metadata defined in Amazon Braket. Args: use_cached_value (bool): If `True`, uses the value most recently retrieved from the Amazon Braket `GetQuantumTask` operation, if it exists; if not, `GetQuantumTask` will be called to retrieve the metadata. If `False`, always calls `GetQuantumTask`, which also updates the cached value. Default: `False`. + Returns: dict[str, Any]: The response from the Amazon Braket `GetQuantumTask` operation. If `use_cached_value` is `True`, Amazon Braket is not called and the most recently @@ -326,26 +327,26 @@ def metadata(self, use_cached_value: bool = False) -> dict[str, Any]: return self._metadata def state(self, use_cached_value: bool = False) -> str: - """ - The state of the quantum task. + """The state of the quantum task. Args: use_cached_value (bool): If `True`, uses the value most recently retrieved from the Amazon Braket `GetQuantumTask` operation. If `False`, calls the `GetQuantumTask` operation to retrieve metadata, which also updates the cached value. Default = `False`. + Returns: str: The value of `status` in `metadata()`. This is the value of the `status` key in the Amazon Braket `GetQuantumTask` operation. If `use_cached_value` is `True`, the value most recently returned from the `GetQuantumTask` operation is used. + See Also: `metadata()` """ return self._status(use_cached_value) def queue_position(self) -> QuantumTaskQueueInfo: - """ - The queue position details for the quantum task. + """The queue position details for the quantum task. Returns: QuantumTaskQueueInfo: Instance of QuantumTaskQueueInfo class @@ -399,8 +400,7 @@ def result( ) -> Union[ GateModelQuantumTaskResult, AnnealingQuantumTaskResult, PhotonicModelQuantumTaskResult ]: - """ - Get the quantum task result by polling Amazon Braket to see if the task is completed. + """Get the quantum task result by polling Amazon Braket to see if the task is completed. Once the quantum task is completed, the result is retrieved from S3 and returned as a `GateModelQuantumTaskResult` or `AnnealingQuantumTaskResult` @@ -409,10 +409,10 @@ def result( Consecutive calls to this method return a cached result from the preceding request. Returns: - Union[GateModelQuantumTaskResult, AnnealingQuantumTaskResult, PhotonicModelQuantumTaskResult]: # noqa - The result of the quantum task, if the quantum task completed successfully; returns + Union[GateModelQuantumTaskResult, AnnealingQuantumTaskResult, PhotonicModelQuantumTaskResult]: The + result of the quantum task, if the quantum task completed successfully; returns `None` if the quantum task did not complete successfully or the future timed out. - """ + """ # noqa E501 if self._result or ( self._metadata and self._status(True) in self.NO_RESULT_TERMINAL_STATES ): @@ -445,15 +445,13 @@ def _get_future(self) -> asyncio.Future: return self._future def async_result(self) -> asyncio.Task: - """ - Get the quantum task result asynchronously. Consecutive calls to this method return + """Get the quantum task result asynchronously. Consecutive calls to this method return the result cached from the most recent request. """ return self._get_future() async def _create_future(self) -> asyncio.Task: - """ - Wrap the `_wait_for_completion` coroutine inside a future-like object. + """Wrap the `_wait_for_completion` coroutine inside a future-like object. Invoking this method starts the coroutine and returns back the future-like object that contains it. Note that this does not block on the coroutine to finish. @@ -467,19 +465,19 @@ async def _wait_for_completion( ) -> Union[ GateModelQuantumTaskResult, AnnealingQuantumTaskResult, PhotonicModelQuantumTaskResult ]: - """ - Waits for the quantum task to be completed, then returns the result from the S3 bucket. + """Waits for the quantum task to be completed, then returns the result from the S3 bucket. Returns: - Union[GateModelQuantumTaskResult, AnnealingQuantumTaskResult]: If the task is in the + Union[GateModelQuantumTaskResult, AnnealingQuantumTaskResult, PhotonicModelQuantumTaskResult]: If the task is in the `AwsQuantumTask.RESULTS_READY_STATES` state within the specified time limit, the result from the S3 bucket is loaded and returned. `None` is returned if a timeout occurs or task state is in `AwsQuantumTask.NO_RESULT_TERMINAL_STATES`. + Note: Timeout and sleep intervals are defined in the constructor fields `poll_timeout_seconds` and `poll_interval_seconds` respectively. - """ + """ # noqa E501 self._logger.debug(f"Task {self._arn}: start polling for completion") start_time = time.time() @@ -545,7 +543,7 @@ def _download_result( def __repr__(self) -> str: return f"AwsQuantumTask('id/taskArn':'{self.id}')" - def __eq__(self, other) -> bool: + def __eq__(self, other: AwsQuantumTask) -> bool: if isinstance(other, AwsQuantumTask): return self.id == other.id return False @@ -621,7 +619,7 @@ def _( device_arn, GateModelParameters(qubitCount=0), # qubitCount unused ) - if type(device_parameters) is dict + if isinstance(device_parameters, dict) else device_parameters ) create_task_kwargs.update( @@ -671,7 +669,7 @@ def _( ) final_device_parameters = ( _circuit_device_params_from_dict(device_parameters or {}, device_arn, paradigm_parameters) - if type(device_parameters) is dict + if isinstance(device_parameters, dict) else device_parameters ) @@ -725,7 +723,7 @@ def _( DwaveAdvantageDeviceParameters, Dwave2000QDeviceParameters, ], - _, + _: bool, inputs: dict[str, float], gate_definitions: Optional[dict[tuple[Gate, QubitSet], PulseSequence]], *args, @@ -750,7 +748,7 @@ def _( create_task_kwargs: dict[str, Any], device_arn: str, device_parameters: dict, - _, + _: AnalogHamiltonianSimulationTaskResult, inputs: dict[str, float], gate_definitions: Optional[dict[tuple[Gate, QubitSet], PulseSequence]], *args, @@ -793,7 +791,7 @@ def _create_annealing_device_params( Union[DwaveAdvantageDeviceParameters, Dwave2000QDeviceParameters]: The device parameters. """ - if type(device_params) is not dict: + if not isinstance(device_params, dict): device_params = device_params.dict() # check for device level or provider level parameters @@ -834,7 +832,7 @@ def _create_common_params( @singledispatch def _format_result( - result: Union[GateModelTaskResult, AnnealingTaskResult, PhotonicModelTaskResult] + result: Union[GateModelTaskResult, AnnealingTaskResult, PhotonicModelTaskResult], ) -> Union[GateModelQuantumTaskResult, AnnealingQuantumTaskResult, PhotonicModelQuantumTaskResult]: raise TypeError("Invalid result specification type") diff --git a/src/braket/aws/aws_quantum_task_batch.py b/src/braket/aws/aws_quantum_task_batch.py index 6c505e6ef..a02dfa6d6 100644 --- a/src/braket/aws/aws_quantum_task_batch.py +++ b/src/braket/aws/aws_quantum_task_batch.py @@ -16,7 +16,7 @@ import time from concurrent.futures.thread import ThreadPoolExecutor from itertools import repeat -from typing import Union +from typing import Any, Union from braket.ahs.analog_hamiltonian_simulation import AnalogHamiltonianSimulation from braket.annealing import Problem @@ -62,8 +62,8 @@ def __init__( poll_interval_seconds: float = AwsQuantumTask.DEFAULT_RESULTS_POLL_INTERVAL, inputs: Union[dict[str, float], list[dict[str, float]]] | None = None, reservation_arn: str | None = None, - *aws_quantum_task_args, - **aws_quantum_task_kwargs, + *aws_quantum_task_args: Any, + **aws_quantum_task_kwargs: Any, ): """Creates a batch of quantum tasks. @@ -97,7 +97,9 @@ def __init__( Note: If you are creating tasks in a job that itself was created reservation ARN, those tasks do not need to be created with the reservation ARN. Default: None. - """ + *aws_quantum_task_args (Any): Arbitrary args for `QuantumTask`. + **aws_quantum_task_kwargs (Any): Arbitrary kwargs for `QuantumTask`., + """ # noqa E501 self._tasks = AwsQuantumTaskBatch._execute( aws_session, device_arn, @@ -166,10 +168,7 @@ def _tasks_and_inputs( if not single_task and not single_input: if len(task_specifications) != len(inputs): - raise ValueError( - "Multiple inputs and task specifications must " "be equal in number." - ) - + raise ValueError("Multiple inputs and task specifications must be equal in number.") if single_task: task_specifications = repeat(task_specifications, times=max_inputs_tasks) @@ -386,7 +385,8 @@ def retry_unsuccessful_tasks(self) -> bool: @property def tasks(self) -> list[AwsQuantumTask]: """list[AwsQuantumTask]: The quantum tasks in this batch, as a list of AwsQuantumTask - objects""" + objects + """ return list(self._tasks) @property @@ -397,6 +397,7 @@ def size(self) -> int: @property def unfinished(self) -> set[str]: """Gets all the IDs of all the quantum tasks in teh batch that have yet to complete. + Returns: set[str]: The IDs of all the quantum tasks in the batch that have yet to complete. """ @@ -414,5 +415,6 @@ def unfinished(self) -> set[str]: @property def unsuccessful(self) -> set[str]: """set[str]: The IDs of all the FAILED, CANCELLED, or timed out quantum tasks in the - batch.""" + batch. + """ return set(self._unsuccessful) diff --git a/src/braket/aws/aws_session.py b/src/braket/aws/aws_session.py index 0534871a2..6c63a7e45 100644 --- a/src/braket/aws/aws_session.py +++ b/src/braket/aws/aws_session.py @@ -33,10 +33,14 @@ from braket.tracking.tracking_events import _TaskCreationEvent, _TaskStatusEvent -class AwsSession(object): +class AwsSession: """Manage interactions with AWS services.""" - S3DestinationFolder = NamedTuple("S3DestinationFolder", [("bucket", str), ("key", str)]) + class S3DestinationFolder(NamedTuple): + """A `NamedTuple` for an S3 bucket and object key.""" + + bucket: str + key: str def __init__( self, @@ -45,12 +49,16 @@ def __init__( config: Config | None = None, default_bucket: str | None = None, ): - """ + """Initializes an `AwsSession`. + Args: - boto_session (Session | None): A boto3 session object. + boto_session (boto3.Session | None): A boto3 session object. braket_client (client | None): A boto3 Braket client. config (Config | None): A botocore Config object. default_bucket (str | None): The name of the default bucket of the AWS Session. + + Raises: + ValueError: invalid boto_session or braket_client. """ if ( boto_session @@ -158,8 +166,7 @@ def ecr_client(self) -> client: return self._ecr def _update_user_agent(self) -> None: - """ - Updates the `User-Agent` header forwarded by boto3 to include the braket-sdk, + """Updates the `User-Agent` header forwarded by boto3 to include the braket-sdk, braket-schemas and the notebook instance version. The header is a string of space delimited values (For example: "Boto3/1.14.43 Python/3.7.9 Botocore/1.17.44"). """ @@ -176,8 +183,7 @@ def _notebook_instance_version() -> str: ) def add_braket_user_agent(self, user_agent: str) -> None: - """ - Appends the `user-agent` value to the User-Agent header, if it does not yet exist in the + """Appends the `user-agent` value to the User-Agent header, if it does not yet exist in the header. This method is typically only relevant for libraries integrating with the Amazon Braket SDK. @@ -204,8 +210,7 @@ def _add_cost_tracker_count_handler(request: awsrequest.AWSRequest, **kwargs) -> # Quantum Tasks # def cancel_quantum_task(self, arn: str) -> None: - """ - Cancel the quantum task. + """Cancel the quantum task. Args: arn (str): The ARN of the quantum task to cancel. @@ -214,11 +219,10 @@ def cancel_quantum_task(self, arn: str) -> None: broadcast_event(_TaskStatusEvent(arn=arn, status=response["cancellationStatus"])) def create_quantum_task(self, **boto3_kwargs) -> str: - """ - Create a quantum task. + """Create a quantum task. Args: - ``**boto3_kwargs``: Keyword arguments for the Amazon Braket `CreateQuantumTask` + **boto3_kwargs: Keyword arguments for the Amazon Braket `CreateQuantumTask` operation. Returns: @@ -240,11 +244,10 @@ def create_quantum_task(self, **boto3_kwargs) -> str: return response["quantumTaskArn"] def create_job(self, **boto3_kwargs) -> str: - """ - Create a quantum hybrid job. + """Create a quantum hybrid job. Args: - ``**boto3_kwargs``: Keyword arguments for the Amazon Braket `CreateJob` operation. + **boto3_kwargs: Keyword arguments for the Amazon Braket `CreateJob` operation. Returns: str: The ARN of the hybrid job. @@ -271,8 +274,7 @@ def _should_giveup(err: Exception) -> bool: giveup=_should_giveup.__func__, ) def get_quantum_task(self, arn: str) -> dict[str, Any]: - """ - Gets the quantum task. + """Gets the quantum task. Args: arn (str): The ARN of the quantum task to get. @@ -287,9 +289,8 @@ def get_quantum_task(self, arn: str) -> dict[str, Any]: return response def get_default_jobs_role(self) -> str: - """ - Returns the role ARN for the default hybrid jobs role created in the Amazon Braket Console. - It will pick the first role it finds with the `RoleName` prefix + """This returns the role ARN for the default hybrid jobs role created in the Amazon Braket + Console. It will pick the first role it finds with the `RoleName` prefix `AmazonBraketJobsExecutionRole` with a `PathPrefix` of `/service-role/`. Returns: @@ -298,7 +299,7 @@ def get_default_jobs_role(self) -> str: Raises: RuntimeError: If no roles can be found with the prefix - `/service-role/AmazonBraketJobsExecutionRole`. + `/service-role/AmazonBraketJobsExecutionRole`. """ roles_paginator = self.iam_client.get_paginator("list_roles") for page in roles_paginator.paginate(PathPrefix="/service-role/"): @@ -318,8 +319,7 @@ def get_default_jobs_role(self) -> str: giveup=_should_giveup.__func__, ) def get_job(self, arn: str) -> dict[str, Any]: - """ - Gets the hybrid job. + """Gets the hybrid job. Args: arn (str): The ARN of the hybrid job to get. @@ -330,8 +330,7 @@ def get_job(self, arn: str) -> dict[str, Any]: return self.braket_client.get_job(jobArn=arn, additionalAttributeNames=["QueueInfo"]) def cancel_job(self, arn: str) -> dict[str, Any]: - """ - Cancel the hybrid job. + """Cancel the hybrid job. Args: arn (str): The ARN of the hybrid job to cancel. @@ -342,8 +341,7 @@ def cancel_job(self, arn: str) -> dict[str, Any]: return self.braket_client.cancel_job(jobArn=arn) def retrieve_s3_object_body(self, s3_bucket: str, s3_object_key: str) -> str: - """ - Retrieve the S3 object body. + """Retrieve the S3 object body. Args: s3_bucket (str): The S3 bucket name. @@ -367,8 +365,7 @@ def upload_to_s3(self, filename: str, s3_uri: str) -> None: self.s3_client.upload_file(filename, bucket, key) def upload_local_data(self, local_prefix: str, s3_prefix: str) -> None: - """ - Upload local data matching a prefix to a corresponding location in S3 + """Upload local data matching a prefix to a corresponding location in S3 Args: local_prefix (str): a prefix designating files to be uploaded to S3. All files @@ -410,8 +407,7 @@ def upload_local_data(self, local_prefix: str, s3_prefix: str) -> None: self.upload_to_s3(str(file), s3_uri) def download_from_s3(self, s3_uri: str, filename: str) -> None: - """ - Download file from S3 + """Download file from S3 Args: s3_uri (str): The S3 uri from where the file will be downloaded. @@ -421,8 +417,7 @@ def download_from_s3(self, s3_uri: str, filename: str) -> None: self.s3_client.download_file(bucket, key, filename) def copy_s3_object(self, source_s3_uri: str, destination_s3_uri: str) -> None: - """ - Copy object from another location in s3. Does nothing if source and + """Copy object from another location in s3. Does nothing if source and destination URIs are the same. Args: @@ -445,8 +440,7 @@ def copy_s3_object(self, source_s3_uri: str, destination_s3_uri: str) -> None: ) def copy_s3_directory(self, source_s3_path: str, destination_s3_path: str) -> None: - """ - Copy all objects from a specified directory in S3. Does nothing if source and + """Copy all objects from a specified directory in S3. Does nothing if source and destination URIs are the same. Preserves nesting structure, will not overwrite other files in the destination location unless they share a name with a file being copied. @@ -475,8 +469,7 @@ def copy_s3_directory(self, source_s3_path: str, destination_s3_path: str) -> No ) def list_keys(self, bucket: str, prefix: str) -> list[str]: - """ - Lists keys matching prefix in bucket. + """Lists keys matching prefix in bucket. Args: bucket (str): Bucket to be queried. @@ -501,8 +494,7 @@ def list_keys(self, bucket: str, prefix: str) -> list[str]: return keys def default_bucket(self) -> str: - """ - Returns the name of the default bucket of the AWS Session. In the following order + """Returns the name of the default bucket of the AWS Session. In the following order of priority, it will return either the parameter `default_bucket` set during initialization of the AwsSession (if not None), the bucket being used by the currently running Braket Hybrid Job (if evoked inside of a Braket Hybrid Job), or a default @@ -598,8 +590,7 @@ def _create_s3_bucket_if_it_does_not_exist(self, bucket_name: str, region: str) raise def get_device(self, arn: str) -> dict[str, Any]: - """ - Calls the Amazon Braket `get_device` API to retrieve device metadata. + """Calls the Amazon Braket `get_device` API to retrieve device metadata. Args: arn (str): The ARN of the device. @@ -617,8 +608,7 @@ def search_devices( statuses: Optional[list[str]] = None, provider_names: Optional[list[str]] = None, ) -> list[dict[str, Any]]: - """ - Get devices based on filters. The result is the AND of + """Get devices based on filters. The result is the AND of all the filters `arns`, `names`, `types`, `statuses`, `provider_names`. Args: @@ -657,6 +647,7 @@ def search_devices( @staticmethod def is_s3_uri(string: str) -> bool: """Determines if a given string is an S3 URI. + Args: string (str): the string to check. @@ -671,8 +662,7 @@ def is_s3_uri(string: str) -> bool: @staticmethod def parse_s3_uri(s3_uri: str) -> tuple[str, str]: - """ - Parse S3 URI to get bucket and key + """Parse S3 URI to get bucket and key Args: s3_uri (str): S3 URI. @@ -690,9 +680,9 @@ def parse_s3_uri(s3_uri: str) -> tuple[str, str]: s3_uri_match = re.match(r"^https://([^./]+)\.[sS]3\.[^/]+/(.+)$", s3_uri) or re.match( r"^[sS]3://([^./]+)/(.+)$", s3_uri ) - assert s3_uri_match + if s3_uri_match is None: + raise AssertionError bucket, key = s3_uri_match.groups() - assert bucket and key return bucket, key except (AssertionError, ValueError): raise ValueError(f"Not a valid S3 uri: {s3_uri}") @@ -703,7 +693,7 @@ def construct_s3_uri(bucket: str, *dirs: str) -> str: Args: bucket (str): S3 URI. - ``*dirs`` (str): directories to be appended in the resulting S3 URI + *dirs (str): directories to be appended in the resulting S3 URI Returns: str: S3 URI @@ -723,8 +713,7 @@ def describe_log_streams( limit: Optional[int] = None, next_token: Optional[str] = None, ) -> dict[str, Any]: - """ - Describes CloudWatch log streams in a log group with a given prefix. + """Describes CloudWatch log streams in a log group with a given prefix. Args: log_group (str): Name of the log group. @@ -759,8 +748,7 @@ def get_log_events( start_from_head: bool = True, next_token: Optional[str] = None, ) -> dict[str, Any]: - """ - Gets CloudWatch log events from a given log stream. + """Gets CloudWatch log events from a given log stream. Args: log_group (str): Name of the log group. @@ -791,8 +779,7 @@ def copy_session( region: Optional[str] = None, max_connections: Optional[int] = None, ) -> AwsSession: - """ - Creates a new AwsSession based on the region. + """Creates a new AwsSession based on the region. Args: region (Optional[str]): Name of the region. Default = `None`. @@ -833,8 +820,7 @@ def copy_session( @cache def get_full_image_tag(self, image_uri: str) -> str: - """ - Get verbose image tag from image uri. + """Get verbose image tag from image uri. Args: image_uri (str): Image uri to get tag for. diff --git a/src/braket/aws/queue_information.py b/src/braket/aws/queue_information.py index 109632751..77e5f3554 100644 --- a/src/braket/aws/queue_information.py +++ b/src/braket/aws/queue_information.py @@ -17,8 +17,7 @@ class QueueType(str, Enum): - """ - Enumerates the possible priorities for the queue. + """Enumerates the possible priorities for the queue. Values: NORMAL: Represents normal queue for the device. @@ -31,8 +30,7 @@ class QueueType(str, Enum): @dataclass() class QueueDepthInfo: - """ - Represents quantum tasks and hybrid jobs queue depth information. + """Represents quantum tasks and hybrid jobs queue depth information. Attributes: quantum_tasks (dict[QueueType, str]): number of quantum tasks waiting @@ -49,8 +47,7 @@ class QueueDepthInfo: @dataclass class QuantumTaskQueueInfo: - """ - Represents quantum tasks queue information. + """Represents quantum tasks queue information. Attributes: queue_type (QueueType): type of the quantum_task queue either 'Normal' @@ -68,8 +65,7 @@ class QuantumTaskQueueInfo: @dataclass class HybridJobQueueInfo: - """ - Represents hybrid job queue information. + """Represents hybrid job queue information. Attributes: queue_position (Optional[str]): current position of your hybrid job within a respective diff --git a/src/braket/circuits/angled_gate.py b/src/braket/circuits/angled_gate.py index e453177a7..5b4c4faba 100644 --- a/src/braket/circuits/angled_gate.py +++ b/src/braket/circuits/angled_gate.py @@ -27,9 +27,7 @@ class AngledGate(Gate, Parameterizable): - """ - Class `AngledGate` represents a quantum gate that operates on N qubits and an angle. - """ + """Class `AngledGate` represents a quantum gate that operates on N qubits and an angle.""" def __init__( self, @@ -37,7 +35,8 @@ def __init__( qubit_count: Optional[int], ascii_symbols: Sequence[str], ): - """ + """Initializes an `AngledGate`. + Args: angle (Union[FreeParameterExpression, float]): The angle of the gate in radians or expression representation. @@ -63,8 +62,7 @@ def __init__( @property def parameters(self) -> list[Union[FreeParameterExpression, float]]: - """ - Returns the parameters associated with the object, either unbound free parameters or + """Returns the parameters associated with the object, either unbound free parameters or bound values. Returns: @@ -75,8 +73,7 @@ def parameters(self) -> list[Union[FreeParameterExpression, float]]: @property def angle(self) -> Union[FreeParameterExpression, float]: - """ - Returns the angle for the gate + """Returns the angle of the gate Returns: Union[FreeParameterExpression, float]: The angle of the gate in radians @@ -110,7 +107,7 @@ def adjoint(self) -> list[Gate]: new._ascii_symbols = new_ascii_symbols return [new] - def __eq__(self, other): + def __eq__(self, other: AngledGate): return ( isinstance(other, AngledGate) and self.name == other.name @@ -125,8 +122,8 @@ def __hash__(self): class DoubleAngledGate(Gate, Parameterizable): - """ - Class `DoubleAngledGate` represents a quantum gate that operates on N qubits and two angles. + """Class `DoubleAngledGate` represents a quantum gate that operates on N qubits and + two angles. """ def __init__( @@ -136,7 +133,8 @@ def __init__( qubit_count: Optional[int], ascii_symbols: Sequence[str], ): - """ + """Inits a `DoubleAngledGate`. + Args: angle_1 (Union[FreeParameterExpression, float]): The first angle of the gate in radians or expression representation. @@ -168,8 +166,7 @@ def __init__( @property def parameters(self) -> list[Union[FreeParameterExpression, float]]: - """ - Returns the parameters associated with the object, either unbound free parameters or + """Returns the parameters associated with the object, either unbound free parameters or bound values. Returns: @@ -180,8 +177,7 @@ def parameters(self) -> list[Union[FreeParameterExpression, float]]: @property def angle_1(self) -> Union[FreeParameterExpression, float]: - """ - Returns the first angle for the gate + """Returns the first angle of the gate Returns: Union[FreeParameterExpression, float]: The first angle of the gate in radians @@ -190,20 +186,18 @@ def angle_1(self) -> Union[FreeParameterExpression, float]: @property def angle_2(self) -> Union[FreeParameterExpression, float]: - """ - Returns the second angle for the gate + """Returns the second angle of the gate Returns: Union[FreeParameterExpression, float]: The second angle of the gate in radians """ return self._parameters[1] - def bind_values(self, **kwargs) -> AngledGate: - """ - Takes in parameters and attempts to assign them to values. + def bind_values(self, **kwargs: FreeParameterExpression | str) -> AngledGate: + """Takes in parameters and attempts to assign them to values. Args: - ``**kwargs``: The parameters that are being assigned. + **kwargs (FreeParameterExpression | str): The parameters that are being assigned. Returns: AngledGate: A new Gate of the same type with the requested parameters bound. @@ -221,7 +215,7 @@ def adjoint(self) -> list[Gate]: """ raise NotImplementedError - def __eq__(self, other): + def __eq__(self, other: DoubleAngledGate): return ( isinstance(other, DoubleAngledGate) and self.name == other.name @@ -240,8 +234,8 @@ def __hash__(self): class TripleAngledGate(Gate, Parameterizable): - """ - Class `TripleAngledGate` represents a quantum gate that operates on N qubits and three angles. + """Class `TripleAngledGate` represents a quantum gate that operates on N qubits and + three angles. """ def __init__( @@ -252,7 +246,8 @@ def __init__( qubit_count: Optional[int], ascii_symbols: Sequence[str], ): - """ + """Inits a `TripleAngledGate`. + Args: angle_1 (Union[FreeParameterExpression, float]): The first angle of the gate in radians or expression representation. @@ -287,8 +282,7 @@ def __init__( @property def parameters(self) -> list[Union[FreeParameterExpression, float]]: - """ - Returns the parameters associated with the object, either unbound free parameters or + """Returns the parameters associated with the object, either unbound free parameters or bound values. Returns: @@ -299,8 +293,7 @@ def parameters(self) -> list[Union[FreeParameterExpression, float]]: @property def angle_1(self) -> Union[FreeParameterExpression, float]: - """ - Returns the first angle for the gate + """Returns the first angle of the gate Returns: Union[FreeParameterExpression, float]: The first angle of the gate in radians @@ -309,8 +302,7 @@ def angle_1(self) -> Union[FreeParameterExpression, float]: @property def angle_2(self) -> Union[FreeParameterExpression, float]: - """ - Returns the second angle for the gate + """Returns the second angle of the gate Returns: Union[FreeParameterExpression, float]: The second angle of the gate in radians @@ -319,20 +311,18 @@ def angle_2(self) -> Union[FreeParameterExpression, float]: @property def angle_3(self) -> Union[FreeParameterExpression, float]: - """ - Returns the second angle for the gate + """Returns the third angle of the gate Returns: Union[FreeParameterExpression, float]: The third angle of the gate in radians """ return self._parameters[2] - def bind_values(self, **kwargs) -> AngledGate: - """ - Takes in parameters and attempts to assign them to values. + def bind_values(self, **kwargs: FreeParameterExpression | str) -> AngledGate: + """Takes in parameters and attempts to assign them to values. Args: - ``**kwargs``: The parameters that are being assigned. + **kwargs (FreeParameterExpression | str): The parameters that are being assigned. Returns: AngledGate: A new Gate of the same type with the requested parameters bound. @@ -350,7 +340,7 @@ def adjoint(self) -> list[Gate]: """ raise NotImplementedError - def __eq__(self, other): + def __eq__(self, other: TripleAngledGate): return ( isinstance(other, TripleAngledGate) and self.name == other.name @@ -382,8 +372,7 @@ def _(angle_1: FreeParameterExpression, angle_2: FreeParameterExpression): def angled_ascii_characters(gate: str, angle: Union[FreeParameterExpression, float]) -> str: - """ - Generates a formatted ascii representation of an angled gate. + """Generates a formatted ascii representation of an angled gate. Args: gate (str): The name of the gate. @@ -400,24 +389,22 @@ def _multi_angled_ascii_characters( gate: str, *angles: Union[FreeParameterExpression, float], ) -> str: - """ - Generates a formatted ascii representation of an angled gate. + """Generates a formatted ascii representation of an angled gate. Args: gate (str): The name of the gate. - `*angles` (Union[FreeParameterExpression, float]): angles in radians. + *angles (Union[FreeParameterExpression, float]): angles in radians. Returns: str: Returns the ascii representation for an angled gate. """ - def format_string(angle: Union[FreeParameterExpression, float]) -> str: - """ - Formats an angle for ASCII representation. + def format_string(angle: FreeParameterExpression | float) -> str: + """Formats an angle for ASCII representation. Args: - angle (Union[FreeParameterExpression, float]): The angle to format. + angle (FreeParameterExpression | float): The angle to format. Returns: str: The ASCII representation of the angle. @@ -427,13 +414,13 @@ def format_string(angle: Union[FreeParameterExpression, float]) -> str: return f"{gate}({', '.join(f'{angle:{format_string(angle)}}' for angle in angles)})" -def get_angle(gate: AngledGate, **kwargs) -> AngledGate: - """ - Gets the angle with all values substituted in that are requested. +def get_angle(gate: AngledGate, **kwargs: FreeParameterExpression | str) -> AngledGate: + """Gets the angle with all values substituted in that are requested. Args: gate (AngledGate): The subclass of AngledGate for which the angle is being obtained. - ``**kwargs``: The named parameters that are being filled for a particular gate. + **kwargs (FreeParameterExpression | str): The named parameters that are being filled + for a particular gate. Returns: AngledGate: A new gate of the type of the AngledGate originally used with all @@ -445,14 +432,16 @@ def get_angle(gate: AngledGate, **kwargs) -> AngledGate: return type(gate)(angle=new_angle) -def _get_angles(gate: TripleAngledGate, **kwargs) -> TripleAngledGate: - """ - Gets the angle with all values substituted in that are requested. +def _get_angles( + gate: TripleAngledGate, **kwargs: FreeParameterExpression | str +) -> TripleAngledGate: + """Gets the angle with all values substituted in that are requested. Args: gate (TripleAngledGate): The subclass of TripleAngledGate for which the angle is being obtained. - ``**kwargs``: The named parameters that are being filled for a particular gate. + **kwargs (FreeParameterExpression | str): The named parameters that are being filled + for a particular gate. Returns: TripleAngledGate: A new gate of the type of the AngledGate originally used with all angles diff --git a/src/braket/circuits/ascii_circuit_diagram.py b/src/braket/circuits/ascii_circuit_diagram.py index 2c7024574..c255377b5 100644 --- a/src/braket/circuits/ascii_circuit_diagram.py +++ b/src/braket/circuits/ascii_circuit_diagram.py @@ -33,16 +33,14 @@ class AsciiCircuitDiagram(CircuitDiagram): @staticmethod def build_diagram(circuit: cir.Circuit) -> str: - """ - Build an ASCII string circuit diagram. + """Build an ASCII string circuit diagram. Args: - circuit (Circuit): Circuit for which to build a diagram. + circuit (cir.Circuit): Circuit for which to build a diagram. Returns: str: ASCII string circuit diagram. """ - if not circuit.instructions: return "" @@ -128,8 +126,7 @@ def _prepare_diagram_vars( def _compute_moment_global_phase( global_phase: float | None, items: list[Instruction] ) -> float | None: - """ - Compute the integrated phase at a certain moment. + """Compute the integrated phase at a certain moment. Args: global_phase (float | None): The integrated phase up to the computed moment @@ -153,8 +150,7 @@ def _ascii_group_items( circuit_qubits: QubitSet, items: list[Union[Instruction, ResultType]], ) -> list[tuple[QubitSet, list[Instruction]]]: - """ - Group instructions in a moment for ASCII diagram + """Group instructions in a moment for ASCII diagram Args: circuit_qubits (QubitSet): set of qubits in circuit @@ -212,8 +208,7 @@ def _ascii_group_items( def _categorize_result_types( result_types: list[ResultType], ) -> tuple[list[str], list[ResultType]]: - """ - Categorize result types into result types with target and those without. + """Categorize result types into result types with target and those without. Args: result_types (list[ResultType]): list of result types @@ -239,8 +234,7 @@ def _ascii_diagram_column_set( items: list[Union[Instruction, ResultType]], global_phase: float | None, ) -> str: - """ - Return a set of columns in the ASCII string diagram of the circuit for a list of items. + """Return a set of columns in the ASCII string diagram of the circuit for a list of items. Args: col_title (str): title of column set @@ -251,7 +245,6 @@ def _ascii_diagram_column_set( Returns: str: An ASCII string diagram for the column set. """ - # Group items to separate out overlapping multi-qubit items groupings = AsciiCircuitDiagram._ascii_group_items(circuit_qubits, items) @@ -287,8 +280,7 @@ def _ascii_diagram_column( items: list[Union[Instruction, ResultType]], global_phase: float | None = None, ) -> str: - """ - Return a column in the ASCII string diagram of the circuit for a given list of items. + """Return a column in the ASCII string diagram of the circuit for a given list of items. Args: circuit_qubits (QubitSet): qubits in circuit @@ -317,7 +309,7 @@ def _ascii_diagram_column( marker = "*" * len(ascii_symbol) num_after = len(circuit_qubits) - 1 after = ["|"] * (num_after - 1) + ([marker] if num_after else []) - ascii_symbols = [ascii_symbol] + after + ascii_symbols = [ascii_symbol, *after] elif ( isinstance(item, Instruction) and isinstance(item.operator, Gate) @@ -412,9 +404,7 @@ def _create_output( def _build_map_control_qubits(item: Instruction, control_qubits: QubitSet) -> dict(Qubit, int): control_state = getattr(item, "control_state", None) if control_state is not None: - map_control_qubit_states = { - qubit: state for qubit, state in zip(control_qubits, control_state) - } + map_control_qubit_states = dict(zip(control_qubits, control_state)) else: map_control_qubit_states = {qubit: 1 for qubit in control_qubits} diff --git a/src/braket/circuits/basis_state.py b/src/braket/circuits/basis_state.py index b6ce11bc8..86578fc89 100644 --- a/src/braket/circuits/basis_state.py +++ b/src/braket/circuits/basis_state.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from functools import singledispatch from typing import Optional, Union @@ -5,7 +7,7 @@ class BasisState: - def __init__(self, state: "BasisStateInput", size: Optional[int] = None): + def __init__(self, state: BasisStateInput, size: Optional[int] = None): self.state = _as_tuple(state, size) @property @@ -30,7 +32,7 @@ def __len__(self) -> int: def __iter__(self): return iter(self.state) - def __eq__(self, other): + def __eq__(self, other: BasisState): return self.state == other.state def __bool__(self): @@ -42,7 +44,7 @@ def __str__(self): def __repr__(self): return f'BasisState("{self.as_string}")' - def __getitem__(self, item): + def __getitem__(self, item: int): return BasisState(self.state[item]) diff --git a/src/braket/circuits/braket_program_context.py b/src/braket/circuits/braket_program_context.py index 863513565..46d6e3b0b 100644 --- a/src/braket/circuits/braket_program_context.py +++ b/src/braket/circuits/braket_program_context.py @@ -31,7 +31,8 @@ class BraketProgramContext(AbstractProgramContext): def __init__(self, circuit: Optional[Circuit] = None): - """ + """Inits a `BraketProgramContext`. + Args: circuit (Optional[Circuit]): A partially-built circuit to continue building with this context. Default: None. @@ -133,8 +134,7 @@ def add_kraus_instruction(self, matrices: list[np.ndarray], target: list[int]) - self._circuit.add_instruction(instruction) def add_result(self, result: Results) -> None: - """ - Abstract method to add result type to the circuit + """Abstract method to add result type to the circuit Args: result (Results): The result object representing the measurement results diff --git a/src/braket/circuits/circuit.py b/src/braket/circuits/circuit.py index adebae07d..b3063c444 100644 --- a/src/braket/circuits/circuit.py +++ b/src/braket/circuits/circuit.py @@ -70,8 +70,7 @@ class Circuit: - """ - A representation of a quantum circuit that contains the instructions to be performed on a + """A representation of a quantum circuit that contains the instructions to be performed on a quantum device and the requested result types. See :mod:`braket.circuits.gates` module for all of the supported instructions. @@ -86,8 +85,7 @@ class Circuit: @classmethod def register_subroutine(cls, func: SubroutineCallable) -> None: - """ - Register the subroutine `func` as an attribute of the `Circuit` class. The attribute name + """Register the subroutine `func` as an attribute of the `Circuit` class. The attribute name is the name of `func`. Args: @@ -116,10 +114,11 @@ def method_from_subroutine(self, *args, **kwargs) -> SubroutineReturn: setattr(cls, function_name, method_from_subroutine) function_attr = getattr(cls, function_name) - setattr(function_attr, "__doc__", func.__doc__) + function_attr.__doc__ = func.__doc__ def __init__(self, addable: AddableTypes | None = None, *args, **kwargs): - """ + """Inits a `Circuit`. + Args: addable (AddableTypes | None): The item(s) to add to self. Default = None. @@ -223,6 +222,7 @@ def moments(self) -> Moments: @property def qubit_count(self) -> int: """Get the qubit count for this circuit. Note that this includes observables. + Returns: int: The qubit count for this circuit. """ @@ -236,8 +236,7 @@ def qubits(self) -> QubitSet: @property def parameters(self) -> set[FreeParameter]: - """ - Gets a set of the parameters in the Circuit. + """Gets a set of the parameters in the Circuit. Returns: set[FreeParameter]: The `FreeParameters` in the Circuit. @@ -250,8 +249,7 @@ def add_result_type( target: QubitSetInput | None = None, target_mapping: dict[QubitInput, QubitInput] | None = None, ) -> Circuit: - """ - Add a requested result type to `self`, returns `self` for chaining ability. + """Add a requested result type to `self`, returns `self` for chaining ability. Args: result_type (ResultType): `ResultType` to add into `self`. @@ -414,8 +412,7 @@ def add_instruction( target: QubitSetInput | None = None, target_mapping: dict[QubitInput, QubitInput] | None = None, ) -> Circuit: - """ - Add an instruction to `self`, returns `self` for chaining ability. + """Add an instruction to `self`, returns `self` for chaining ability. Args: instruction (Instruction): `Instruction` to add into `self`. @@ -484,8 +481,7 @@ def add_instruction( return self def _check_for_params(self, instruction: Instruction) -> bool: - """ - This checks for free parameters in an :class:{Instruction}. Checks children classes of + """This checks for free parameters in an :class:{Instruction}. Checks children classes of :class:{Parameterizable}. Args: @@ -506,8 +502,7 @@ def add_circuit( target: QubitSetInput | None = None, target_mapping: dict[QubitInput, QubitInput] | None = None, ) -> Circuit: - """ - Add a `circuit` to self, returns self for chaining ability. + """Add a `Circuit` to `self`, returning `self` for chaining ability. Args: circuit (Circuit): Circuit to add into self. @@ -582,9 +577,8 @@ def add_verbatim_box( target: QubitSetInput | None = None, target_mapping: dict[QubitInput, QubitInput] | None = None, ) -> Circuit: - """ - Add a verbatim `circuit` to self, that is, ensures that `circuit` is not modified in any way - by the compiler. + """Add a verbatim `Circuit` to `self`, ensuring that the circuit is not modified in + any way by the compiler. Args: verbatim_circuit (Circuit): Circuit to add into self. @@ -700,7 +694,8 @@ def apply_gate_noise( If `target_unitary` is not a unitary. If `noise` is multi-qubit noise and `target_gates` contain gates with the number of qubits not the same as `noise.qubit_count`. - Warning: + + Warning: If `noise` is multi-qubit noise while there is no gate with the same number of qubits in `target_qubits` or in the whole circuit when `target_qubits` is not given. @@ -860,8 +855,7 @@ def apply_initialization_noise( return apply_noise_to_moments(self, noise, target_qubits, "initialization") def make_bound_circuit(self, param_values: dict[str, Number], strict: bool = False) -> Circuit: - """ - Binds FreeParameters based upon their name and values passed in. If parameters + """Binds `FreeParameter`s based upon their name and values passed in. If parameters share the same name, all the parameters of that name will be set to the mapped value. Args: @@ -879,16 +873,15 @@ def make_bound_circuit(self, param_values: dict[str, Number], strict: bool = Fal return self._use_parameter_value(param_values) def _validate_parameters(self, parameter_values: dict[str, Number]) -> None: - """ - This runs a check to see that the parameters are in the Circuit. + """Checks that the parameters are in the `Circuit`. Args: parameter_values (dict[str, Number]): A mapping of FreeParameter names to a value to assign to them. Raises: - ValueError: If a parameter name is given which does not appear in the circuit. - + ValueError: If there are no parameters that match the key for the arg + param_values. """ parameter_strings = set() for parameter in self.parameters: @@ -898,8 +891,7 @@ def _validate_parameters(self, parameter_values: dict[str, Number]) -> None: raise ValueError(f"No parameter in the circuit named: {param}") def _use_parameter_value(self, param_values: dict[str, Number]) -> Circuit: - """ - Creates a Circuit that uses the parameter values passed in. + """Creates a `Circuit` that uses the parameter values passed in. Args: param_values (dict[str, Number]): A mapping of FreeParameter names @@ -927,8 +919,7 @@ def _use_parameter_value(self, param_values: dict[str, Number]) -> Circuit: @staticmethod def _validate_parameter_value(val: Any) -> None: - """ - Validates the value being used is a Number. + """Validates the value being used is a `Number`. Args: val (Any): The value be verified. @@ -938,7 +929,7 @@ def _validate_parameter_value(val: Any) -> None: """ if not isinstance(val, Number): raise ValueError( - f"Parameters can only be assigned numeric values. " f"Invalid inputs: {val}" + f"Parameters can only be assigned numeric values. Invalid inputs: {val}" ) def apply_readout_noise( @@ -1020,8 +1011,7 @@ def apply_readout_noise( return apply_noise_to_moments(self, noise, target_qubits, "readout") def add(self, addable: AddableTypes, *args, **kwargs) -> Circuit: - """ - Generic add method for adding item(s) to self. Any arguments that + """Generic add method for adding item(s) to self. Any arguments that `add_circuit()` and / or `add_instruction()` and / or `add_result_type` supports are supported by this method. If adding a subroutine, check with that subroutines documentation to determine what @@ -1094,8 +1084,7 @@ def adjoint(self) -> Circuit: return circ def diagram(self, circuit_diagram_class: type = AsciiCircuitDiagram) -> str: - """ - Get a diagram for the current circuit. + """Get a diagram for the current circuit. Args: circuit_diagram_class (type): A `CircuitDiagram` class that builds the @@ -1109,21 +1098,20 @@ def diagram(self, circuit_diagram_class: type = AsciiCircuitDiagram) -> str: def to_ir( self, ir_type: IRType = IRType.JAQCD, - serialization_properties: Optional[SerializationProperties] = None, - gate_definitions: Optional[dict[tuple[Gate, QubitSet], PulseSequence]] = None, + serialization_properties: SerializationProperties | None = None, + gate_definitions: dict[tuple[Gate, QubitSet], PulseSequence] | None = None, ) -> Union[OpenQasmProgram, JaqcdProgram]: - """ - Converts the circuit into the canonical intermediate representation. + """Converts the circuit into the canonical intermediate representation. If the circuit is sent over the wire, this method is called before it is sent. Args: ir_type (IRType): The IRType to use for converting the circuit object to its IR representation. - serialization_properties (Optional[SerializationProperties]): The serialization + serialization_properties (SerializationProperties | None): The serialization properties to use while serializing the object to the IR representation. The serialization properties supplied must correspond to the supplied `ir_type`. Defaults to None. - gate_definitions (Optional[dict[tuple[Gate, QubitSet], PulseSequence]]): The + gate_definitions (dict[tuple[Gate, QubitSet], PulseSequence] | None): The calibration data for the device. default: None. Returns: @@ -1132,7 +1120,7 @@ def to_ir( Raises: ValueError: If the supplied `ir_type` is not supported, or if the supplied serialization - properties don't correspond to the `ir_type`. + properties don't correspond to the `ir_type`. """ if ir_type == IRType.JAQCD: return self._to_jaqcd() @@ -1155,8 +1143,7 @@ def to_ir( def from_ir( source: Union[str, OpenQasmProgram], inputs: Optional[dict[str, io_type]] = None ) -> Circuit: - """ - Converts an OpenQASM program to a Braket Circuit object. + """Converts an OpenQASM program to a Braket Circuit object. Args: source (Union[str, OpenQasmProgram]): OpenQASM string. @@ -1260,7 +1247,7 @@ def _validate_gate_calbrations_uniqueness( frames: dict[str, Frame], waveforms: dict[str, Waveform], ) -> None: - for key, calibration in gate_definitions.items(): + for _key, calibration in gate_definitions.items(): for frame in calibration._frames.values(): _validate_uniqueness(frames, frame) frames[frame.id] = frame @@ -1420,8 +1407,7 @@ def _add_fixed_argument_calibrations( return additional_calibrations def to_unitary(self) -> np.ndarray: - """ - Returns the unitary matrix representation of the entire circuit. + """Returns the unitary matrix representation of the entire circuit. Note: The performance of this method degrades with qubit count. It might be slow for @@ -1484,8 +1470,7 @@ def _copy(self) -> Circuit: return copy def copy(self) -> Circuit: - """ - Return a shallow copy of the circuit. + """Return a shallow copy of the circuit. Returns: Circuit: A shallow copy of the circuit. @@ -1512,25 +1497,25 @@ def __repr__(self) -> str: def __str__(self): return self.diagram(AsciiCircuitDiagram) - def __eq__(self, other): + def __eq__(self, other: Circuit): if isinstance(other, Circuit): return ( self.instructions == other.instructions and self.result_types == other.result_types ) return NotImplemented - def __call__(self, arg: Any | None = None, **kwargs) -> Circuit: - """ - Implements the call function to easily make a bound Circuit. + def __call__(self, arg: Any | None = None, **kwargs: Any) -> Circuit: + """Implements the call function to easily make a bound Circuit. Args: arg (Any | None): A value to bind to all parameters. Defaults to None and can be overridden if the parameter is in kwargs. + **kwargs (Any): The parameter and valued to be bound. Returns: Circuit: A circuit with the specified parameters bound. """ - param_values = dict() + param_values = {} if arg is not None: for param in self.parameters: param_values[str(param)] = arg @@ -1540,8 +1525,7 @@ def __call__(self, arg: Any | None = None, **kwargs) -> Circuit: def subroutine(register: bool = False) -> Callable: - """ - Subroutine is a function that returns instructions, result types, or circuits. + """Subroutine is a function that returns instructions, result types, or circuits. Args: register (bool): If `True`, adds this subroutine into the `Circuit` class. diff --git a/src/braket/circuits/circuit_diagram.py b/src/braket/circuits/circuit_diagram.py index 5b156d290..cc39aa7ee 100644 --- a/src/braket/circuits/circuit_diagram.py +++ b/src/braket/circuits/circuit_diagram.py @@ -24,11 +24,10 @@ class CircuitDiagram(ABC): @staticmethod @abstractmethod def build_diagram(circuit: cir.Circuit) -> str: - """ - Build a diagram for the specified `circuit`. + """Build a diagram for the specified `circuit`. Args: - circuit (Circuit): The circuit to build a diagram for. + circuit (cir.Circuit): The circuit to build a diagram for. Returns: str: String representation for the circuit diagram. diff --git a/src/braket/circuits/circuit_helpers.py b/src/braket/circuits/circuit_helpers.py index f0e3f3144..1a50c4c83 100644 --- a/src/braket/circuits/circuit_helpers.py +++ b/src/braket/circuits/circuit_helpers.py @@ -15,8 +15,7 @@ def validate_circuit_and_shots(circuit: Circuit, shots: int) -> None: - """ - Validates if circuit and shots are correct before running on a device + """Validates if circuit and shots are correct before running on a device Args: circuit (Circuit): circuit to validate @@ -40,7 +39,7 @@ def validate_circuit_and_shots(circuit: Circuit, shots: int) -> None: if not circuit.observables_simultaneously_measurable: raise ValueError("Observables cannot be sampled simultaneously") for rt in circuit.result_types: - if isinstance(rt, ResultType.StateVector) or isinstance(rt, ResultType.Amplitude): + if isinstance(rt, (ResultType.Amplitude, ResultType.StateVector)): raise ValueError("StateVector or Amplitude cannot be specified when shots>0") elif isinstance(rt, ResultType.Probability): num_qubits = len(rt.target) or circuit.qubit_count diff --git a/src/braket/circuits/compiler_directive.py b/src/braket/circuits/compiler_directive.py index 628422c7e..ad2c701c6 100644 --- a/src/braket/circuits/compiler_directive.py +++ b/src/braket/circuits/compiler_directive.py @@ -28,7 +28,8 @@ class CompilerDirective(Operator): """ def __init__(self, ascii_symbols: Sequence[str]): - """ + """Inits a `CompilerDirective`. + Args: ascii_symbols (Sequence[str]): ASCII string symbols for the compiler directiver. These are used when printing a diagram of circuits. @@ -97,7 +98,7 @@ def counterpart(self) -> CompilerDirective: f"Compiler directive {self.name} does not have counterpart implemented" ) - def __eq__(self, other): + def __eq__(self, other: CompilerDirective): return isinstance(other, CompilerDirective) and self.name == other.name def __repr__(self): diff --git a/src/braket/circuits/compiler_directives.py b/src/braket/circuits/compiler_directives.py index 2533537f5..9376d338d 100644 --- a/src/braket/circuits/compiler_directives.py +++ b/src/braket/circuits/compiler_directives.py @@ -18,8 +18,7 @@ class StartVerbatimBox(CompilerDirective): - """ - Prevents the compiler from modifying any ensuing instructions + """Prevents the compiler from modifying any ensuing instructions until the appearance of a corresponding ``EndVerbatimBox``. """ @@ -37,8 +36,7 @@ def _to_openqasm(self) -> str: class EndVerbatimBox(CompilerDirective): - """ - Marks the end of a portion of code following a StartVerbatimBox that prevents the enclosed + """Marks the end of a portion of code following a StartVerbatimBox that prevents the enclosed instructions from being modified by the compiler. """ diff --git a/src/braket/circuits/gate.py b/src/braket/circuits/gate.py index 907c495ce..453b121fd 100644 --- a/src/braket/circuits/gate.py +++ b/src/braket/circuits/gate.py @@ -28,14 +28,14 @@ class Gate(QuantumOperator): - """ - Class `Gate` represents a quantum gate that operates on N qubits. Gates are considered the + """Class `Gate` represents a quantum gate that operates on N qubits. Gates are considered the building blocks of quantum circuits. This class is considered the gate definition containing the metadata that defines what a gate is and what it does. """ def __init__(self, qubit_count: Optional[int], ascii_symbols: Sequence[str]): - """ + """Initializes a `Gate`. + Args: qubit_count (Optional[int]): Number of qubits this gate interacts with. ascii_symbols (Sequence[str]): ASCII string symbols for the gate. These are used when @@ -76,7 +76,7 @@ def to_ir( control_state: Optional[BasisStateInput] = None, power: float = 1, ) -> Any: - """Returns IR object of quantum operator and target + r"""Returns IR object of quantum operator and target Args: target (QubitSet): target qubit(s). @@ -97,6 +97,7 @@ def to_ir( power (float): Integer or fractional power to raise the gate to. Negative powers will be split into an inverse, accompanied by the positive power. Default 1. + Returns: Any: IR object of the quantum operator and target @@ -128,8 +129,7 @@ def to_ir( raise ValueError(f"Supplied ir_type {ir_type} is not supported.") def _to_jaqcd(self, target: QubitSet) -> Any: - """ - Returns the JAQCD representation of the gate. + """Returns the JAQCD representation of the gate. Args: target (QubitSet): target qubit(s). @@ -148,8 +148,7 @@ def _to_openqasm( control_state: Optional[BasisStateInput] = None, power: float = 1, ) -> str: - """ - Returns the openqasm string representation of the gate. + """Returns the OpenQASM string representation of the gate. Args: target (QubitSet): target qubit(s). @@ -208,7 +207,7 @@ def ascii_symbols(self) -> tuple[str, ...]: """tuple[str, ...]: Returns the ascii symbols for the quantum operator.""" return self._ascii_symbols - def __eq__(self, other): + def __eq__(self, other: Gate): return isinstance(other, Gate) and self.name == other.name def __repr__(self): diff --git a/src/braket/circuits/gate_calibrations.py b/src/braket/circuits/gate_calibrations.py index 57013df4a..7617493cb 100644 --- a/src/braket/circuits/gate_calibrations.py +++ b/src/braket/circuits/gate_calibrations.py @@ -27,8 +27,7 @@ class GateCalibrations: - """ - An object containing gate calibration data. The data respresents the mapping on a particular gate + """An object containing gate calibration data. The data respresents the mapping on a particular gate on a set of qubits to its calibration to be used by a quantum device. This is represented by a dictionary with keys of `Tuple(Gate, QubitSet)` mapped to a `PulseSequence`. """ # noqa: E501 @@ -37,18 +36,18 @@ def __init__( self, pulse_sequences: dict[tuple[Gate, QubitSet], PulseSequence], ): - """ + """Inits a `GateCalibrations`. + Args: - pulse_sequences (dict[tuple[Gate, QubitSet], PulseSequence]): A mapping containing a key of - `(Gate, QubitSet)` mapped to the corresponding pulse sequence. + pulse_sequences (dict[tuple[Gate, QubitSet], PulseSequence]): A mapping containing a key + of `(Gate, QubitSet)` mapped to the corresponding pulse sequence. - """ # noqa: E501 + """ self.pulse_sequences: dict[tuple[Gate, QubitSet], PulseSequence] = pulse_sequences @property def pulse_sequences(self) -> dict[tuple[Gate, QubitSet], PulseSequence]: - """ - Gets the mapping of (Gate, Qubit) to the corresponding `PulseSequence`. + """Gets the mapping of (Gate, Qubit) to the corresponding `PulseSequence`. Returns: dict[tuple[Gate, QubitSet], PulseSequence]: The calibration data Dictionary. @@ -57,8 +56,7 @@ def pulse_sequences(self) -> dict[tuple[Gate, QubitSet], PulseSequence]: @pulse_sequences.setter def pulse_sequences(self, value: Any) -> None: - """ - Sets the mapping of (Gate, Qubit) to the corresponding `PulseSequence`. + """Sets the mapping of (Gate, Qubit) to the corresponding `PulseSequence`. Args: value(Any): The value for the pulse_sequences property to be set to. @@ -79,8 +77,7 @@ def pulse_sequences(self, value: Any) -> None: ) def copy(self) -> GateCalibrations: - """ - Returns a copy of the object. + """Returns a copy of the object. Returns: GateCalibrations: a copy of the calibrations. @@ -95,8 +92,7 @@ def filter( gates: list[Gate] | None = None, qubits: QubitSet | list[QubitSet] | None = None, ) -> GateCalibrations: - """ - Filters the data based on optional lists of gates and QubitSets. + """Filters the data based on optional lists of gates and QubitSets. Args: gates (list[Gate] | None): An optional list of gates to filter on. @@ -105,7 +101,7 @@ def filter( Returns: GateCalibrations: A filtered GateCalibrations object. - """ # noqa: E501 + """ keys = self.pulse_sequences.keys() if isinstance(qubits, QubitSet): qubits = [qubits] @@ -120,13 +116,15 @@ def filter( ) def to_ir(self, calibration_key: tuple[Gate, QubitSet] | None = None) -> str: - """ - Returns the defcal representation for the `GateCalibrations` object. + """Returns the defcal representation for the `GateCalibrations` object. Args: calibration_key (tuple[Gate, QubitSet] | None): An optional key to get a specific defcal. Default: None + Raises: + ValueError: Key does not exist in the `GateCalibrations` object. + Returns: str: the defcal string for the object. @@ -162,5 +160,5 @@ def _def_cal_gate(self, gate_key: tuple[Gate, QubitSet]) -> str: ] ) - def __eq__(self, other): + def __eq__(self, other: GateCalibrations): return isinstance(other, GateCalibrations) and other.pulse_sequences == self.pulse_sequences diff --git a/src/braket/circuits/gates.py b/src/braket/circuits/gates.py index e955c4bb0..df17c03c3 100644 --- a/src/braket/circuits/gates.py +++ b/src/braket/circuits/gates.py @@ -137,7 +137,7 @@ def h( Gate.register_gate(H) -class I(Gate): # noqa: E742, E261 +class I(Gate): # noqa: E742 r"""Identity gate. Unitary matrix: @@ -224,6 +224,9 @@ class GPhase(AngledGate): Args: angle (Union[FreeParameterExpression, float]): angle in radians. + + Raises: + ValueError: If `angle` is not present """ def __init__(self, angle: Union[FreeParameterExpression, float]): @@ -1066,8 +1069,9 @@ def _to_jaqcd(self, target: QubitSet, **kwargs) -> Any: def to_matrix(self) -> np.ndarray: r"""Returns a matrix representation of this gate. + Returns: - ndarray: The matrix representation of this gate. + np.ndarray: The matrix representation of this gate. """ cos = np.cos(self.angle / 2) sin = np.sin(self.angle / 2) @@ -1158,8 +1162,9 @@ def _to_jaqcd(self, target: QubitSet) -> Any: def to_matrix(self) -> np.ndarray: r"""Returns a matrix representation of this gate. + Returns: - ndarray: The matrix representation of this gate. + np.ndarray: The matrix representation of this gate. """ cos = np.cos(self.angle / 2) sin = np.sin(self.angle / 2) @@ -1435,8 +1440,9 @@ def _qasm_name(self) -> str: def to_matrix(self) -> np.ndarray: r"""Returns a matrix representation of this gate. + Returns: - ndarray: The matrix representation of this gate. + np.ndarray: The matrix representation of this gate. """ _theta = self.angle_1 _phi = self.angle_2 @@ -1928,8 +1934,9 @@ def _to_jaqcd(self, target: QubitSet) -> Any: def to_matrix(self) -> np.ndarray: r"""Returns a matrix representation of this gate. + Returns: - ndarray: The matrix representation of this gate. + np.ndarray: The matrix representation of this gate. """ cos = np.cos(self.angle / 2) sin = np.sin(self.angle / 2) @@ -2694,8 +2701,9 @@ def _to_jaqcd(self, target: QubitSet) -> Any: def to_matrix(self) -> np.ndarray: r"""Returns a matrix representation of this gate. + Returns: - ndarray: The matrix representation of this gate. + np.ndarray: The matrix representation of this gate. """ cos = np.cos(self.angle / 2) isin = 1.0j * np.sin(self.angle / 2) @@ -2806,8 +2814,9 @@ def _to_jaqcd(self, target: QubitSet) -> Any: def to_matrix(self) -> np.ndarray: r"""Returns a matrix representation of this gate. + Returns: - ndarray: The matrix representation of this gate. + np.ndarray: The matrix representation of this gate. """ cos = np.cos(self.angle / 2) isin = 1.0j * np.sin(self.angle / 2) @@ -3398,7 +3407,7 @@ class MS(TripleAngledGate): angle_1 (Union[FreeParameterExpression, float]): angle in radians. angle_2 (Union[FreeParameterExpression, float]): angle in radians. angle_3 (Union[FreeParameterExpression, float]): angle in radians. - Default value is angle_3=pi/2. + Default value is angle_3=pi/2. """ def __init__( @@ -3554,7 +3563,7 @@ def adjoint(self) -> list[Gate]: def _to_jaqcd(self, target: QubitSet) -> Any: return ir.Unitary.construct( - targets=[qubit for qubit in target], + targets=list(target), matrix=Unitary._transform_matrix_to_ir(self._matrix), ) @@ -3571,7 +3580,7 @@ def _to_openqasm( return f"#pragma braket unitary({formatted_matrix}) {', '.join(qubits)}" - def __eq__(self, other): + def __eq__(self, other: Unitary): if isinstance(other, Unitary): return self.matrix_equivalence(other) return False @@ -3647,8 +3656,7 @@ def parameters(self) -> list[FreeParameter]: return list(self._pulse_sequence.parameters) def bind_values(self, **kwargs) -> PulseGate: - """ - Takes in parameters and returns an object with specified parameters + """Takes in parameters and returns an object with specified parameters replaced with their values. Returns: @@ -3681,7 +3689,7 @@ def pulse_gate( control_state: Optional[BasisStateInput] = None, power: float = 1, ) -> Instruction: - """Arbitrary pulse gate which provides the ability to embed custom pulse sequences + r"""Arbitrary pulse gate which provides the ability to embed custom pulse sequences within circuits. Args: @@ -3721,8 +3729,7 @@ def pulse_gate( def format_complex(number: complex) -> str: - """ - Format a complex number into + im to be consumed by the braket unitary pragma + """Format a complex number into + im to be consumed by the braket unitary pragma Args: number (complex): A complex number. @@ -3736,8 +3743,7 @@ def format_complex(number: complex) -> str: return f"{number.real} {imag_sign} {abs(number.imag)}im" else: return f"{number.real}" + elif number.imag: + return f"{number.imag}im" else: - if number.imag: - return f"{number.imag}im" - else: - return "0" + return "0" diff --git a/src/braket/circuits/instruction.py b/src/braket/circuits/instruction.py index 0b2f90d01..bedfd0c44 100644 --- a/src/braket/circuits/instruction.py +++ b/src/braket/circuits/instruction.py @@ -29,8 +29,7 @@ class Instruction: - """ - An instruction is a quantum directive that describes the quantum task to perform on a quantum + """An instruction is a quantum directive that describes the quantum task to perform on a quantum device. """ @@ -43,8 +42,7 @@ def __init__( control_state: Optional[BasisStateInput] = None, power: float = 1, ) -> Instruction: - """ - InstructionOperator includes objects of type `Gate` and `Noise` only. + """InstructionOperator includes objects of type `Gate` and `Noise` only. Args: operator (InstructionOperator): Operator for the instruction. @@ -110,30 +108,22 @@ def operator(self) -> InstructionOperator: @property def target(self) -> QubitSet: - """ - QubitSet: Target qubits that the operator is applied to. - """ + """QubitSet: Target qubits that the operator is applied to.""" return self._target @property def control(self) -> QubitSet: - """ - QubitSet: Target qubits that the operator is controlled on. - """ + """QubitSet: Target qubits that the operator is controlled on.""" return self._control @property def control_state(self) -> BasisState: - """ - BasisState: Quantum state that the operator is controlled to. - """ + """BasisState: Quantum state that the operator is controlled to.""" return self._control_state @property def power(self) -> float: - """ - float: Power that the operator is raised to. - """ + """float: Power that the operator is raised to.""" return self._power def adjoint(self) -> list[Instruction]: @@ -168,8 +158,7 @@ def to_ir( ir_type: IRType = IRType.JAQCD, serialization_properties: SerializationProperties | None = None, ) -> Any: - """ - Converts the operator into the canonical intermediate representation. + """Converts the operator into the canonical intermediate representation. If the operator is passed in a request, this method is called before it is passed. Args: @@ -209,8 +198,7 @@ def copy( control_state: Optional[BasisStateInput] = None, power: float = 1, ) -> Instruction: - """ - Return a shallow copy of the instruction. + """Return a shallow copy of the instruction. Note: If `target_mapping` is specified, then `self.target` is mapped to the specified @@ -282,7 +270,7 @@ def __repr__(self): f"'power': {self.power})" ) - def __eq__(self, other): + def __eq__(self, other: Instruction): if isinstance(other, Instruction): return ( self._operator, @@ -299,7 +287,7 @@ def __eq__(self, other): ) return NotImplemented - def __pow__(self, power, modulo=None): + def __pow__(self, power: float, modulo: float = None): new_power = self.power * power if modulo is not None: new_power %= modulo diff --git a/src/braket/circuits/moments.py b/src/braket/circuits/moments.py index 6e87db78d..64a3556c1 100644 --- a/src/braket/circuits/moments.py +++ b/src/braket/circuits/moments.py @@ -27,8 +27,7 @@ class MomentType(str, Enum): - """ - The type of moments. + """The type of moments. GATE: a gate NOISE: a noise channel added directly to the circuit GATE_NOISE: a gate-based noise channel @@ -48,6 +47,7 @@ class MomentType(str, Enum): class MomentsKey(NamedTuple): """Key of the Moments mapping. + Args: time: moment qubits: qubit set @@ -65,8 +65,7 @@ class MomentsKey(NamedTuple): class Moments(Mapping[MomentsKey, Instruction]): - """ - An ordered mapping of `MomentsKey` or `NoiseMomentsKey` to `Instruction`. The + r"""An ordered mapping of `MomentsKey` or `NoiseMomentsKey` to `Instruction`. The core data structure that contains instructions, ordering they are inserted in, and time slices when they occur. `Moments` implements `Mapping` and functions the same as a read-only dictionary. It is mutable only through the `add()` method. @@ -77,7 +76,7 @@ class Moments(Mapping[MomentsKey, Instruction]): method. Args: - instructions (Iterable[Instruction], optional): Instructions to initialize self. + instructions (Iterable[Instruction] | None): Instructions to initialize self. Default = None. Examples: @@ -125,9 +124,8 @@ def qubit_count(self) -> int: @property def qubits(self) -> QubitSet: - """ - QubitSet: Get the qubits used across all of the instructions. The order of qubits is based - on the order in which the instructions were added. + """QubitSet: Get the qubits used across all of the instructions. The order of qubits is + based on the order in which the instructions were added. Note: Don't mutate this object, any changes may impact the behavior of this class and / or @@ -136,8 +134,7 @@ def qubits(self) -> QubitSet: return self._qubits def time_slices(self) -> dict[int, list[Instruction]]: - """ - Get instructions keyed by time. + """Get instructions keyed by time. Returns: dict[int, list[Instruction]]: Key is the time and value is a list of instructions that @@ -148,7 +145,6 @@ def time_slices(self) -> dict[int, list[Instruction]]: every call, with a computational runtime O(N) where N is the number of instructions in self. """ - time_slices = {} self.sort_moments() for key, instruction in self._moments.items(): @@ -161,8 +157,7 @@ def time_slices(self) -> dict[int, list[Instruction]]: def add( self, instructions: Union[Iterable[Instruction], Instruction], noise_index: int = 0 ) -> None: - """ - Add one or more instructions to self. + """Add one or more instructions to self. Args: instructions (Union[Iterable[Instruction], Instruction]): Instructions to add to self. @@ -218,6 +213,7 @@ def add_noise( self, instruction: Instruction, input_type: str = "noise", noise_index: int = 0 ) -> None: """Adds noise to a moment. + Args: instruction (Instruction): Instruction to add. input_type (str): One of MomentType. @@ -237,8 +233,7 @@ def add_noise( self._qubits.update(qubit_range) def sort_moments(self) -> None: - """ - Make the disordered moments in order. + """Make the disordered moments in order. 1. Make the readout noise in the end 2. Make the initialization noise at the beginning @@ -293,6 +288,7 @@ def items(self) -> ItemsView[MomentsKey, Instruction]: def values(self) -> ValuesView[Instruction]: """Return a view of self's instructions. + Returns: ValuesView[Instruction]: The (in-order) instructions. """ @@ -300,8 +296,7 @@ def values(self) -> ValuesView[Instruction]: return self._moments.values() def get(self, key: MomentsKey, default: Any | None = None) -> Instruction: - """ - Get the instruction in self by key. + """Get the instruction in self by key. Args: key (MomentsKey): Key of the instruction to fetch. @@ -312,7 +307,7 @@ def get(self, key: MomentsKey, default: Any | None = None) -> Instruction: """ return self._moments.get(key, default) - def __getitem__(self, key): + def __getitem__(self, key: MomentsKey): return self._moments.__getitem__(key) def __iter__(self): @@ -321,15 +316,15 @@ def __iter__(self): def __len__(self): return self._moments.__len__() - def __contains__(self, item): + def __contains__(self, item: MomentsKey): return self._moments.__contains__(item) - def __eq__(self, other): + def __eq__(self, other: Moments): if isinstance(other, Moments): return self._moments == other._moments return NotImplemented - def __ne__(self, other): + def __ne__(self, other: Moments): result = self.__eq__(other) if result is not NotImplemented: return not result diff --git a/src/braket/circuits/noise.py b/src/braket/circuits/noise.py index af1bb422f..fe256f1da 100644 --- a/src/braket/circuits/noise.py +++ b/src/braket/circuits/noise.py @@ -14,7 +14,7 @@ from __future__ import annotations from collections.abc import Iterable, Sequence -from typing import Any, Optional, Union +from typing import Any, ClassVar, Optional, Union import numpy as np @@ -31,8 +31,7 @@ class Noise(QuantumOperator): - """ - Class `Noise` represents a noise channel that operates on one or multiple qubits. Noise + """Class `Noise` represents a noise channel that operates on one or multiple qubits. Noise are considered as building blocks of quantum circuits that simulate noise. It can be used as an operator in an `Instruction` object. It appears in the diagram when user prints a circuit with `Noise`. This class is considered the noise channel definition containing @@ -40,7 +39,8 @@ class Noise(QuantumOperator): """ def __init__(self, qubit_count: Optional[int], ascii_symbols: Sequence[str]): - """ + """Initializes a `Noise` object. + Args: qubit_count (Optional[int]): Number of qubits this noise channel interacts with. ascii_symbols (Sequence[str]): ASCII string symbols for this noise channel. These @@ -56,8 +56,7 @@ def __init__(self, qubit_count: Optional[int], ascii_symbols: Sequence[str]): @property def name(self) -> str: - """ - Returns the name of the quantum operator + """Returns the name of the quantum operator Returns: str: The name of the quantum operator as a string @@ -79,6 +78,7 @@ def to_ir( serialization_properties (SerializationProperties | None): The serialization properties to use while serializing the object to the IR representation. The serialization properties supplied must correspond to the supplied `ir_type`. Defaults to None. + Returns: Any: IR object of the quantum operator and target @@ -103,8 +103,7 @@ def to_ir( raise ValueError(f"Supplied ir_type {ir_type} is not supported.") def _to_jaqcd(self, target: QubitSet) -> Any: - """ - Returns the JAQCD representation of the noise. + """Returns the JAQCD representation of the noise. Args: target (QubitSet): target qubit(s). @@ -117,8 +116,7 @@ def _to_jaqcd(self, target: QubitSet) -> Any: def _to_openqasm( self, target: QubitSet, serialization_properties: OpenQASMSerializationProperties ) -> str: - """ - Returns the openqasm string representation of the noise. + """Returns the openqasm string representation of the noise. Args: target (QubitSet): target qubit(s). @@ -138,7 +136,7 @@ def to_matrix(self, *args, **kwargs) -> Iterable[np.ndarray]: """ raise NotImplementedError("to_matrix has not been implemented yet.") - def __eq__(self, other): + def __eq__(self, other: Noise): if isinstance(other, Noise): return self.name == other.name return False @@ -148,8 +146,8 @@ def __repr__(self): @classmethod def from_dict(cls, noise: dict) -> Noise: - """ - Converts a dictionary representing an object of this class into an instance of this class. + """Converts a dictionary representing an object of this class into an instance of + this class. Args: noise (dict): A dictionary representation of an object of this class. @@ -166,6 +164,7 @@ def from_dict(cls, noise: dict) -> Noise: @classmethod def register_noise(cls, noise: type[Noise]) -> None: """Register a noise implementation by adding it into the Noise class. + Args: noise (type[Noise]): Noise class to register. """ @@ -173,8 +172,7 @@ def register_noise(cls, noise: type[Noise]) -> None: class SingleProbabilisticNoise(Noise, Parameterizable): - """ - Class `SingleProbabilisticNoise` represents the bit/phase flip noise channel on N qubits + """Class `SingleProbabilisticNoise` represents the bit/phase flip noise channel on N qubits parameterized by a single probability. """ @@ -185,7 +183,8 @@ def __init__( ascii_symbols: Sequence[str], max_probability: float = 0.5, ): - """ + """Initializes a `SingleProbabilisticNoise`. + Args: probability (Union[FreeParameterExpression, float]): The probability that the noise occurs. @@ -209,6 +208,7 @@ def __init__( @property def probability(self) -> float: """The probability that parametrizes the noise channel. + Returns: float: The probability that parametrizes the noise channel. """ @@ -222,9 +222,8 @@ def __str__(self): @property def parameters(self) -> list[Union[FreeParameterExpression, float]]: - """ - Returns the parameters associated with the object, either unbound free parameter expressions - or bound values. + """Returns the parameters associated with the object, either unbound free parameter + expressions or bound values. Returns: list[Union[FreeParameterExpression, float]]: The free parameter expressions @@ -232,14 +231,13 @@ def parameters(self) -> list[Union[FreeParameterExpression, float]]: """ return [self._probability] - def __eq__(self, other): - if isinstance(other, type(self)): + def __eq__(self, other: SingleProbabilisticNoise): + if isinstance(other, SingleProbabilisticNoise): return self.name == other.name and self.probability == other.probability return False def bind_values(self, **kwargs) -> SingleProbabilisticNoise: - """ - Takes in parameters and attempts to assign them to values. + """Takes in parameters and attempts to assign them to values. Returns: SingleProbabilisticNoise: A new Noise object of the same type with the requested @@ -251,8 +249,7 @@ def bind_values(self, **kwargs) -> SingleProbabilisticNoise: raise NotImplementedError def to_dict(self) -> dict: - """ - Converts this object into a dictionary representation. + """Converts this object into a dictionary representation. Returns: dict: A dictionary object that represents this object. It can be converted back @@ -267,8 +264,7 @@ def to_dict(self) -> dict: class SingleProbabilisticNoise_34(SingleProbabilisticNoise): - """ - Class `SingleProbabilisticNoise` represents the Depolarizing and TwoQubitDephasing noise + """Class `SingleProbabilisticNoise` represents the Depolarizing and TwoQubitDephasing noise channels parameterized by a single probability. """ @@ -278,7 +274,8 @@ def __init__( qubit_count: Optional[int], ascii_symbols: Sequence[str], ): - """ + """Initializes a `SingleProbabilisticNoise_34`. + Args: probability (Union[FreeParameterExpression, float]): The probability that the noise occurs. @@ -301,8 +298,7 @@ def __init__( class SingleProbabilisticNoise_1516(SingleProbabilisticNoise): - """ - Class `SingleProbabilisticNoise` represents the TwoQubitDepolarizing noise channel + """Class `SingleProbabilisticNoise` represents the TwoQubitDepolarizing noise channel parameterized by a single probability. """ @@ -312,7 +308,8 @@ def __init__( qubit_count: Optional[int], ascii_symbols: Sequence[str], ): - """ + """Initializes a `SingleProbabilisticNoise_1516`. + Args: probability (Union[FreeParameterExpression, float]): The probability that the noise occurs. @@ -335,12 +332,11 @@ def __init__( class MultiQubitPauliNoise(Noise, Parameterizable): - """ - Class `MultiQubitPauliNoise` represents a general multi-qubit Pauli channel, + """Class `MultiQubitPauliNoise` represents a general multi-qubit Pauli channel, parameterized by up to 4**N - 1 probabilities. """ - _allowed_substrings = {"I", "X", "Y", "Z"} + _allowed_substrings: ClassVar = {"I", "X", "Y", "Z"} def __init__( self, @@ -372,7 +368,6 @@ def __init__( TypeError: If the type of the dictionary keys are not strings. If the probabilities are not floats. """ - super().__init__(qubit_count=qubit_count, ascii_symbols=ascii_symbols) self._probabilities = probabilities @@ -395,10 +390,8 @@ def __init__( total_prob += prob if not (1.0 >= total_prob >= 0.0): raise ValueError( - ( - "Total probability must be a real number in the interval [0, 1]. " - f"Total probability was {total_prob}." - ) + "Total probability must be a real number in the interval [0, 1]. " + f"Total probability was {total_prob}." ) @classmethod @@ -409,17 +402,13 @@ def _validate_pauli_string( raise TypeError(f"Type of {pauli_str} was not a string.") if len(pauli_str) != qubit_count: raise ValueError( - ( - "Length of each Pauli string must be equal to number of qubits. " - f"{pauli_str} had length {len(pauli_str)} instead of length {qubit_count}." - ) + "Length of each Pauli string must be equal to number of qubits. " + f"{pauli_str} had length {len(pauli_str)} instead of length {qubit_count}." ) if not set(pauli_str) <= allowed_substrings: raise ValueError( - ( - "Strings must be Pauli strings consisting of only [I, X, Y, Z]. " - f"Received {pauli_str}." - ) + "Strings must be Pauli strings consisting of only [I, X, Y, Z]. " + f"Received {pauli_str}." ) def __repr__(self): @@ -431,14 +420,15 @@ def __repr__(self): def __str__(self): return f"{self.name}({self._probabilities})" - def __eq__(self, other): - if isinstance(other, type(self)): + def __eq__(self, other: MultiQubitPauliNoise): + if isinstance(other, MultiQubitPauliNoise): return self.name == other.name and self._probabilities == other._probabilities return False @property def probabilities(self) -> dict[str, float]: """A map of a Pauli string to its corresponding probability. + Returns: dict[str, float]: A map of a Pauli string to its corresponding probability. """ @@ -446,9 +436,8 @@ def probabilities(self) -> dict[str, float]: @property def parameters(self) -> list[Union[FreeParameterExpression, float]]: - """ - Returns the parameters associated with the object, either unbound free parameter expressions - or bound values. + """Returns the parameters associated with the object, either unbound free parameter + expressions or bound values. Parameters are in alphabetical order of the Pauli strings in `probabilities`. @@ -461,8 +450,7 @@ def parameters(self) -> list[Union[FreeParameterExpression, float]]: ] def bind_values(self, **kwargs) -> MultiQubitPauliNoise: - """ - Takes in parameters and attempts to assign them to values. + """Takes in parameters and attempts to assign them to values. Returns: MultiQubitPauliNoise: A new Noise object of the same type with the requested @@ -474,14 +462,13 @@ def bind_values(self, **kwargs) -> MultiQubitPauliNoise: raise NotImplementedError def to_dict(self) -> dict: - """ - Converts this object into a dictionary representation. + """Converts this object into a dictionary representation. Returns: dict: A dictionary object that represents this object. It can be converted back into this object using the `from_dict()` method. """ - probabilities = dict() + probabilities = {} for pauli_string, prob in self._probabilities.items(): probabilities[pauli_string] = _parameter_to_dict(prob) return { @@ -493,8 +480,7 @@ def to_dict(self) -> dict: class PauliNoise(Noise, Parameterizable): - """ - Class `PauliNoise` represents the a single-qubit Pauli noise channel + """Class `PauliNoise` represents the a single-qubit Pauli noise channel acting on one qubit. It is parameterized by three probabilities. """ @@ -506,7 +492,8 @@ def __init__( qubit_count: Optional[int], ascii_symbols: Sequence[str], ): - """ + """Initializes a `PauliNoise`. + Args: probX (Union[FreeParameterExpression, float]): The X coefficient of the Kraus operators in the channel. @@ -556,7 +543,8 @@ def _get_param_float(param: Union[FreeParameterExpression, float], param_name: s @property def probX(self) -> Union[FreeParameterExpression, float]: - """ + """The probability of a Pauli X error. + Returns: Union[FreeParameterExpression, float]: The probability of a Pauli X error. """ @@ -564,7 +552,8 @@ def probX(self) -> Union[FreeParameterExpression, float]: @property def probY(self) -> Union[FreeParameterExpression, float]: - """ + """The probability of a Pauli Y error. + Returns: Union[FreeParameterExpression, float]: The probability of a Pauli Y error. """ @@ -572,7 +561,8 @@ def probY(self) -> Union[FreeParameterExpression, float]: @property def probZ(self) -> Union[FreeParameterExpression, float]: - """ + """The probability of a Pauli Z error. + Returns: Union[FreeParameterExpression, float]: The probability of a Pauli Z error. """ @@ -591,16 +581,15 @@ def __repr__(self): def __str__(self): return f"{self.name}({self._parameters[0]}, {self._parameters[1]}, {self._parameters[2]})" - def __eq__(self, other): - if isinstance(other, type(self)): + def __eq__(self, other: PauliNoise): + if isinstance(other, PauliNoise): return self.name == other.name and self._parameters == other._parameters return False @property def parameters(self) -> list[Union[FreeParameterExpression, float]]: - """ - Returns the parameters associated with the object, either unbound free parameter expressions - or bound values. + """Returns the parameters associated with the object, either unbound free parameter + expressions or bound values. Parameters are in the order [probX, probY, probZ] @@ -611,8 +600,7 @@ def parameters(self) -> list[Union[FreeParameterExpression, float]]: return self._parameters def bind_values(self, **kwargs) -> PauliNoise: - """ - Takes in parameters and attempts to assign them to values. + """Takes in parameters and attempts to assign them to values. Returns: PauliNoise: A new Noise object of the same type with the requested @@ -624,8 +612,7 @@ def bind_values(self, **kwargs) -> PauliNoise: raise NotImplementedError def to_dict(self) -> dict: - """ - Converts this object into a dictionary representation. + """Converts this object into a dictionary representation. Returns: dict: A dictionary object that represents this object. It can be converted back @@ -642,8 +629,7 @@ def to_dict(self) -> dict: class DampingNoise(Noise, Parameterizable): - """ - Class `DampingNoise` represents a damping noise channel + """Class `DampingNoise` represents a damping noise channel on N qubits parameterized by gamma. """ @@ -653,7 +639,8 @@ def __init__( qubit_count: Optional[int], ascii_symbols: Sequence[str], ): - """ + """Initalizes a `DampingNoise`. + Args: gamma (Union[FreeParameterExpression, float]): Probability of damping. qubit_count (Optional[int]): The number of qubits to apply noise. @@ -661,7 +648,7 @@ def __init__( printing a diagram of a circuit. The length must be the same as `qubit_count`, and index ordering is expected to correlate with the target ordering on the instruction. - Raises: + Raises: ValueError: If `qubit_count` < 1, `ascii_symbols` is `None`, @@ -678,6 +665,7 @@ def __init__( @property def gamma(self) -> float: """Probability of damping. + Returns: float: Probability of damping. """ @@ -691,9 +679,8 @@ def __str__(self): @property def parameters(self) -> list[Union[FreeParameterExpression, float]]: - """ - Returns the parameters associated with the object, either unbound free parameter expressions - or bound values. + """Returns the parameters associated with the object, either unbound free parameter + expressions or bound values. Returns: list[Union[FreeParameterExpression, float]]: The free parameter expressions @@ -701,14 +688,13 @@ def parameters(self) -> list[Union[FreeParameterExpression, float]]: """ return [self._gamma] - def __eq__(self, other): - if isinstance(other, type(self)): + def __eq__(self, other: DampingNoise): + if isinstance(other, DampingNoise): return self.name == other.name and self.gamma == other.gamma return False def bind_values(self, **kwargs) -> DampingNoise: - """ - Takes in parameters and attempts to assign them to values. + """Takes in parameters and attempts to assign them to values. Returns: DampingNoise: A new Noise object of the same type with the requested @@ -720,8 +706,7 @@ def bind_values(self, **kwargs) -> DampingNoise: raise NotImplementedError def to_dict(self) -> dict: - """ - Converts this object into a dictionary representation. + """Converts this object into a dictionary representation. Returns: dict: A dictionary object that represents this object. It can be converted back @@ -736,8 +721,7 @@ def to_dict(self) -> dict: class GeneralizedAmplitudeDampingNoise(DampingNoise): - """ - Class `GeneralizedAmplitudeDampingNoise` represents the generalized amplitude damping + """Class `GeneralizedAmplitudeDampingNoise` represents the generalized amplitude damping noise channel on N qubits parameterized by gamma and probability. """ @@ -748,7 +732,8 @@ def __init__( qubit_count: Optional[int], ascii_symbols: Sequence[str], ): - """ + """Inits a `GeneralizedAmplitudeDampingNoise`. + Args: gamma (Union[FreeParameterExpression, float]): Probability of damping. probability (Union[FreeParameterExpression, float]): Probability of the system being @@ -758,7 +743,7 @@ def __init__( printing a diagram of a circuit. The length must be the same as `qubit_count`, and index ordering is expected to correlate with the target ordering on the instruction. - Raises: + Raises: ValueError: If `qubit_count` < 1, `ascii_symbols` is `None`, @@ -776,6 +761,7 @@ def __init__( @property def probability(self) -> float: """Probability of the system being excited by the environment. + Returns: float: Probability of the system being excited by the environment. """ @@ -793,9 +779,8 @@ def __str__(self): @property def parameters(self) -> list[Union[FreeParameterExpression, float]]: - """ - Returns the parameters associated with the object, either unbound free parameter expressions - or bound values. + """Returns the parameters associated with the object, either unbound free parameter + expressions or bound values. Parameters are in the order [gamma, probability] @@ -805,8 +790,8 @@ def parameters(self) -> list[Union[FreeParameterExpression, float]]: """ return [self.gamma, self.probability] - def __eq__(self, other): - if isinstance(other, type(self)): + def __eq__(self, other: GeneralizedAmplitudeDampingNoise): + if isinstance(other, GeneralizedAmplitudeDampingNoise): return ( self.name == other.name and self.gamma == other.gamma @@ -815,8 +800,7 @@ def __eq__(self, other): return False def to_dict(self) -> dict: - """ - Converts this object into a dictionary representation. + """Converts this object into a dictionary representation. Returns: dict: A dictionary object that represents this object. It can be converted back diff --git a/src/braket/circuits/noise_helpers.py b/src/braket/circuits/noise_helpers.py index 06c0b3620..6dda8130d 100644 --- a/src/braket/circuits/noise_helpers.py +++ b/src/braket/circuits/noise_helpers.py @@ -32,6 +32,7 @@ def no_noise_applied_warning(noise_applied: bool) -> None: """Helper function to give a warning is noise is not applied. + Args: noise_applied (bool): True if the noise has been applied. """ @@ -39,12 +40,14 @@ def no_noise_applied_warning(noise_applied: bool) -> None: warnings.warn( "Noise is not applied to any gate, as there is no eligible gate in the circuit" " with the input criteria or there is no multi-qubit gate to apply" - " the multi-qubit noise." + " the multi-qubit noise.", + stacklevel=1, ) def wrap_with_list(an_item: Any) -> list[Any]: """Helper function to make the input parameter a list. + Args: an_item (Any): The item to wrap. @@ -61,6 +64,7 @@ def check_noise_target_gates(noise: Noise, target_gates: Iterable[type[Gate]]) - 1. whether all the elements in target_gates are a Gate type; 2. if `noise` is multi-qubit noise and `target_gates` contain gates with the number of qubits is the same as `noise.qubit_count`. + Args: noise (Noise): A Noise class object to be applied to the circuit. target_gates (Iterable[type[Gate]]): Gate class or @@ -93,7 +97,6 @@ def check_noise_target_unitary(noise: Noise, target_unitary: np.ndarray) -> None noise (Noise): A Noise class object to be applied to the circuit. target_unitary (ndarray): matrix of the target unitary gates """ - if not isinstance(target_unitary, np.ndarray): raise TypeError("target_unitary must be a np.ndarray type") @@ -104,11 +107,12 @@ def check_noise_target_unitary(noise: Noise, target_unitary: np.ndarray) -> None def check_noise_target_qubits( circuit: Circuit, target_qubits: Optional[QubitSetInput] = None ) -> QubitSet: - """ - Helper function to check whether all the target_qubits are positive integers. + """Helper function to check whether all the target_qubits are positive integers. + Args: circuit (Circuit): A ciruit where `noise` is to be checked. target_qubits (Optional[QubitSetInput]): Index or indices of qubit(s). + Returns: QubitSet: The target qubits. """ @@ -129,8 +133,7 @@ def check_noise_target_qubits( def apply_noise_to_moments( circuit: Circuit, noise: Iterable[type[Noise]], target_qubits: QubitSet, position: str ) -> Circuit: - """ - Apply initialization/readout noise to the circuit. + """Apply initialization/readout noise to the circuit. When `noise.qubit_count` == 1, `noise` is added to all qubits in `target_qubits`. @@ -210,7 +213,6 @@ def _apply_noise_to_gates_helper( noise_index: The number of noise channels applied to the gate noise_applied: Whether noise is applied or not """ - for noise_channel in noise: if noise_channel.qubit_count == 1: for qubit in intersection: @@ -218,17 +220,16 @@ def _apply_noise_to_gates_helper( noise_index += 1 new_noise_instruction.append((Instruction(noise_channel, qubit), noise_index)) noise_applied = True - else: - # only apply noise to the gates that have the same qubit_count as the noise. - if ( - instruction.operator.qubit_count == noise_channel.qubit_count - and instruction.target.issubset(target_qubits) - ): - noise_index += 1 - new_noise_instruction.append( - (Instruction(noise_channel, instruction.target), noise_index) - ) - noise_applied = True + # only apply noise to the gates that have the same qubit_count as the noise. + elif ( + instruction.operator.qubit_count == noise_channel.qubit_count + and instruction.target.issubset(target_qubits) + ): + noise_index += 1 + new_noise_instruction.append( + (Instruction(noise_channel, instruction.target), noise_index) + ) + noise_applied = True return new_noise_instruction, noise_index, noise_applied @@ -265,7 +266,6 @@ def apply_noise_to_gates( If no `target_gates` exist in `target_qubits` or in the whole circuit when `target_qubits` is not given. """ - new_moments = Moments() noise_applied = False diff --git a/src/braket/circuits/noise_model/circuit_instruction_criteria.py b/src/braket/circuits/noise_model/circuit_instruction_criteria.py index 170d3e996..1db40aa5f 100644 --- a/src/braket/circuits/noise_model/circuit_instruction_criteria.py +++ b/src/braket/circuits/noise_model/circuit_instruction_criteria.py @@ -29,6 +29,9 @@ def instruction_matches(self, instruction: Instruction) -> bool: Args: instruction (Instruction): An Instruction to match. + Raises: + NotImplementedError: Not implemented. + Returns: bool: True if an Instruction matches the criteria. """ @@ -38,8 +41,7 @@ def instruction_matches(self, instruction: Instruction) -> bool: def _check_target_in_qubits( qubits: Optional[set[Union[int, tuple[int]]]], target: QubitSetInput ) -> bool: - """ - Returns true if the given targets of an instruction match the given qubit input set. + """Returns true if the given targets of an instruction match the given qubit input set. Args: qubits (Optional[set[Union[int, tuple[int]]]]): The qubits provided to the criteria. diff --git a/src/braket/circuits/noise_model/criteria.py b/src/braket/circuits/noise_model/criteria.py index b9f0d2cc4..63625491f 100644 --- a/src/braket/circuits/noise_model/criteria.py +++ b/src/braket/circuits/noise_model/criteria.py @@ -20,8 +20,8 @@ class CriteriaKey(str, Enum): - """ - Specifies the types of keys that a criteria may use to match an instruction, observable, etc. + """Specifies the types of keys that a criteria may use to match an instruction, + observable, etc. """ QUBIT = "QUBIT" @@ -31,8 +31,7 @@ class CriteriaKey(str, Enum): class CriteriaKeyResult(str, Enum): - """ - The get_keys() method may return this enum instead of actual keys for + """The get_keys() method may return this enum instead of actual keys for a given criteria key type. """ @@ -90,8 +89,8 @@ def to_dict(self) -> dict: @classmethod def from_dict(cls, criteria: dict) -> Criteria: - """ - Converts a dictionary representing an object of this class into an instance of this class. + """Converts a dictionary representing an object of this class into an instance of this + class. Args: criteria (dict): A dictionary representation of an object of this class. diff --git a/src/braket/circuits/noise_model/criteria_input_parsing.py b/src/braket/circuits/noise_model/criteria_input_parsing.py index 11f24619e..bc86e53bf 100644 --- a/src/braket/circuits/noise_model/criteria_input_parsing.py +++ b/src/braket/circuits/noise_model/criteria_input_parsing.py @@ -19,10 +19,9 @@ def parse_operator_input( - operators: Union[QuantumOperator, Iterable[QuantumOperator]] + operators: Union[QuantumOperator, Iterable[QuantumOperator]], ) -> Optional[set[QuantumOperator]]: - """ - Processes the quantum operator input to __init__ to validate and return a set of + """Processes the quantum operator input to __init__ to validate and return a set of QuantumOperators. Args: @@ -49,8 +48,7 @@ def parse_operator_input( def parse_qubit_input( qubits: Optional[QubitSetInput], expected_qubit_count: Optional[int] = 0 ) -> Optional[set[Union[int, tuple[int]]]]: - """ - Processes the qubit input to __init__ to validate and return a set of qubit targets. + """Processes the qubit input to __init__ to validate and return a set of qubit targets. Args: qubits (Optional[QubitSetInput]): Qubit input. diff --git a/src/braket/circuits/noise_model/gate_criteria.py b/src/braket/circuits/noise_model/gate_criteria.py index 623c02477..7870e9b6b 100644 --- a/src/braket/circuits/noise_model/gate_criteria.py +++ b/src/braket/circuits/noise_model/gate_criteria.py @@ -33,8 +33,7 @@ def __init__( gates: Optional[Union[Gate, Iterable[Gate]]] = None, qubits: Optional[QubitSetInput] = None, ): - """ - Creates Gate-based Criteria. See instruction_matches() for more details. + """Creates Gate-based Criteria. See instruction_matches() for more details. Args: gates (Optional[Union[Gate, Iterable[Gate]]]): A set of relevant Gates. All the Gates @@ -60,7 +59,8 @@ def __repr__(self): return f"{self.__class__.__name__}(gates={gate_names}, qubits={self._qubits})" def applicable_key_types(self) -> Iterable[CriteriaKey]: - """ + """Returns an Iterable of criteria keys. + Returns: Iterable[CriteriaKey]: This Criteria operates on Gates and Qubits. """ @@ -86,8 +86,8 @@ def get_keys(self, key_type: CriteriaKey) -> Union[CriteriaKeyResult, set[Any]]: return set() def to_dict(self) -> dict: - """ - Converts a dictionary representing an object of this class into an instance of this class. + """Converts a dictionary representing an object of this class into an instance of this + class. Returns: dict: A dictionary representing the serialized version of this Criteria. diff --git a/src/braket/circuits/noise_model/initialization_criteria.py b/src/braket/circuits/noise_model/initialization_criteria.py index e40d4e9de..4bf29a356 100644 --- a/src/braket/circuits/noise_model/initialization_criteria.py +++ b/src/braket/circuits/noise_model/initialization_criteria.py @@ -18,14 +18,11 @@ class InitializationCriteria(Criteria): - """ - Criteria that implement these methods may be used to determine initialization noise. - """ + """Criteria that implement these methods may be used to determine initialization noise.""" @abstractmethod def qubit_intersection(self, qubits: QubitSetInput) -> QubitSetInput: - """ - Returns subset of passed qubits that match the criteria. + """Returns subset of passed qubits that match the criteria. Args: qubits (QubitSetInput): A qubit or set of qubits that may match the criteria. diff --git a/src/braket/circuits/noise_model/noise_model.py b/src/braket/circuits/noise_model/noise_model.py index 8922cda72..4ea566131 100644 --- a/src/braket/circuits/noise_model/noise_model.py +++ b/src/braket/circuits/noise_model/noise_model.py @@ -56,8 +56,8 @@ def to_dict(self) -> dict: @classmethod def from_dict(cls, noise_model_item: dict) -> NoiseModelInstruction: - """ - Converts a dictionary representing an object of this class into an instance of this class. + """Converts a dictionary representing an object of this class into an instance of + this class. Args: noise_model_item (dict): A dictionary representation of an object of this class. @@ -82,8 +82,7 @@ class NoiseModelInstructions: class NoiseModel: - """ - A Noise Model can be thought of as a set of Noise objects, and a corresponding set of + """A Noise Model can be thought of as a set of Noise objects, and a corresponding set of criteria for how each Noise object should be applied to a circuit. For example, a noise model may represent that every H gate that acts on qubit 0 has a 10% probability of a bit flip, and every X gate that acts on qubit 0 has a 20% probability of a bit flip, and 5% probability of @@ -110,8 +109,7 @@ def __str__(self): @property def instructions(self) -> list[NoiseModelInstruction]: - """ - List all the noise in the NoiseModel. + """List all the noise in the NoiseModel. Returns: list[NoiseModelInstruction]: The noise model instructions. @@ -157,8 +155,7 @@ def _add_instruction(self, instruction: NoiseModelInstruction) -> NoiseModel: return self def remove_noise(self, index: int) -> NoiseModel: - """ - Removes the noise and corresponding criteria from the NoiseModel at the given index. + """Removes the noise and corresponding criteria from the NoiseModel at the given index. Args: index (int): The index of the instruction to remove. @@ -175,6 +172,7 @@ def remove_noise(self, index: int) -> NoiseModel: def get_instructions_by_type(self) -> NoiseModelInstructions: """Returns the noise in this model by noise type. + Returns: NoiseModelInstructions: The noise model instructions. """ @@ -200,8 +198,7 @@ def from_filter( gate: Optional[Gate] = None, noise: Optional[type[Noise]] = None, ) -> NoiseModel: - """ - Returns a new NoiseModel from this NoiseModel using a given filter. If no filters are + """Returns a new NoiseModel from this NoiseModel using a given filter. If no filters are specified, the returned NoiseModel will be the same as this one. Args: @@ -235,8 +232,7 @@ class as the given noise class. return new_model def apply(self, circuit: Circuit) -> Circuit: - """ - Applies this noise model to a circuit, and returns a new circuit that's the `noisy` + """Applies this noise model to a circuit, and returns a new circuit that's the `noisy` version of the given circuit. If multiple noise will act on the same instruction, they will be applied in the order they are added to the noise model. @@ -261,8 +257,7 @@ def _apply_gate_noise( circuit: Circuit, gate_noise_instructions: list[NoiseModelInstruction], ) -> Circuit: - """ - Applies the gate noise to return a new circuit that's the `noisy` version of the given + """Applies the gate noise to return a new circuit that's the `noisy` version of the given circuit. Args: @@ -295,8 +290,8 @@ def _apply_init_noise( circuit: Circuit, init_noise_instructions: list[NoiseModelInstruction], ) -> Circuit: - """ - Applies the initialization noise of this noise model to a circuit and returns the circuit. + """Applies the initialization noise of this noise model to a circuit and returns + the circuit. Args: circuit (Circuit): A circuit to apply `noise` to. @@ -320,8 +315,7 @@ def _apply_readout_noise( circuit: Circuit, readout_noise_instructions: list[NoiseModelInstruction], ) -> Circuit: - """ - Applies the readout noise of this noise model to a circuit and returns the circuit. + """Applies the readout noise of this noise model to a circuit and returns the circuit. Args: circuit (Circuit): A circuit to apply `noise` to. @@ -339,8 +333,7 @@ def _apply_readout_noise( def _items_to_string( cls, instructions_title: str, instructions: list[NoiseModelInstruction] ) -> list[str]: - """ - Creates a string representation of a list of instructions. + """Creates a string representation of a list of instructions. Args: instructions_title (str): The title for this list of instructions. @@ -358,8 +351,8 @@ def _items_to_string( @classmethod def from_dict(cls, noise_dict: dict) -> NoiseModel: - """ - Converts a dictionary representing an object of this class into an instance of this class. + """Converts a dictionary representing an object of this class into an instance + of this class. Args: noise_dict (dict): A dictionary representation of an object of this class. diff --git a/src/braket/circuits/noise_model/observable_criteria.py b/src/braket/circuits/noise_model/observable_criteria.py index 2275ccce7..1a2126502 100644 --- a/src/braket/circuits/noise_model/observable_criteria.py +++ b/src/braket/circuits/noise_model/observable_criteria.py @@ -33,8 +33,7 @@ def __init__( observables: Optional[Union[Observable, Iterable[Observable]]] = None, qubits: Optional[QubitSetInput] = None, ): - """ - Creates Observable-based Criteria. See instruction_matches() for more details. + """Creates Observable-based Criteria. See instruction_matches() for more details. Args: observables (Optional[Union[Observable, Iterable[Observable]]]): A set of relevant @@ -66,7 +65,8 @@ def __repr__(self): return f"{self.__class__.__name__}(observables={observables_names}, qubits={self._qubits})" def applicable_key_types(self) -> Iterable[CriteriaKey]: - """ + """Returns an Iterable of criteria keys. + Returns: Iterable[CriteriaKey]: This Criteria operates on Observables and Qubits. """ @@ -93,8 +93,8 @@ def get_keys(self, key_type: CriteriaKey) -> Union[CriteriaKeyResult, set[Any]]: return set() def to_dict(self) -> dict: - """ - Converts a dictionary representing an object of this class into an instance of this class. + """Converts a dictionary representing an object of this class into an instance of + this class. Returns: dict: A dictionary representing the serialized version of this Criteria. @@ -116,6 +116,7 @@ def result_type_matches(self, result_type: ResultType) -> bool: Args: result_type (ResultType): A result type or list of result types to match. + Returns: bool: Returns true if the result type is one of the Observables provided in the constructor and the target is a qubit (or set of qubits)provided in the constructor. diff --git a/src/braket/circuits/noise_model/qubit_initialization_criteria.py b/src/braket/circuits/noise_model/qubit_initialization_criteria.py index abed13af8..eb8ea0f21 100644 --- a/src/braket/circuits/noise_model/qubit_initialization_criteria.py +++ b/src/braket/circuits/noise_model/qubit_initialization_criteria.py @@ -24,8 +24,7 @@ class QubitInitializationCriteria(InitializationCriteria): """This class models initialization noise Criteria based on qubits.""" def __init__(self, qubits: Optional[QubitSetInput] = None): - """ - Creates initialization noise Qubit-based Criteria. + """Creates initialization noise Qubit-based Criteria. Args: qubits (Optional[QubitSetInput]): A set of relevant qubits. If no qubits @@ -40,7 +39,8 @@ def __repr__(self): return f"{self.__class__.__name__}(qubits={self._qubits})" def applicable_key_types(self) -> Iterable[CriteriaKey]: - """ + """Gets the QUBIT criteria key. + Returns: Iterable[CriteriaKey]: This Criteria operates on Qubits, but is valid for all Gates. """ @@ -65,8 +65,8 @@ def get_keys(self, key_type: CriteriaKey) -> Union[CriteriaKeyResult, set[Any]]: return set() def to_dict(self) -> dict: - """ - Converts a dictionary representing an object of this class into an instance of this class. + """Converts a dictionary representing an object of this class into an instance of + this class. Returns: dict: A dictionary representing the serialized version of this Criteria. @@ -78,8 +78,7 @@ def to_dict(self) -> dict: } def qubit_intersection(self, qubits: QubitSetInput) -> QubitSetInput: - """ - Returns subset of passed qubits that match the criteria. + """Returns subset of passed qubits that match the criteria. Args: qubits (QubitSetInput): A qubit or set of qubits that may match the criteria. @@ -94,8 +93,7 @@ def qubit_intersection(self, qubits: QubitSetInput) -> QubitSetInput: @classmethod def from_dict(cls, criteria: dict) -> Criteria: - """ - Deserializes a dictionary into a Criteria object. + """Deserializes a dictionary into a Criteria object. Args: criteria (dict): A dictionary representation of a QubitCriteria. diff --git a/src/braket/circuits/noise_model/result_type_criteria.py b/src/braket/circuits/noise_model/result_type_criteria.py index 77c8d0d68..4d52c5c29 100644 --- a/src/braket/circuits/noise_model/result_type_criteria.py +++ b/src/braket/circuits/noise_model/result_type_criteria.py @@ -26,6 +26,7 @@ def result_type_matches(self, result_type: ResultType) -> bool: Args: result_type (ResultType): A result type or list of result types to match. + Returns: bool: True if the result type matches the criteria. """ diff --git a/src/braket/circuits/noise_model/unitary_gate_criteria.py b/src/braket/circuits/noise_model/unitary_gate_criteria.py index 229fc11ba..34b348e2e 100644 --- a/src/braket/circuits/noise_model/unitary_gate_criteria.py +++ b/src/braket/circuits/noise_model/unitary_gate_criteria.py @@ -26,14 +26,14 @@ class UnitaryGateCriteria(CircuitInstructionCriteria): """This class models noise Criteria based on unitary gates represented as a matrix.""" def __init__(self, unitary: Unitary, qubits: Optional[QubitSetInput] = None): - """ - Creates unitary gate-based Criteria. See instruction_matches() for more details. + """Creates unitary gate-based Criteria. See instruction_matches() for more details. Args: unitary (Unitary): A unitary gate matrix represented as a Braket Unitary. qubits (Optional[QubitSetInput]): A set of relevant qubits. If no qubits are provided, all (possible) qubits are considered to be relevant. - Throws: + + Raises: ValueError: If unitary is not a Unitary type. """ if not isinstance(unitary, Unitary): @@ -48,7 +48,8 @@ def __repr__(self): return f"{self.__class__.__name__}(unitary={self._unitary}, qubits={self._qubits})" def applicable_key_types(self) -> Iterable[CriteriaKey]: - """ + """Returns keys based on criterion. + Returns: Iterable[CriteriaKey]: This Criteria operates on unitary gates and Qubits. """ @@ -75,8 +76,8 @@ def get_keys(self, key_type: CriteriaKey) -> Union[CriteriaKeyResult, set[Any]]: return set() def to_dict(self) -> dict: - """ - Converts a dictionary representing an object of this class into an instance of this class. + """Converts a dictionary representing an object of this class into an instance of + this class. Returns: dict: A dictionary representing the serialized version of this Criteria. diff --git a/src/braket/circuits/noises.py b/src/braket/circuits/noises.py index 572489a9d..904f7ac74 100644 --- a/src/braket/circuits/noises.py +++ b/src/braket/circuits/noises.py @@ -13,7 +13,7 @@ import itertools from collections.abc import Iterable -from typing import Any, Union +from typing import Any, ClassVar, Union import numpy as np @@ -52,7 +52,7 @@ class BitFlip(SingleProbabilisticNoise): - """Bit flip noise channel which transforms a density matrix :math:`\\rho` according to: + r"""Bit flip noise channel which transforms a density matrix :math:`\\rho` according to: .. math:: \\rho \\Rightarrow (1-p) \\rho + p X \\rho X^{\\dagger} @@ -96,6 +96,7 @@ def _to_openqasm( def to_matrix(self) -> Iterable[np.ndarray]: """Returns a matrix representation of this noise. + Returns: Iterable[ndarray]: A list of matrix representations of this noise. """ @@ -127,9 +128,11 @@ def bit_flip(target: QubitSetInput, probability: float) -> Iterable[Instruction] for qubit in QubitSet(target) ] - def bind_values(self, **kwargs) -> Noise: - """ - Takes in parameters and attempts to assign them to values. + def bind_values(self, **kwargs: Union[FreeParameter, str]) -> Noise: + """Takes in parameters and attempts to assign them to values. + + Args: + **kwargs (Union[FreeParameter, str]): Arbitrary keyword arguments. Returns: Noise: A new Noise object of the same type with the requested @@ -139,8 +142,7 @@ def bind_values(self, **kwargs) -> Noise: @classmethod def from_dict(cls, noise: dict) -> Noise: - """ - Converts a dictionary representation of this class into this class. + """Converts a dictionary representation of this class into this class. Args: noise(dict): The dictionary representation of this noise. @@ -155,7 +157,7 @@ def from_dict(cls, noise: dict) -> Noise: class PhaseFlip(SingleProbabilisticNoise): - """Phase flip noise channel which transforms a density matrix :math:`\\rho` according to: + r"""Phase flip noise channel which transforms a density matrix :math:`\\rho` according to: .. math:: \\rho \\Rightarrow (1-p) \\rho + p X \\rho X^{\\dagger} @@ -199,6 +201,7 @@ def _to_openqasm( def to_matrix(self) -> Iterable[np.ndarray]: """Returns a matrix representation of this noise. + Returns: Iterable[ndarray]: A list of matrix representations of this noise. """ @@ -230,9 +233,11 @@ def phase_flip(target: QubitSetInput, probability: float) -> Iterable[Instructio for qubit in QubitSet(target) ] - def bind_values(self, **kwargs) -> Noise: - """ - Takes in parameters and attempts to assign them to values. + def bind_values(self, **kwargs: Union[FreeParameter, str]) -> Noise: + """Takes in parameters and attempts to assign them to values. + + Args: + **kwargs (Union[FreeParameter, str]): Arbitrary keyword arguments. Returns: Noise: A new Noise object of the same type with the requested @@ -242,8 +247,7 @@ def bind_values(self, **kwargs) -> Noise: @classmethod def from_dict(cls, noise: dict) -> Noise: - """ - Converts a dictionary representation of this class into this class. + """Converts a dictionary representation of this class into this class. Args: noise(dict): The dictionary representation of this noise. @@ -258,7 +262,7 @@ def from_dict(cls, noise: dict) -> Noise: class PauliChannel(PauliNoise): - """Pauli noise channel which transforms a density matrix :math:`\\rho` according to: + r"""Pauli noise channel which transforms a density matrix :math:`\\rho` according to: .. math:: \\rho \\Rightarrow (1-probX-probY-probZ) \\rho @@ -307,6 +311,7 @@ def __init__( probZ: Union[FreeParameterExpression, float], ): """Creates PauliChannel noise. + Args: probX (Union[FreeParameterExpression, float]): X rotation probability. probY (Union[FreeParameterExpression, float]): Y rotation probability. @@ -336,6 +341,7 @@ def _to_openqasm( def to_matrix(self) -> Iterable[np.ndarray]: """Returns a matrix representation of this noise. + Returns: Iterable[ndarray]: A list of matrix representations of this noise. """ @@ -376,8 +382,7 @@ def pauli_channel( ] def bind_values(self, **kwargs) -> Noise: - """ - Takes in parameters and attempts to assign them to values. + """Takes in parameters and attempts to assign them to values. Returns: Noise: A new Noise object of the same type with the requested @@ -391,8 +396,7 @@ def bind_values(self, **kwargs) -> Noise: @classmethod def from_dict(cls, noise: dict) -> Noise: - """ - Converts a dictionary representation of this class into this class. + """Converts a dictionary representation of this class into this class. Args: noise(dict): The dictionary representation of this noise. @@ -411,7 +415,7 @@ def from_dict(cls, noise: dict) -> Noise: class Depolarizing(SingleProbabilisticNoise_34): - """Depolarizing noise channel which transforms a density matrix :math:`\\rho` according to: + r"""Depolarizing noise channel which transforms a density matrix :math:`\\rho` according to: .. math:: \\rho \\Rightarrow (1-p) \\rho @@ -473,6 +477,7 @@ def _to_openqasm( def to_matrix(self) -> Iterable[np.ndarray]: """Returns a matrix representation of this noise. + Returns: Iterable[ndarray]: A list of matrix representations of this noise. """ @@ -507,8 +512,7 @@ def depolarizing(target: QubitSetInput, probability: float) -> Iterable[Instruct ] def bind_values(self, **kwargs) -> Noise: - """ - Takes in parameters and attempts to assign them to values. + """Takes in parameters and attempts to assign them to values. Returns: Noise: A new Noise object of the same type with the requested @@ -518,8 +522,7 @@ def bind_values(self, **kwargs) -> Noise: @classmethod def from_dict(cls, noise: dict) -> Noise: - """ - Converts a dictionary representation of this class into this class. + """Converts a dictionary representation of this class into this class. Args: noise(dict): The dictionary representation of this noise. @@ -534,7 +537,7 @@ def from_dict(cls, noise: dict) -> Noise: class TwoQubitDepolarizing(SingleProbabilisticNoise_1516): - """Two-Qubit Depolarizing noise channel which transforms a + r"""Two-Qubit Depolarizing noise channel which transforms a density matrix :math:`\\rho` according to: .. math:: @@ -605,10 +608,10 @@ def _to_openqasm( def to_matrix(self) -> Iterable[np.ndarray]: """Returns a matrix representation of this noise. + Returns: Iterable[ndarray]: A list of matrix representations of this noise. """ - SI = np.array([[1.0, 0.0], [0.0, 1.0]], dtype=complex) SX = np.array([[0.0, 1.0], [1.0, 0.0]], dtype=complex) SY = np.array([[0.0, -1.0j], [1.0j, 0.0]], dtype=complex) @@ -652,8 +655,7 @@ def two_qubit_depolarizing( ] def bind_values(self, **kwargs) -> Noise: - """ - Takes in parameters and attempts to assign them to values. + """Takes in parameters and attempts to assign them to values. Returns: Noise: A new Noise object of the same type with the requested @@ -663,8 +665,7 @@ def bind_values(self, **kwargs) -> Noise: @classmethod def from_dict(cls, noise: dict) -> Noise: - """ - Converts a dictionary representation of this class into this class. + """Converts a dictionary representation of this class into this class. Args: noise(dict): The dictionary representation of this noise. @@ -679,7 +680,7 @@ def from_dict(cls, noise: dict) -> Noise: class TwoQubitDephasing(SingleProbabilisticNoise_34): - """Two-Qubit Dephasing noise channel which transforms a + r"""Two-Qubit Dephasing noise channel which transforms a density matrix :math:`\\rho` according to: .. math:: @@ -732,6 +733,7 @@ def _to_openqasm( def to_matrix(self) -> Iterable[np.ndarray]: """Returns a matrix representation of this noise. + Returns: Iterable[ndarray]: A list of matrix representations of this noise. """ @@ -771,8 +773,7 @@ def two_qubit_dephasing( ] def bind_values(self, **kwargs) -> Noise: - """ - Takes in parameters and attempts to assign them to values. + """Takes in parameters and attempts to assign them to values. Returns: Noise: A new Noise object of the same type with the requested @@ -782,8 +783,7 @@ def bind_values(self, **kwargs) -> Noise: @classmethod def from_dict(cls, noise: dict) -> Noise: - """ - Converts a dictionary representation of this class into this class. + """Converts a dictionary representation of this class into this class. Args: noise(dict): The dictionary representation of this noise. @@ -798,7 +798,7 @@ def from_dict(cls, noise: dict) -> Noise: class TwoQubitPauliChannel(MultiQubitPauliNoise): - """Two-Qubit Pauli noise channel which transforms a + r"""Two-Qubit Pauli noise channel which transforms a density matrix :math:`\\rho` according to: .. math:: @@ -855,14 +855,14 @@ class TwoQubitPauliChannel(MultiQubitPauliNoise): This noise channel is shown as `PC_2({"pauli_string": probability})` in circuit diagrams. """ - _paulis = { + _paulis: ClassVar = { "I": np.array([[1.0, 0.0], [0.0, 1.0]], dtype=complex), "X": np.array([[0.0, 1.0], [1.0, 0.0]], dtype=complex), "Y": np.array([[0.0, -1.0j], [1.0j, 0.0]], dtype=complex), "Z": np.array([[1.0, 0.0], [0.0, -1.0]], dtype=complex), } _tensor_products_strings = itertools.product(_paulis.keys(), repeat=2) - _names_list = ["".join(x) for x in _tensor_products_strings] + _names_list: ClassVar = ["".join(x) for x in _tensor_products_strings] def __init__(self, probabilities: dict[str, float]): super().__init__( @@ -877,6 +877,7 @@ def __init__(self, probabilities: dict[str, float]): def to_matrix(self) -> Iterable[np.ndarray]: """Returns a matrix representation of this noise. + Returns: Iterable[ndarray]: A list of matrix representations of this noise. """ @@ -930,8 +931,7 @@ def two_qubit_pauli_channel( ] def bind_values(self, **kwargs) -> Noise: - """ - Takes in parameters and attempts to assign them to values. + """Takes in parameters and attempts to assign them to values. Returns: Noise: A new Noise object of the same type with the requested @@ -945,8 +945,7 @@ def bind_values(self, **kwargs) -> Noise: @classmethod def from_dict(cls, noise: dict) -> Noise: - """ - Converts a dictionary representation of this class into this class. + """Converts a dictionary representation of this class into this class. Args: noise(dict): The dictionary representation of this noise. @@ -954,7 +953,7 @@ def from_dict(cls, noise: dict) -> Noise: Returns: Noise: A Noise object that represents the passed in dictionary. """ - probabilities = dict() + probabilities = {} for pauli_string, prob in noise["probabilities"].items(): probabilities[pauli_string] = _parameter_from_dict(prob) return TwoQubitPauliChannel(probabilities=probabilities) @@ -964,7 +963,7 @@ def from_dict(cls, noise: dict) -> Noise: class AmplitudeDamping(DampingNoise): - """AmplitudeDamping noise channel which transforms a density matrix :math:`\\rho` according to: + r"""AmplitudeDamping noise channel which transforms a density matrix :math:`\\rho` according to: .. math:: \\rho \\Rightarrow E_0 \\rho E_0^{\\dagger} + E_1 \\rho E_1^{\\dagger} @@ -1006,6 +1005,7 @@ def _to_openqasm( def to_matrix(self) -> Iterable[np.ndarray]: """Returns a matrix representation of this noise. + Returns: Iterable[ndarray]: A list of matrix representations of this noise. """ @@ -1038,8 +1038,7 @@ def amplitude_damping(target: QubitSetInput, gamma: float) -> Iterable[Instructi ] def bind_values(self, **kwargs) -> Noise: - """ - Takes in parameters and attempts to assign them to values. + """Takes in parameters and attempts to assign them to values. Returns: Noise: A new Noise object of the same type with the requested @@ -1049,8 +1048,7 @@ def bind_values(self, **kwargs) -> Noise: @classmethod def from_dict(cls, noise: dict) -> Noise: - """ - Converts a dictionary representation of this class into this class. + """Converts a dictionary representation of this class into this class. Args: noise(dict): The dictionary representation of this noise. @@ -1065,7 +1063,7 @@ def from_dict(cls, noise: dict) -> Noise: class GeneralizedAmplitudeDamping(GeneralizedAmplitudeDampingNoise): - """Generalized AmplitudeDamping noise channel which transforms a + r"""Generalized AmplitudeDamping noise channel which transforms a density matrix :math:`\\rho` according to: .. math:: \\rho \\Rightarrow E_0 \\rho E_0^{\\dagger} + E_1 \\rho E_1^{\\dagger} @@ -1131,6 +1129,7 @@ def _to_openqasm( def to_matrix(self) -> Iterable[np.ndarray]: """Returns a matrix representation of this noise. + Returns: Iterable[ndarray]: A list of matrix representations of this noise. """ @@ -1175,8 +1174,7 @@ def generalized_amplitude_damping( ] def bind_values(self, **kwargs) -> Noise: - """ - Takes in parameters and attempts to assign them to values. + """Takes in parameters and attempts to assign them to values. Returns: Noise: A new Noise object of the same type with the requested @@ -1188,8 +1186,7 @@ def bind_values(self, **kwargs) -> Noise: @classmethod def from_dict(cls, noise: dict) -> Noise: - """ - Converts a dictionary representation of this class into this class. + """Converts a dictionary representation of this class into this class. Args: noise(dict): The dictionary representation of this noise. @@ -1207,7 +1204,7 @@ def from_dict(cls, noise: dict) -> Noise: class PhaseDamping(DampingNoise): - """Phase damping noise channel which transforms a density matrix :math:`\\rho` according to: + r"""Phase damping noise channel which transforms a density matrix :math:`\\rho` according to: .. math:: \\rho \\Rightarrow E_0 \\rho E_0^{\\dagger} + E_1 \\rho E_1^{\\dagger} @@ -1251,6 +1248,7 @@ def _to_openqasm( def to_matrix(self) -> Iterable[np.ndarray]: """Returns a matrix representation of this noise. + Returns: Iterable[ndarray]: A list of matrix representations of this noise. """ @@ -1282,8 +1280,7 @@ def phase_damping(target: QubitSetInput, gamma: float) -> Iterable[Instruction]: ] def bind_values(self, **kwargs) -> Noise: - """ - Takes in parameters and attempts to assign them to values. + """Takes in parameters and attempts to assign them to values. Returns: Noise: A new Noise object of the same type with the requested @@ -1293,8 +1290,7 @@ def bind_values(self, **kwargs) -> Noise: @classmethod def from_dict(cls, noise: dict) -> Noise: - """ - Converts a dictionary representation of this class into this class. + """Converts a dictionary representation of this class into this class. Args: noise(dict): The dictionary representation of this noise. @@ -1311,21 +1307,24 @@ def from_dict(cls, noise: dict) -> Noise: class Kraus(Noise): """User-defined noise channel that uses the provided matrices as Kraus operators This noise channel is shown as `NK` in circuit diagrams. - - Args: - matrices (Iterable[np.array]): A list of matrices that define a noise - channel. These matrices need to satisfy the requirement of CPTP map. - display_name (str): Name to be used for an instance of this general noise - channel for circuit diagrams. Defaults to `KR`. - - Raises: - ValueError: If any matrix in `matrices` is not a two-dimensional square - matrix, - or has a dimension length which is not a positive exponent of 2, - or the `matrices` do not satisfy CPTP condition. """ def __init__(self, matrices: Iterable[np.ndarray], display_name: str = "KR"): + """Inits `Kraus`. + + Args: + matrices (Iterable[ndarray]): A list of matrices that define a noise + channel. These matrices need to satisfy the requirement of CPTP map. + display_name (str): Name to be used for an instance of this general noise + channel for circuit diagrams. Defaults to `KR`. + + Raises: + ValueError: If any matrix in `matrices` is not a two-dimensional square + matrix, + or has a dimension length which is not a positive exponent of 2, + or the `matrices` do not satisfy CPTP condition. + + """ for matrix in matrices: verify_quantum_operator_matrix_dimensions(matrix) if not int(np.log2(matrix.shape[0])) == int(np.log2(matrices[0].shape[0])): @@ -1347,6 +1346,7 @@ def __init__(self, matrices: Iterable[np.ndarray], display_name: str = "KR"): def to_matrix(self) -> Iterable[np.ndarray]: """Returns a matrix representation of this noise. + Returns: Iterable[ndarray]: A list of matrix representations of this noise. """ @@ -1354,7 +1354,7 @@ def to_matrix(self) -> Iterable[np.ndarray]: def _to_jaqcd(self, target: QubitSet) -> Any: return ir.Kraus.construct( - targets=[qubit for qubit in target], + targets=list(target), matrices=Kraus._transform_matrix_to_ir(self._matrices), ) @@ -1414,8 +1414,7 @@ def kraus( ) def to_dict(self) -> dict: - """ - Converts this object into a dictionary representation. Not implemented at this time. + """Converts this object into a dictionary representation. Not implemented at this time. Returns: dict: Not implemented at this time.. @@ -1424,8 +1423,7 @@ def to_dict(self) -> dict: @classmethod def from_dict(cls, noise: dict) -> Noise: - """ - Converts a dictionary representation of this class into this class. + """Converts a dictionary representation of this class into this class. Args: noise(dict): The dictionary representation of this noise. @@ -1442,8 +1440,7 @@ def from_dict(cls, noise: dict) -> Noise: def _ascii_representation( noise: str, parameters: list[Union[FreeParameterExpression, float]] ) -> str: - """ - Generates a formatted ascii representation of a noise. + """Generates a formatted ascii representation of a noise. Args: noise (str): The name of the noise. @@ -1455,7 +1452,7 @@ def _ascii_representation( param_list = [] for param in parameters: param_list.append( - str(param) if isinstance(param, FreeParameterExpression) else "{:.2g}".format(param) + str(param) if isinstance(param, FreeParameterExpression) else f"{param:.2g}" ) param_str = ",".join(param_list) return f"{noise}({param_str})" diff --git a/src/braket/circuits/observable.py b/src/braket/circuits/observable.py index 03cd0714e..d3f3fc862 100644 --- a/src/braket/circuits/observable.py +++ b/src/braket/circuits/observable.py @@ -31,8 +31,7 @@ class Observable(QuantumOperator): - """ - Class `Observable` to represent a quantum observable. + """Class `Observable` to represent a quantum observable. Objects of this type can be used as input to `ResultType.Sample`, `ResultType.Variance`, `ResultType.Expectation` to specify the measurement basis. @@ -67,7 +66,7 @@ def to_ir( Raises: ValueError: If the supplied `ir_type` is not supported, or if the supplied serialization - properties don't correspond to the `ir_type`. + properties don't correspond to the `ir_type`. """ if ir_type == IRType.JAQCD: return self._to_jaqcd() @@ -94,8 +93,7 @@ def _to_openqasm( serialization_properties: OpenQASMSerializationProperties, target: QubitSet | None = None, ) -> str: - """ - Returns the openqasm string representation of the result type. + """Returns the openqasm string representation of the result type. Args: serialization_properties (OpenQASMSerializationProperties): The serialization properties @@ -109,7 +107,8 @@ def _to_openqasm( @property def coefficient(self) -> int: - """ + """The coefficient of the observable. + Returns: int: coefficient value of the observable. """ @@ -118,6 +117,7 @@ def coefficient(self) -> int: @property def basis_rotation_gates(self) -> tuple[Gate, ...]: """Returns the basis rotation gates for this observable. + Returns: tuple[Gate, ...]: The basis rotation gates for this observable. """ @@ -126,8 +126,9 @@ def basis_rotation_gates(self) -> tuple[Gate, ...]: @property def eigenvalues(self) -> np.ndarray: """Returns the eigenvalues of this observable. + Returns: - ndarray: The eigenvalues of this observable. + np.ndarray: The eigenvalues of this observable. """ raise NotImplementedError @@ -154,13 +155,13 @@ def register_observable(cls, observable: Observable) -> None: """ setattr(cls, observable.__name__, observable) - def __matmul__(self, other) -> Observable.TensorProduct: + def __matmul__(self, other: Observable) -> Observable.TensorProduct: if isinstance(other, Observable): return Observable.TensorProduct([self, other]) raise ValueError("Can only perform tensor products between observables.") - def __mul__(self, other) -> Observable: + def __mul__(self, other: Observable) -> Observable: """Scalar multiplication""" if isinstance(other, numbers.Number): observable_copy = deepcopy(self) @@ -168,16 +169,16 @@ def __mul__(self, other) -> Observable: return observable_copy raise TypeError("Observable coefficients must be numbers.") - def __rmul__(self, other) -> Observable: + def __rmul__(self, other: Observable) -> Observable: return self * other - def __add__(self, other): + def __add__(self, other: Observable): if not isinstance(other, Observable): raise ValueError("Can only perform addition between observables.") return Observable.Sum([self, other]) - def __sub__(self, other): + def __sub__(self, other: Observable): if not isinstance(other, Observable): raise ValueError("Can only perform subtraction between observables.") @@ -186,15 +187,14 @@ def __sub__(self, other): def __repr__(self) -> str: return f"{self.name}('qubit_count': {self.qubit_count})" - def __eq__(self, other) -> bool: + def __eq__(self, other: Observable) -> bool: if isinstance(other, Observable): return self.name == other.name return NotImplemented class StandardObservable(Observable): - """ - Class `StandardObservable` to represent a Pauli-like quantum observable with + """Class `StandardObservable` to represent a Pauli-like quantum observable with eigenvalues of (+1, -1). """ diff --git a/src/braket/circuits/observables.py b/src/braket/circuits/observables.py index dc0ff0782..2d5ccdb68 100644 --- a/src/braket/circuits/observables.py +++ b/src/braket/circuits/observables.py @@ -18,7 +18,7 @@ import math import numbers from copy import deepcopy -from typing import Union +from typing import ClassVar, Union import numpy as np @@ -37,9 +37,8 @@ class H(StandardObservable): """Hadamard operation as an observable.""" def __init__(self): - """ - Examples: - >>> Observable.H() + """Examples: + >>> Observable.H() """ super().__init__(ascii_symbols=["H"]) @@ -68,19 +67,18 @@ def to_matrix(self) -> np.ndarray: @property def basis_rotation_gates(self) -> tuple[Gate, ...]: - return tuple([Gate.Ry(-math.pi / 4)]) + return tuple([Gate.Ry(-math.pi / 4)]) # noqa: C409 Observable.register_observable(H) -class I(Observable): # noqa: E742, E261 +class I(Observable): # noqa: E742 """Identity operation as an observable.""" def __init__(self): - """ - Examples: - >>> Observable.I() + """Examples: + >>> Observable.I() """ super().__init__(qubit_count=1, ascii_symbols=["I"]) @@ -112,6 +110,7 @@ def basis_rotation_gates(self) -> tuple[Gate, ...]: @property def eigenvalues(self) -> np.ndarray: """Returns the eigenvalues of this observable. + Returns: np.ndarray: The eigenvalues of this observable. """ @@ -128,9 +127,8 @@ class X(StandardObservable): """Pauli-X operation as an observable.""" def __init__(self): - """ - Examples: - >>> Observable.X() + """Examples: + >>> Observable.X() """ super().__init__(ascii_symbols=["X"]) @@ -157,7 +155,7 @@ def to_matrix(self) -> np.ndarray: @property def basis_rotation_gates(self) -> tuple[Gate, ...]: - return tuple([Gate.H()]) + return tuple([Gate.H()]) # noqa: C409 Observable.register_observable(X) @@ -167,9 +165,8 @@ class Y(StandardObservable): """Pauli-Y operation as an observable.""" def __init__(self): - """ - Examples: - >>> Observable.Y() + """Examples: + >>> Observable.Y() """ super().__init__(ascii_symbols=["Y"]) @@ -196,7 +193,7 @@ def to_matrix(self) -> np.ndarray: @property def basis_rotation_gates(self) -> tuple[Gate, ...]: - return tuple([Gate.Z(), Gate.S(), Gate.H()]) + return tuple([Gate.Z(), Gate.S(), Gate.H()]) # noqa: C409 Observable.register_observable(Y) @@ -206,9 +203,8 @@ class Z(StandardObservable): """Pauli-Z operation as an observable.""" def __init__(self): - """ - Examples: - >>> Observable.Z() + """Examples: + >>> Observable.Z() """ super().__init__(ascii_symbols=["Z"]) @@ -245,7 +241,8 @@ class TensorProduct(Observable): """Tensor product of observables""" def __init__(self, observables: list[Observable]): - """ + """Initializes a `TensorProduct`. + Args: observables (list[Observable]): List of observables for tensor product @@ -348,6 +345,7 @@ def to_matrix(self) -> np.ndarray: @property def basis_rotation_gates(self) -> tuple[Gate, ...]: """Returns the basis rotation gates for this observable. + Returns: tuple[Gate, ...]: The basis rotation gates for this observable. """ @@ -359,6 +357,7 @@ def basis_rotation_gates(self) -> tuple[Gate, ...]: @property def eigenvalues(self) -> np.ndarray: """Returns the eigenvalues of this observable. + Returns: np.ndarray: The eigenvalues of this observable. """ @@ -400,7 +399,7 @@ def eigenvalue(self, index: int) -> float: def __repr__(self): return "TensorProduct(" + ", ".join([repr(o) for o in self.factors]) + ")" - def __eq__(self, other): + def __eq__(self, other: TensorProduct): return self.matrix_equivalence(other) @staticmethod @@ -432,7 +431,8 @@ class Sum(Observable): """Sum of observables""" def __init__(self, observables: list[Observable], display_name: str = "Hamiltonian"): - """ + """Inits a `Sum`. + Args: observables (list[Observable]): List of observables for Sum display_name (str): Name to use for an instance of this Sum @@ -456,11 +456,11 @@ def __init__(self, observables: list[Observable], display_name: str = "Hamiltoni qubit_count = max(flattened_observables, key=lambda obs: obs.qubit_count).qubit_count super().__init__(qubit_count=qubit_count, ascii_symbols=[display_name] * qubit_count) - def __mul__(self, other) -> Observable: + def __mul__(self, other: numbers.Number) -> Observable: """Scalar multiplication""" if isinstance(other, numbers.Number): sum_copy = deepcopy(self) - for i, obs in enumerate(sum_copy.summands): + for i, _obs in enumerate(sum_copy.summands): sum_copy._summands[i]._coef *= other return sum_copy raise TypeError("Observable coefficients must be numbers.") @@ -514,7 +514,7 @@ def eigenvalue(self, index: int) -> float: def __repr__(self): return "Sum(" + ", ".join([repr(o) for o in self.summands]) + ")" - def __eq__(self, other): + def __eq__(self, other: Sum): return repr(self) == repr(other) @staticmethod @@ -529,12 +529,13 @@ class Hermitian(Observable): """Hermitian matrix as an observable.""" # Cache of eigenpairs - _eigenpairs = {} + _eigenpairs: ClassVar = {} def __init__(self, matrix: np.ndarray, display_name: str = "Hermitian"): - """ + """Inits a `Hermitian`. + Args: - matrix (numpy.ndarray): Hermitian matrix that defines the observable. + matrix (np.ndarray): Hermitian matrix that defines the observable. display_name (str): Name to use for an instance of this Hermitian matrix observable for circuit diagrams. Defaults to `Hermitian`. @@ -594,7 +595,7 @@ def _serialized_matrix_openqasm_matrix(self) -> str: def to_matrix(self) -> np.ndarray: return self.coefficient * self._matrix - def __eq__(self, other) -> bool: + def __eq__(self, other: Hermitian) -> bool: return self.matrix_equivalence(other) @property @@ -604,6 +605,7 @@ def basis_rotation_gates(self) -> tuple[Gate, ...]: @property def eigenvalues(self) -> np.ndarray: """Returns the eigenvalues of this observable. + Returns: np.ndarray: The eigenvalues of this observable. """ @@ -614,8 +616,7 @@ def eigenvalue(self, index: int) -> float: @staticmethod def _get_eigendecomposition(matrix: np.ndarray) -> dict[str, np.ndarray]: - """ - Decomposes the Hermitian matrix into its eigenvectors and associated eigenvalues. + """Decomposes the Hermitian matrix into its eigenvectors and associated eigenvalues. The eigendecomposition is cached so that if another Hermitian observable is created with the same matrix, the eigendecomposition doesn't have to be recalculated. @@ -649,8 +650,7 @@ def __repr__(self): def observable_from_ir(ir_observable: list[Union[str, list[list[list[float]]]]]) -> Observable: - """ - Create an observable from the IR observable list. This can be a tensor product of + """Create an observable from the IR observable list. This can be a tensor product of observables or a single observable. Args: diff --git a/src/braket/circuits/operator.py b/src/braket/circuits/operator.py index 06e72c8a8..ccd63ac37 100644 --- a/src/braket/circuits/operator.py +++ b/src/braket/circuits/operator.py @@ -22,14 +22,14 @@ class Operator(ABC): @abstractmethod def name(self) -> str: """The name of the operator. + Returns: str: The name of the operator. """ @abstractmethod def to_ir(self, *args, **kwargs) -> Any: - """ - Converts the operator into the canonical intermediate representation. + """Converts the operator into the canonical intermediate representation. If the operator is passed in a request, this method is called before it is passed. Returns: diff --git a/src/braket/circuits/quantum_operator.py b/src/braket/circuits/quantum_operator.py index df67bf199..068c4171d 100644 --- a/src/braket/circuits/quantum_operator.py +++ b/src/braket/circuits/quantum_operator.py @@ -25,7 +25,8 @@ class QuantumOperator(Operator): """A quantum operator is the definition of a quantum operation for a quantum device.""" def __init__(self, qubit_count: Optional[int], ascii_symbols: Sequence[str]): - """ + """Initializes a `QuantumOperator`. + Args: qubit_count (Optional[int]): Number of qubits this quantum operator acts on. If all instances of the operator act on the same number of qubits, this argument @@ -48,7 +49,6 @@ def __init__(self, qubit_count: Optional[int], ascii_symbols: Sequence[str]): ``fixed_qubit_count`` is implemented and and not equal to ``qubit_count``, or ``len(ascii_symbols) != qubit_count`` """ - fixed_qubit_count = self.fixed_qubit_count() if fixed_qubit_count is NotImplemented: self._qubit_count = qubit_count @@ -79,8 +79,7 @@ def __init__(self, qubit_count: Optional[int], ascii_symbols: Sequence[str]): @staticmethod def fixed_qubit_count() -> int: - """ - Returns the number of qubits this quantum operator acts on, + """Returns the number of qubits this quantum operator acts on, if instances are guaranteed to act on the same number of qubits. If different instances can act on a different number of qubits, @@ -103,33 +102,45 @@ def ascii_symbols(self) -> tuple[str, ...]: @property def name(self) -> str: - """ - Returns the name of the quantum operator + """Returns the name of the quantum operator Returns: str: The name of the quantum operator as a string """ return self.__class__.__name__ - def to_ir(self, *args, **kwargs) -> Any: + def to_ir(self, *args: Any, **kwargs: Any) -> Any: """Returns IR representation of quantum operator. + Args: + *args (Any): Not Implemented. + **kwargs (Any): Not Implemented. + + Raises: + NotImplementError: Not Implemented. + Returns: Any: The the canonical intermediate representation of the operator. """ raise NotImplementedError("to_ir has not been implemented yet.") - def to_matrix(self, *args, **kwargs) -> np.ndarray: - """Returns a matrix representation of the quantum operator + def to_matrix(self, *args: Any, **kwargs: Any) -> np.ndarray: + """Returns a matrix representation of the quantum operator. + + Args: + *args (Any): Not Implemented. + **kwargs (Any): Not Implemented. + + Raises: + NotImplementError: Not Implemented. Returns: - ndarray: A matrix representation of the quantum operator + np.ndarray: A matrix representation of the quantum operator """ raise NotImplementedError("to_matrix has not been implemented yet.") def matrix_equivalence(self, other: QuantumOperator) -> bool: - """ - Whether the matrix form of two quantum operators are equivalent + """Whether the matrix form of two quantum operators are equivalent Args: other (QuantumOperator): Quantum operator instance to compare this quantum operator to diff --git a/src/braket/circuits/quantum_operator_helpers.py b/src/braket/circuits/quantum_operator_helpers.py index a264d0b38..8d64888ed 100644 --- a/src/braket/circuits/quantum_operator_helpers.py +++ b/src/braket/circuits/quantum_operator_helpers.py @@ -18,8 +18,7 @@ def verify_quantum_operator_matrix_dimensions(matrix: np.ndarray) -> None: - """ - Verifies matrix is square and matrix dimensions are positive powers of 2, + """Verifies matrix is square and matrix dimensions are positive powers of 2, raising `ValueError` otherwise. Args: @@ -40,8 +39,7 @@ def verify_quantum_operator_matrix_dimensions(matrix: np.ndarray) -> None: def is_hermitian(matrix: np.ndarray) -> bool: - r""" - Whether matrix is Hermitian + r"""Whether matrix is Hermitian A square matrix :math:`U` is Hermitian if @@ -59,11 +57,10 @@ def is_hermitian(matrix: np.ndarray) -> bool: def is_square_matrix(matrix: np.ndarray) -> bool: - """ - Whether matrix is square, meaning it has exactly two dimensions and the dimensions are equal + """Whether matrix is square, meaning it has exactly two dimensions and the dimensions are equal Args: - matrix (ndarray): matrix to verify + matrix (np.ndarray): matrix to verify Returns: bool: If matrix is square @@ -72,8 +69,7 @@ def is_square_matrix(matrix: np.ndarray) -> bool: def is_unitary(matrix: np.ndarray) -> bool: - r""" - Whether matrix is unitary + r"""Whether matrix is unitary A square matrix :math:`U` is unitary if @@ -83,7 +79,7 @@ def is_unitary(matrix: np.ndarray) -> bool: and :math:`I` is the identity matrix. Args: - matrix (ndarray): matrix to verify + matrix (np.ndarray): matrix to verify Returns: bool: If matrix is unitary @@ -92,8 +88,7 @@ def is_unitary(matrix: np.ndarray) -> bool: def is_cptp(matrices: Iterable[np.ndarray]) -> bool: - """ - Whether a transformation defined by these matrics as Kraus operators is a + """Whether a transformation defined by these matrics as Kraus operators is a completely positive trace preserving (CPTP) map. This is the requirement for a transformation to be a quantum channel. Reference: Section 8.2.3 in Nielsen & Chuang (2010) 10th edition. @@ -108,17 +103,16 @@ def is_cptp(matrices: Iterable[np.ndarray]) -> bool: return np.allclose(E, np.eye(*E.shape)) -@lru_cache() +@lru_cache def get_pauli_eigenvalues(num_qubits: int) -> np.ndarray: - """ - Get the eigenvalues of Pauli operators and their tensor products as + """Get the eigenvalues of Pauli operators and their tensor products as an immutable Numpy ndarray. Args: num_qubits (int): the number of qubits the operator acts on Returns: - ndarray: the eigenvalues of a Pauli product operator of the given size + np.ndarray: the eigenvalues of a Pauli product operator of the given size """ if num_qubits == 1: eigs = np.array([1, -1]) diff --git a/src/braket/circuits/result_type.py b/src/braket/circuits/result_type.py index c6877262e..b66d4da67 100644 --- a/src/braket/circuits/result_type.py +++ b/src/braket/circuits/result_type.py @@ -28,14 +28,14 @@ class ResultType: - """ - Class `ResultType` represents a requested result type for the circuit. + """Class `ResultType` represents a requested result type for the circuit. This class is considered the result type definition containing the metadata that defines what a requested result type is and what it does. """ def __init__(self, ascii_symbols: list[str]): - """ + """Initializes a `ResultType`. + Args: ascii_symbols (list[str]): ASCII string symbols for the result type. This is used when printing a diagram of circuits. @@ -43,7 +43,6 @@ def __init__(self, ascii_symbols: list[str]): Raises: ValueError: `ascii_symbols` is `None` """ - if ascii_symbols is None: raise ValueError("ascii_symbols must not be None") @@ -56,8 +55,7 @@ def ascii_symbols(self) -> list[str]: @property def name(self) -> str: - """ - Returns the name of the result type + """Returns the name of the result type Returns: str: The name of the result type as a string @@ -73,7 +71,7 @@ def to_ir( """Returns IR object of the result type Args: - ir_type(IRType) : The IRType to use for converting the result type object to its + ir_type(IRType): The IRType to use for converting the result type object to its IR representation. Defaults to IRType.JAQCD. serialization_properties (SerializationProperties | None): The serialization properties to use while serializing the object to the IR representation. The serialization @@ -84,7 +82,7 @@ def to_ir( Raises: ValueError: If the supplied `ir_type` is not supported, or if the supplied serialization - properties don't correspond to the `ir_type`. + properties don't correspond to the `ir_type`. """ if ir_type == IRType.JAQCD: return self._to_jaqcd() @@ -105,13 +103,15 @@ def _to_jaqcd(self) -> Any: raise NotImplementedError("to_jaqcd has not been implemented yet.") def _to_openqasm(self, serialization_properties: OpenQASMSerializationProperties) -> str: - """ - Returns the openqasm string representation of the result type. + """Returns the openqasm string representation of the result type. Args: serialization_properties (OpenQASMSerializationProperties): The serialization properties to use while serializing the object to the IR representation. + Raises: + NotImplementedError: not implemented. + Returns: str: Representing the openqasm representation of the result type. """ @@ -122,8 +122,7 @@ def copy( target_mapping: dict[QubitInput, QubitInput] | None = None, target: QubitSetInput | None = None, ) -> ResultType: - """ - Return a shallow copy of the result type. + """Return a shallow copy of the result type. Note: If `target_mapping` is specified, then `self.target` is mapped to the specified @@ -180,8 +179,7 @@ def __hash__(self) -> int: class ObservableResultType(ResultType): - """ - Result types with observables and targets. + """Result types with observables and targets. If no targets are specified, the observable must only operate on 1 qubit and it will be applied to all qubits in parallel. Otherwise, the number of specified targets must be equivalent to the number of qubits the observable can be applied to. @@ -192,7 +190,8 @@ class ObservableResultType(ResultType): def __init__( self, ascii_symbols: list[str], observable: Observable, target: QubitSetInput | None = None ): - """ + """Initializes an `ObservableResultType`. + Args: ascii_symbols (list[str]): ASCII string symbols for the result type. This is used when printing a diagram of circuits. @@ -215,29 +214,28 @@ def __init__( raise ValueError( f"Observable {self._observable} must only operate on 1 qubit for target=None" ) - else: - if isinstance(observable, Sum): # nested target - if len(target) != len(observable.summands): + elif isinstance(observable, Sum): # nested target + if len(target) != len(observable.summands): + raise ValueError( + "Sum observable's target shape must be a nested list where each term's " + "target length is equal to the observable term's qubits count." + ) + self._target = [QubitSet(term_target) for term_target in target] + for term_target, obs in zip(target, observable.summands): + if obs.qubit_count != len(term_target): raise ValueError( "Sum observable's target shape must be a nested list where each term's " "target length is equal to the observable term's qubits count." ) - self._target = [QubitSet(term_target) for term_target in target] - for term_target, obs in zip(target, observable.summands): - if obs.qubit_count != len(term_target): - raise ValueError( - "Sum observable's target shape must be a nested list where each term's " - "target length is equal to the observable term's qubits count." - ) - elif self._observable.qubit_count != len(self._target): - raise ValueError( - f"Observable's qubit count {self._observable.qubit_count} and " - f"the size of the target qubit set {self._target} must be equal" - ) - elif self._observable.qubit_count != len(self.ascii_symbols): - raise ValueError( - "Observable's qubit count and the number of ASCII symbols must be equal" - ) + elif self._observable.qubit_count != len(self._target): + raise ValueError( + f"Observable's qubit count {self._observable.qubit_count} and " + f"the size of the target qubit set {self._target} must be equal" + ) + elif self._observable.qubit_count != len(self.ascii_symbols): + raise ValueError( + "Observable's qubit count and the number of ASCII symbols must be equal" + ) @property def observable(self) -> Observable: @@ -250,12 +248,13 @@ def target(self) -> QubitSet: @target.setter def target(self, target: QubitSetInput) -> None: """Sets the target. + Args: target (QubitSetInput): The new target. """ self._target = QubitSet(target) - def __eq__(self, other) -> bool: + def __eq__(self, other: ObservableResultType) -> bool: if isinstance(other, ObservableResultType): return ( self.name == other.name @@ -275,8 +274,7 @@ def __hash__(self) -> int: class ObservableParameterResultType(ObservableResultType): - """ - Result types with observables, targets and parameters. + """Result types with observables, targets and parameters. If no targets are specified, the observable must only operate on 1 qubit and it will be applied to all qubits in parallel. Otherwise, the number of specified targets must be equivalent to the number of qubits the observable can be applied to. diff --git a/src/braket/circuits/result_types.py b/src/braket/circuits/result_types.py index 0a1a1c630..0b73c5e7b 100644 --- a/src/braket/circuits/result_types.py +++ b/src/braket/circuits/result_types.py @@ -41,8 +41,7 @@ class StateVector(ResultType): - """ - The full state vector as a requested result type. + """The full state vector as a requested result type. This is available on simulators only when `shots=0`. """ @@ -68,7 +67,7 @@ def state_vector() -> ResultType: """ return ResultType.StateVector() - def __eq__(self, other) -> bool: + def __eq__(self, other: StateVector) -> bool: if isinstance(other, StateVector): return True return False @@ -86,13 +85,13 @@ def __hash__(self) -> int: class DensityMatrix(ResultType): - """ - The full density matrix as a requested result type. + """The full density matrix as a requested result type. This is available on simulators only when `shots=0`. """ def __init__(self, target: QubitSetInput | None = None): - """ + """Inits a `DensityMatrix`. + Args: target (QubitSetInput | None): The target qubits of the reduced density matrix. Default is `None`, and the @@ -112,6 +111,7 @@ def target(self) -> QubitSet: @target.setter def target(self, target: QubitSetInput) -> None: """Sets the target qubit set. + Args: target (QubitSetInput): The target qubit set. """ @@ -136,6 +136,7 @@ def _to_openqasm(self, serialization_properties: OpenQASMSerializationProperties @circuit.subroutine(register=True) def density_matrix(target: QubitSetInput | None = None) -> ResultType: """Registers this function into the circuit class. + Args: target (QubitSetInput | None): The target qubits of the reduced density matrix. Default is `None`, and the @@ -149,7 +150,7 @@ def density_matrix(target: QubitSetInput | None = None) -> ResultType: """ return ResultType.DensityMatrix(target=target) - def __eq__(self, other) -> bool: + def __eq__(self, other: DensityMatrix) -> bool: if isinstance(other, DensityMatrix): return self.target == other.target return False @@ -170,8 +171,7 @@ def __hash__(self) -> int: class AdjointGradient(ObservableParameterResultType): - """ - The gradient of the expectation value of the provided observable, applied to target, + """The gradient of the expectation value of the provided observable, applied to target, with respect to the given parameter. """ @@ -181,7 +181,8 @@ def __init__( target: list[QubitSetInput] | None = None, parameters: list[Union[str, FreeParameter]] | None = None, ): - """ + """Inits an `AdjointGradient`. + Args: observable (Observable): The expectation value of this observable is the function against which parameters in the gradient are differentiated. @@ -197,6 +198,7 @@ def __init__( ValueError: If the observable's qubit count does not equal the number of target qubits, or if `target=None` and the observable's qubit count is not 1. + Examples: >>> ResultType.AdjointGradient(observable=Observable.Z(), target=0, parameters=["alpha", "beta"]) @@ -209,7 +211,6 @@ def __init__( >>> parameters=["alpha", "beta"], >>> ) """ - if isinstance(observable, Sum): target_qubits = reduce(QubitSet.union, map(QubitSet, target), QubitSet()) else: @@ -274,13 +275,13 @@ def adjoint_gradient( class Amplitude(ResultType): - """ - The amplitude of the specified quantum states as a requested result type. + """The amplitude of the specified quantum states as a requested result type. This is available on simulators only when `shots=0`. """ def __init__(self, state: list[str]): - """ + """Initializes an `Amplitude`. + Args: state (list[str]): list of quantum states as strings with "0" and "1" @@ -332,7 +333,7 @@ def amplitude(state: list[str]) -> ResultType: """ return ResultType.Amplitude(state=state) - def __eq__(self, other): + def __eq__(self, other: Amplitude): if isinstance(other, Amplitude): return self.state == other.state return False @@ -362,7 +363,8 @@ class Probability(ResultType): """ def __init__(self, target: QubitSetInput | None = None): - """ + """Inits a `Probability`. + Args: target (QubitSetInput | None): The target qubits that the result type is requested for. Default is `None`, which means all qubits for the @@ -382,6 +384,7 @@ def target(self) -> QubitSet: @target.setter def target(self, target: QubitSetInput) -> None: """Sets the target qubit set. + Args: target (QubitSetInput): The target qubit set. """ @@ -420,7 +423,7 @@ def probability(target: QubitSetInput | None = None) -> ResultType: """ return ResultType.Probability(target=target) - def __eq__(self, other) -> bool: + def __eq__(self, other: Probability) -> bool: if isinstance(other, Probability): return self.target == other.target return False @@ -452,16 +455,14 @@ class Expectation(ObservableResultType): """ def __init__(self, observable: Observable, target: QubitSetInput | None = None): - """ + """Inits an `Expectation`. + Args: observable (Observable): the observable for the result type target (QubitSetInput | None): Target qubits that the result type is requested for. Default is `None`, which means the observable must operate only on 1 qubit and it is applied to all qubits in parallel. - Raises: - ValueError: If the observable's qubit count does not equal the number of target - qubits, or if `target=None` and the observable's qubit count is not 1. Examples: >>> ResultType.Expectation(observable=Observable.Z(), target=0) @@ -527,17 +528,14 @@ class Sample(ObservableResultType): """ def __init__(self, observable: Observable, target: QubitSetInput | None = None): - """ + """Inits a `Sample`. + Args: observable (Observable): the observable for the result type target (QubitSetInput | None): Target qubits that the result type is requested for. Default is `None`, which means the observable must operate only on 1 qubit and it is applied to all qubits in parallel. - Raises: - ValueError: If the observable's qubit count is not equal to the number of target - qubits, or if `target=None` and the observable's qubit count is not 1. - Examples: >>> ResultType.Sample(observable=Observable.Z(), target=0) @@ -603,7 +601,8 @@ class Variance(ObservableResultType): """ def __init__(self, observable: Observable, target: QubitSetInput | None = None): - """ + """Inits a `Variance`. + Args: observable (Observable): the observable for the result type target (QubitSetInput | None): Target qubits that the diff --git a/src/braket/circuits/serialization.py b/src/braket/circuits/serialization.py index 1e0826e80..afcb5d118 100644 --- a/src/braket/circuits/serialization.py +++ b/src/braket/circuits/serialization.py @@ -23,8 +23,7 @@ class IRType(str, Enum): class QubitReferenceType(str, Enum): - """ - Defines how qubits should be referenced in the generated OpenQASM string. + """Defines how qubits should be referenced in the generated OpenQASM string. See https://qiskit.github.io/openqasm/language/types.html#quantum-types for details. """ @@ -35,8 +34,7 @@ class QubitReferenceType(str, Enum): @dataclass class OpenQASMSerializationProperties: - """ - Properties for serializing a circuit to OpenQASM. + """Properties for serializing a circuit to OpenQASM. qubit_reference_type (QubitReferenceType): determines whether to use logical qubits or physical qubits (q[i] vs $i). @@ -46,6 +44,7 @@ class OpenQASMSerializationProperties: def format_target(self, target: int) -> str: """Format a target qubit to the appropriate OpenQASM representation. + Args: target (int): The target qubit. diff --git a/src/braket/circuits/translations.py b/src/braket/circuits/translations.py index 74dae1bbd..9537460ef 100644 --- a/src/braket/circuits/translations.py +++ b/src/braket/circuits/translations.py @@ -15,10 +15,9 @@ from typing import Union import braket.circuits.gates as braket_gates -import braket.circuits.noises as noises -import braket.circuits.result_types as ResultTypes +import braket.circuits.result_types as ResultTypes # noqa: N812 import braket.ir.jaqcd.shared_models as models -from braket.circuits import Observable, observables +from braket.circuits import Observable, noises, observables from braket.ir.jaqcd import ( Amplitude, DensityMatrix, @@ -99,6 +98,14 @@ def get_observable(obs: Union[models.Observable, list]) -> Observable: + """Gets the observable. + + Args: + obs (Union[Observable, list]): The observable(s) to get translated. + + Returns: + Observable: The translated observable. + """ return _get_observable(obs) @@ -140,39 +147,39 @@ def braket_result_to_result_type(result: Results) -> None: @_braket_result_to_result_type.register(Amplitude) -def _(result): +def _(result: Results) -> Amplitude: return ResultTypes.Amplitude(state=result.states) @_braket_result_to_result_type.register(Expectation) -def _(result): +def _(result: Results) -> Expectation: tensor_product = get_tensor_product(result.observable) return ResultTypes.Expectation(observable=tensor_product, target=result.targets) @_braket_result_to_result_type.register(Probability) -def _(result): +def _(result: Results) -> Probability: return ResultTypes.Probability(result.targets) @_braket_result_to_result_type.register(Sample) -def _(result): +def _(result: Results) -> Sample: tensor_product = get_tensor_product(result.observable) return ResultTypes.Sample(observable=tensor_product, target=result.targets) @_braket_result_to_result_type.register(StateVector) -def _(result): +def _(result: Results) -> StateVector: return ResultTypes.StateVector() @_braket_result_to_result_type.register(DensityMatrix) -def _(result): +def _(result: Results): return ResultTypes.DensityMatrix(target=result.targets) @_braket_result_to_result_type.register(Variance) -def _(result): +def _(result: Results): tensor_product = get_tensor_product(result.observable) return ResultTypes.Variance(observable=tensor_product, target=result.targets) diff --git a/src/braket/circuits/unitary_calculation.py b/src/braket/circuits/unitary_calculation.py index ebc3c7878..9fa404284 100644 --- a/src/braket/circuits/unitary_calculation.py +++ b/src/braket/circuits/unitary_calculation.py @@ -26,8 +26,7 @@ def calculate_unitary_big_endian( instructions: Iterable[Instruction], qubits: QubitSet ) -> np.ndarray: - """ - Returns the unitary matrix representation for all the `instructions` on qubits `qubits`. + """Returns the unitary matrix representation for all the `instruction`s on qubits `qubits`. Note: The performance of this method degrades with qubit count. It might be slow for diff --git a/src/braket/devices/device.py b/src/braket/devices/device.py index d61f90162..3f2a28e41 100644 --- a/src/braket/devices/device.py +++ b/src/braket/devices/device.py @@ -13,7 +13,7 @@ import warnings from abc import ABC, abstractmethod -from typing import Optional, Union +from typing import Any, Optional, Union from braket.ahs.analog_hamiltonian_simulation import AnalogHamiltonianSimulation from braket.annealing.problem import Problem @@ -30,7 +30,8 @@ class Device(ABC): """An abstraction over quantum devices that includes quantum computers and simulators.""" def __init__(self, name: str, status: str): - """ + """Initializes a `Device`. + Args: name (str): Name of quantum device status (str): Status of quantum device @@ -58,6 +59,8 @@ def run( inputs (Optional[dict[str, float]]): Inputs to be passed along with the IR. If IR is an OpenQASM Program, the inputs will be updated with this value. Not all devices and IR formats support inputs. Default: {}. + *args (Any): Arbitrary arguments. + **kwargs (Any): Arbitrary keyword arguments. Returns: QuantumTask: The QuantumTask tracking task execution on this device @@ -73,8 +76,8 @@ def run_batch( shots: Optional[int], max_parallel: Optional[int], inputs: Optional[Union[dict[str, float], list[dict[str, float]]]], - *args, - **kwargs, + *args: Any, + **kwargs: Any, ) -> QuantumTaskBatch: """Executes a batch of quantum tasks in parallel @@ -88,6 +91,8 @@ def run_batch( inputs (Optional[Union[dict[str, float], list[dict[str, float]]]]): Inputs to be passed along with the IR. If the IR supports inputs, the inputs will be updated with this value. + *args (Any): Arbitrary arguments. + **kwargs (Any): Arbitrary keyword arguments. Returns: QuantumTaskBatch: A batch containing all of the qauntum tasks run diff --git a/src/braket/devices/local_simulator.py b/src/braket/devices/local_simulator.py index 3140e8534..faee13fdf 100644 --- a/src/braket/devices/local_simulator.py +++ b/src/braket/devices/local_simulator.py @@ -17,7 +17,7 @@ from itertools import repeat from multiprocessing import Pool from os import cpu_count -from typing import Optional, Union +from typing import Any, Optional, Union import pkg_resources @@ -56,7 +56,8 @@ def __init__( backend: Union[str, BraketSimulator] = "default", noise_model: Optional[NoiseModel] = None, ): - """ + """Initializes a `LocalSimulator`. + Args: backend (Union[str, BraketSimulator]): The name of the simulator backend or the actual simulator instance to use for simulation. Defaults to the @@ -80,8 +81,8 @@ def run( task_specification: Union[Circuit, Problem, Program, AnalogHamiltonianSimulation], shots: int = 0, inputs: Optional[dict[str, float]] = None, - *args, - **kwargs, + *args: Any, + **kwargs: Any, ) -> LocalQuantumTask: """Runs the given task with the wrapped local simulator. @@ -95,6 +96,8 @@ def run( inputs (Optional[dict[str, float]]): Inputs to be passed along with the IR. If the IR supports inputs, the inputs will be updated with this value. Default: {}. + *args (Any): Arbitrary arguments. + **kwargs(Any): Arbitrary keyword arguments. Returns: LocalQuantumTask: A LocalQuantumTask object containing the results @@ -129,7 +132,7 @@ def run_batch( # noqa: C901 """Executes a batch of quantum tasks in parallel Args: - task_specifications (Union[Union[Circuit, Problem, Program, AnalogHamiltonianSimulation], list[Union[Circuit, Problem, Program, AnalogHamiltonianSimulation]]]): # noqa + task_specifications (Union[Union[Circuit, Problem, Program, AnalogHamiltonianSimulation], list[Union[Circuit, Problem, Program, AnalogHamiltonianSimulation]]]): Single instance or list of quantum task specification. shots (Optional[int]): The number of times to run the quantum task. Default: 0. @@ -144,7 +147,7 @@ def run_batch( # noqa: C901 See Also: `braket.tasks.local_quantum_task_batch.LocalQuantumTaskBatch` - """ + """ # noqa E501 inputs = inputs or {} if self._noise_model: @@ -165,9 +168,7 @@ def run_batch( # noqa: C901 if not single_task and not single_input: if len(task_specifications) != len(inputs): - raise ValueError( - "Multiple inputs and task specifications must " "be equal in number." - ) + raise ValueError("Multiple inputs and task specifications must be equal in number.") if single_task: task_specifications = repeat(task_specifications) @@ -203,7 +204,8 @@ def properties(self) -> DeviceCapabilities: Please see `braket.device_schema` in amazon-braket-schemas-python_ - .. _amazon-braket-schemas-python: https://github.com/aws/amazon-braket-schemas-python""" + .. _amazon-braket-schemas-python: https://github.com/aws/amazon-braket-schemas-python + """ return self._delegate.properties @staticmethod diff --git a/src/braket/error_mitigation/debias.py b/src/braket/error_mitigation/debias.py index 305bf7b78..8beddc7ef 100644 --- a/src/braket/error_mitigation/debias.py +++ b/src/braket/error_mitigation/debias.py @@ -16,9 +16,7 @@ class Debias(ErrorMitigation): - """ - The debias error mitigation scheme. This scheme takes no parameters. - """ + """The debias error mitigation scheme. This scheme takes no parameters.""" def serialize(self) -> list[error_mitigation.Debias]: return [error_mitigation.Debias()] diff --git a/src/braket/error_mitigation/error_mitigation.py b/src/braket/error_mitigation/error_mitigation.py index 79b1f3e30..95e6b6582 100644 --- a/src/braket/error_mitigation/error_mitigation.py +++ b/src/braket/error_mitigation/error_mitigation.py @@ -16,9 +16,14 @@ class ErrorMitigation: def serialize(self) -> list[error_mitigation.ErrorMitigationScheme]: - """ + """This returns a list of service-readable error mitigation + scheme descriptions. + Returns: list[ErrorMitigationScheme]: A list of service-readable error mitigation scheme descriptions. + + Raises: + NotImplementedError: Not implemented in the base class. """ raise NotImplementedError("serialize is not implemented.") diff --git a/src/braket/ipython_utils.py b/src/braket/ipython_utils.py index 20100d944..c443d1b44 100644 --- a/src/braket/ipython_utils.py +++ b/src/braket/ipython_utils.py @@ -15,8 +15,7 @@ def running_in_jupyter() -> bool: - """ - Determine if running within Jupyter. + """Determine if running within Jupyter. Inspired by https://github.com/ipython/ipython/issues/11694 diff --git a/src/braket/jobs/config.py b/src/braket/jobs/config.py index a598388e4..7c84b42dd 100644 --- a/src/braket/jobs/config.py +++ b/src/braket/jobs/config.py @@ -54,8 +54,8 @@ class DeviceConfig: class S3DataSourceConfig: - """ - Data source for data that lives on S3 + """Data source for data that lives on S3. + Attributes: config (dict[str, dict]): config passed to the Braket API """ diff --git a/src/braket/jobs/data_persistence.py b/src/braket/jobs/data_persistence.py index f2ec9b6fa..0386ed7a7 100644 --- a/src/braket/jobs/data_persistence.py +++ b/src/braket/jobs/data_persistence.py @@ -26,9 +26,8 @@ def save_job_checkpoint( checkpoint_file_suffix: str = "", data_format: PersistedJobDataFormat = PersistedJobDataFormat.PLAINTEXT, ) -> None: - """ - Saves the specified `checkpoint_data` to the local output directory, specified by the container - environment variable `CHECKPOINT_DIR`, with the filename + """Saves the specified `checkpoint_data` to the local output directory, specified by + the container environment variable `CHECKPOINT_DIR`, with the filename `f"{job_name}(_{checkpoint_file_suffix}).json"`. The `job_name` refers to the name of the current job and is retrieved from the container environment variable `JOB_NAME`. The `checkpoint_data` values are serialized to the specified `data_format`. @@ -68,8 +67,7 @@ def save_job_checkpoint( def load_job_checkpoint( job_name: str | None = None, checkpoint_file_suffix: str = "" ) -> dict[str, Any]: - """ - Loads the job checkpoint data stored for the job named 'job_name', with the checkpoint + """Loads the job checkpoint data stored for the job named 'job_name', with the checkpoint file that ends with the `checkpoint_file_suffix`. The `job_name` can refer to any job whose checkpoint data you expect to be available in the file path specified by the `CHECKPOINT_DIR` container environment variable. If not provided, this function will use the currently running @@ -104,7 +102,7 @@ def load_job_checkpoint( if checkpoint_file_suffix else f"{checkpoint_directory}/{job_name}.json" ) - with open(checkpoint_file_path, "r") as f: + with open(checkpoint_file_path) as f: persisted_data = PersistedJobData.parse_raw(f.read()) deserialized_data = deserialize_values( persisted_data.dataDictionary, persisted_data.dataFormat @@ -115,7 +113,7 @@ def load_job_checkpoint( def _load_persisted_data(filename: str | Path | None = None) -> PersistedJobData: filename = filename or Path(get_results_dir()) / "results.json" try: - with open(filename, mode="r") as f: + with open(filename) as f: return PersistedJobData.parse_raw(f.read()) except FileNotFoundError: return PersistedJobData( @@ -125,8 +123,7 @@ def _load_persisted_data(filename: str | Path | None = None) -> PersistedJobData def load_job_result(filename: str | Path | None = None) -> dict[str, Any]: - """ - Loads job result of currently running job. + """Loads job result of currently running job. Args: filename (str | Path | None): Location of job results. Default `results.json` in job @@ -145,8 +142,7 @@ def save_job_result( result_data: dict[str, Any] | Any, data_format: PersistedJobDataFormat | None = None, ) -> None: - """ - Saves the `result_data` to the local output directory that is specified by the container + """Saves the `result_data` to the local output directory that is specified by the container environment variable `AMZN_BRAKET_JOB_RESULTS_DIR`, with the filename 'results.json'. The `result_data` values are serialized to the specified `data_format`. @@ -160,6 +156,9 @@ def save_job_result( data_format (PersistedJobDataFormat | None): The data format used to serialize the values. Note that for `PICKLED` data formats, the values are base64 encoded after serialization. Default: PersistedJobDataFormat.PLAINTEXT. + + Raises: + TypeError: Unsupported data format. """ if not isinstance(result_data, dict): result_data = {"result": result_data} diff --git a/src/braket/jobs/environment_variables.py b/src/braket/jobs/environment_variables.py index 4fba9315c..ad42006de 100644 --- a/src/braket/jobs/environment_variables.py +++ b/src/braket/jobs/environment_variables.py @@ -16,8 +16,7 @@ def get_job_name() -> str: - """ - Get the name of the current job. + """Get the name of the current job. Returns: str: The name of the job if in a job, else an empty string. @@ -26,8 +25,7 @@ def get_job_name() -> str: def get_job_device_arn() -> str: - """ - Get the device ARN of the current job. If not in a job, default to "local:none/none". + """Get the device ARN of the current job. If not in a job, default to "local:none/none". Returns: str: The device ARN of the current job or "local:none/none". @@ -36,8 +34,7 @@ def get_job_device_arn() -> str: def get_input_data_dir(channel: str = "input") -> str: - """ - Get the job input data directory. + """Get the job input data directory. Args: channel (str): The name of the input channel. Default value @@ -53,8 +50,7 @@ def get_input_data_dir(channel: str = "input") -> str: def get_results_dir() -> str: - """ - Get the job result directory. + """Get the job result directory. Returns: str: The results directory, defaulting to current working directory. @@ -63,8 +59,7 @@ def get_results_dir() -> str: def get_checkpoint_dir() -> str: - """ - Get the job checkpoint directory. + """Get the job checkpoint directory. Returns: str: The checkpoint directory, defaulting to current working directory. @@ -73,13 +68,12 @@ def get_checkpoint_dir() -> str: def get_hyperparameters() -> dict[str, str]: - """ - Get the job hyperparameters as a dict, with the values stringified. + """Get the job hyperparameters as a dict, with the values stringified. Returns: dict[str, str]: The hyperparameters of the job. """ if "AMZN_BRAKET_HP_FILE" in os.environ: - with open(os.getenv("AMZN_BRAKET_HP_FILE"), "r") as f: + with open(os.getenv("AMZN_BRAKET_HP_FILE")) as f: return json.load(f) return {} diff --git a/src/braket/jobs/hybrid_job.py b/src/braket/jobs/hybrid_job.py index b8e1e58bf..3cd622e37 100644 --- a/src/braket/jobs/hybrid_job.py +++ b/src/braket/jobs/hybrid_job.py @@ -168,9 +168,13 @@ def hybrid_job( def _hybrid_job(entry_point: Callable) -> Callable: @functools.wraps(entry_point) - def job_wrapper(*args, **kwargs) -> Callable: - """ - The job wrapper. + def job_wrapper(*args: Any, **kwargs: Any) -> Callable: + """The job wrapper. + + Args: + *args (Any): Arbitrary arguments. + **kwargs (Any): Arbitrary keyword arguments. + Returns: Callable: the callable for creating a Hybrid Job. """ @@ -322,7 +326,8 @@ def _log_hyperparameters(entry_point: Callable, args: tuple, kwargs: dict) -> di hyperparameters.update(**value) else: warnings.warn( - "Positional only arguments will not be logged to the hyperparameters file." + "Positional only arguments will not be logged to the hyperparameters file.", + stacklevel=1, ) return {name: _sanitize(value) for name, value in hyperparameters.items()} @@ -351,8 +356,7 @@ def _sanitize(hyperparameter: Any) -> str: def _process_input_data(input_data: dict) -> list[str]: - """ - Create symlinks to data + """Create symlinks to data. Logic chart for how the service moves files into the data directory on the instance: input data matches exactly one file: cwd/filename -> channel/filename diff --git a/src/braket/jobs/image_uris.py b/src/braket/jobs/image_uris.py index 3a3346abe..af6c5012a 100644 --- a/src/braket/jobs/image_uris.py +++ b/src/braket/jobs/image_uris.py @@ -15,7 +15,6 @@ import os from enum import Enum from functools import cache -from typing import Dict, Set class Framework(str, Enum): @@ -26,7 +25,15 @@ class Framework(str, Enum): PL_PYTORCH = "PL_PYTORCH" -def built_in_images(region: str) -> Set[str]: +def built_in_images(region: str) -> set[str]: + """Checks a region for built in Braket images. + + Args: + region (str): The AWS region to check for images + + Returns: + set[str]: returns a set of built images + """ return {retrieve_image(framework, region) for framework in Framework} @@ -53,25 +60,25 @@ def retrieve_image(framework: Framework, region: str) -> str: return f"{registry}.dkr.ecr.{region}.amazonaws.com/{tag}" -def _config_for_framework(framework: Framework) -> Dict[str, str]: +def _config_for_framework(framework: Framework) -> dict[str, str]: """Loads the JSON config for the given framework. Args: framework (Framework): The framework whose config needs to be loaded. Returns: - Dict[str, str]: Dict that contains the configuration for the specified framework. + dict[str, str]: Dict that contains the configuration for the specified framework. """ fname = os.path.join(os.path.dirname(__file__), "image_uri_config", f"{framework.lower()}.json") with open(fname) as f: return json.load(f) -def _registry_for_region(config: Dict[str, str], region: str) -> str: +def _registry_for_region(config: dict[str, str], region: str) -> str: """Retrieves the registry for the specified region from the configuration. Args: - config (Dict[str, str]): Dict containing the framework configuration. + config (dict[str, str]): Dict containing the framework configuration. region (str): str that specifies the region for which the registry is retrieved. Returns: diff --git a/src/braket/jobs/local/local_job.py b/src/braket/jobs/local/local_job.py index f516d9693..af6806157 100644 --- a/src/braket/jobs/local/local_job.py +++ b/src/braket/jobs/local/local_job.py @@ -117,6 +117,9 @@ def create( container image. Optional. Default: True. + Raises: + ValueError: Local directory with the job name already exists. + Returns: LocalQuantumJob: The representation of a local Braket Hybrid Job. """ @@ -166,11 +169,15 @@ def create( return LocalQuantumJob(f"local:job/{job_name}", run_log) def __init__(self, arn: str, run_log: str | None = None): - """ + """Initializes a `LocalQuantumJob`. + Args: arn (str): The ARN of the hybrid job. - run_log (str | None): The container output log of running the hybrid job with the - given arn. + run_log (str | None): The container output log of running the hybrid job with the given + arn. + + Raises: + ValueError: Local job is not found. """ if not arn.startswith("local:job/"): raise ValueError(f"Arn {arn} is not a valid local job arn") @@ -194,12 +201,15 @@ def name(self) -> str: def run_log(self) -> str: """Gets the run output log from running the hybrid job. + Raises: + ValueError: The log file is not found. + Returns: str: The container output log from running the hybrid job. """ if not self._run_log: try: - with open(os.path.join(self.name, "log.txt"), "r") as log_file: + with open(os.path.join(self.name, "log.txt")) as log_file: self._run_log = log_file.read() except FileNotFoundError: raise ValueError(f"Unable to find logs in the local job directory {self.name}.") @@ -207,11 +217,13 @@ def run_log(self) -> str: def state(self, use_cached_value: bool = False) -> str: """The state of the hybrid job. + Args: use_cached_value (bool): If `True`, uses the value most recently retrieved value from the Amazon Braket `GetJob` operation. If `False`, calls the `GetJob` operation to retrieve metadata, which also updates the cached value. Default = `False`. + Returns: str: Returns "COMPLETED". """ @@ -219,11 +231,13 @@ def state(self, use_cached_value: bool = False) -> str: def metadata(self, use_cached_value: bool = False) -> dict[str, Any]: """When running the hybrid job in local mode, the metadata is not available. + Args: use_cached_value (bool): If `True`, uses the value most recently retrieved from the Amazon Braket `GetJob` operation, if it exists; if does not exist, `GetJob` is called to retrieve the metadata. If `False`, always calls `GetJob`, which also updates the cached value. Default: `False`. + Returns: dict[str, Any]: None """ @@ -231,6 +245,7 @@ def metadata(self, use_cached_value: bool = False) -> dict[str, Any]: def cancel(self) -> str: """When running the hybrid job in local mode, the cancelling a running is not possible. + Returns: str: None """ @@ -260,7 +275,7 @@ def result( poll_timeout_seconds: float = QuantumJob.DEFAULT_RESULTS_POLL_TIMEOUT, poll_interval_seconds: float = QuantumJob.DEFAULT_RESULTS_POLL_INTERVAL, ) -> dict[str, Any]: - """Retrieves the hybrid job result persisted using save_job_result() function. + """Retrieves the `LocalQuantumJob` result persisted using `save_job_result` function. Args: poll_timeout_seconds (float): The polling timeout, in seconds, for `result()`. @@ -268,11 +283,14 @@ def result( poll_interval_seconds (float): The polling interval, in seconds, for `result()`. Default: 5 seconds. + Raises: + ValueError: The local job directory does not exist. + Returns: dict[str, Any]: Dict specifying the hybrid job results. """ try: - with open(os.path.join(self.name, "results.json"), "r") as f: + with open(os.path.join(self.name, "results.json")) as f: persisted_data = PersistedJobData.parse_raw(f.read()) deserialized_data = deserialize_values( persisted_data.dataDictionary, persisted_data.dataFormat diff --git a/src/braket/jobs/local/local_job_container.py b/src/braket/jobs/local/local_job_container.py index ea5625623..c4432dcf7 100644 --- a/src/braket/jobs/local/local_job_container.py +++ b/src/braket/jobs/local/local_job_container.py @@ -17,12 +17,11 @@ import subprocess from logging import Logger, getLogger from pathlib import PurePosixPath -from typing import Dict, List from braket.aws.aws_session import AwsSession -class _LocalJobContainer(object): +class _LocalJobContainer: """Uses docker CLI to run Braket Hybrid Jobs on a local docker container.""" ECR_URI_PATTERN = r"^((\d+)\.dkr\.ecr\.([^.]+)\.[^/]*)/([^:]*):(.*)$" @@ -39,6 +38,7 @@ def __init__( container. The function "end_session" must be called when the container is no longer needed. + Args: image_uri (str): The URI of the container image to run. aws_session (AwsSession | None): AwsSession for connecting to AWS Services. @@ -65,16 +65,17 @@ def __exit__(self, exc_type, exc_val, exc_tb): self._end_session() @staticmethod - def _envs_to_list(environment_variables: Dict[str, str]) -> List[str]: + def _envs_to_list(environment_variables: dict[str, str]) -> list[str]: """Converts a dictionary environment variables to a list of parameters that can be passed to the container exec/run commands to ensure those env variables are available in the container. Args: - environment_variables (Dict[str, str]): A dictionary of environment variables and + environment_variables (dict[str, str]): A dictionary of environment variables and their values. + Returns: - List[str]: The list of parameters to use when running a hybrid job that will include the + list[str]: The list of parameters to use when running a hybrid job that will include the provided environment variables as part of the runtime. """ env_list = [] @@ -84,12 +85,12 @@ def _envs_to_list(environment_variables: Dict[str, str]) -> List[str]: return env_list @staticmethod - def _check_output_formatted(command: List[str]) -> str: + def _check_output_formatted(command: list[str]) -> str: """This is a wrapper around the subprocess.check_output command that decodes the output to UTF-8 encoding. Args: - command(List[str]): The command to run. + command(list[str]): The command to run. Returns: str: The UTF-8 encoded output of running the command. @@ -103,6 +104,9 @@ def _login_to_ecr(self, account_id: str, ecr_url: str) -> None: Args: account_id(str): The customer account ID. ecr_url(str): The URL of the ECR repo to log into. + + Raises: + ValueError: Invalid permissions to pull container. """ ecr_client = self._aws_session.ecr_client authorization_data_result = ecr_client.get_authorization_token(registryIds=[account_id]) @@ -121,6 +125,9 @@ def _pull_image(self, image_uri: str) -> None: Args: image_uri(str): The URI of the ECR image to pull. + + Raises: + ValueError: Invalid ECR URL. """ ecr_pattern = re.compile(self.ECR_URI_PATTERN) ecr_pattern_match = ecr_pattern.match(image_uri) @@ -145,6 +152,9 @@ def _start_container(self, image_uri: str, force_update: bool) -> str: image_uri(str): The URI of the ECR image to run. force_update(bool): Do a docker pull, even if the image is local, in order to update. + Raises: + ValueError: Invalid local image URI. + Returns: str: The name of the running container, which can be used to execute further commands. """ @@ -230,13 +240,16 @@ def copy_from(self, source: str, destination: str) -> None: def run_local_job( self, - environment_variables: Dict[str, str], + environment_variables: dict[str, str], ) -> None: """Runs a Braket Hybrid job in a local container. Args: - environment_variables (Dict[str, str]): The environment variables to make available + environment_variables (dict[str, str]): The environment variables to make available as part of running the hybrid job. + + Raises: + ValueError: `start_program_name` is not found. """ start_program_name = self._check_output_formatted( ["docker", "exec", self._container_name, "printenv", "SAGEMAKER_PROGRAM"] diff --git a/src/braket/jobs/local/local_job_container_setup.py b/src/braket/jobs/local/local_job_container_setup.py index 7505dcbf5..57c1f3653 100644 --- a/src/braket/jobs/local/local_job_container_setup.py +++ b/src/braket/jobs/local/local_job_container_setup.py @@ -13,17 +13,18 @@ import json import tempfile +from collections.abc import Iterable from logging import Logger, getLogger from pathlib import Path -from typing import Any, Dict, Iterable +from typing import Any from braket.aws.aws_session import AwsSession from braket.jobs.local.local_job_container import _LocalJobContainer def setup_container( - container: _LocalJobContainer, aws_session: AwsSession, **creation_kwargs -) -> Dict[str, str]: + container: _LocalJobContainer, aws_session: AwsSession, **creation_kwargs: str +) -> dict[str, str]: """Sets up a container with prerequisites for running a Braket Hybrid Job. The prerequisites are based on the options the customer has chosen for the hybrid job. Similarly, any environment variables that are needed during runtime will be returned by this function. @@ -31,9 +32,10 @@ def setup_container( Args: container(_LocalJobContainer): The container that will run the braket hybrid job. aws_session (AwsSession): AwsSession for connecting to AWS Services. + **creation_kwargs (str): Arbitrary keyword arguments. Returns: - Dict[str, str]: A dictionary of environment variables that reflect Braket Hybrid Jobs + dict[str, str]: A dictionary of environment variables that reflect Braket Hybrid Jobs options requested by the customer. """ logger = getLogger(__name__) @@ -51,17 +53,18 @@ def setup_container( return run_environment_variables -def _create_expected_paths(container: _LocalJobContainer, **creation_kwargs) -> None: +def _create_expected_paths(container: _LocalJobContainer, **creation_kwargs: str) -> None: """Creates the basic paths required for Braket Hybrid Jobs to run. Args: container(_LocalJobContainer): The container that will run the braket hybrid job. + **creation_kwargs (str): Arbitrary keyword arguments. """ container.makedir("/opt/ml/model") container.makedir(creation_kwargs["checkpointConfig"]["localPath"]) -def _get_env_credentials(aws_session: AwsSession, logger: Logger) -> Dict[str, str]: +def _get_env_credentials(aws_session: AwsSession, logger: Logger) -> dict[str, str]: """Gets the account credentials from boto so they can be added as environment variables to the running container. @@ -70,7 +73,7 @@ def _get_env_credentials(aws_session: AwsSession, logger: Logger) -> Dict[str, s logger (Logger): Logger object with which to write logs. Default is `getLogger(__name__)` Returns: - Dict[str, str]: The set of key/value pairs that should be added as environment variables + dict[str, str]: The set of key/value pairs that should be added as environment variables to the running container. """ credentials = aws_session.boto_session.get_credentials() @@ -90,15 +93,15 @@ def _get_env_credentials(aws_session: AwsSession, logger: Logger) -> Dict[str, s } -def _get_env_script_mode_config(script_mode_config: Dict[str, str]) -> Dict[str, str]: +def _get_env_script_mode_config(script_mode_config: dict[str, str]) -> dict[str, str]: """Gets the environment variables related to the customer script mode config. Args: - script_mode_config (Dict[str, str]): The values for scriptModeConfig in the boto3 input + script_mode_config (dict[str, str]): The values for scriptModeConfig in the boto3 input parameters for running a Braket Hybrid Job. Returns: - Dict[str, str]: The set of key/value pairs that should be added as environment variables + dict[str, str]: The set of key/value pairs that should be added as environment variables to the running container. """ result = { @@ -110,15 +113,16 @@ def _get_env_script_mode_config(script_mode_config: Dict[str, str]) -> Dict[str, return result -def _get_env_default_vars(aws_session: AwsSession, **creation_kwargs) -> Dict[str, str]: +def _get_env_default_vars(aws_session: AwsSession, **creation_kwargs: str) -> dict[str, str]: """This function gets the remaining 'simple' env variables, that don't require any additional logic to determine what they are or when they should be added as env variables. Args: aws_session (AwsSession): AwsSession for connecting to AWS Services. + **creation_kwargs (str): Arbitrary keyword arguments. Returns: - Dict[str, str]: The set of key/value pairs that should be added as environment variables + dict[str, str]: The set of key/value pairs that should be added as environment variables to the running container. """ job_name = creation_kwargs["jobName"] @@ -135,12 +139,12 @@ def _get_env_default_vars(aws_session: AwsSession, **creation_kwargs) -> Dict[st } -def _get_env_hyperparameters() -> Dict[str, str]: +def _get_env_hyperparameters() -> dict[str, str]: """Gets the env variable for hyperparameters. This should only be added if the customer has provided hyperpameters to the hybrid job. Returns: - Dict[str, str]: The set of key/value pairs that should be added as environment variables + dict[str, str]: The set of key/value pairs that should be added as environment variables to the running container. """ return { @@ -148,12 +152,12 @@ def _get_env_hyperparameters() -> Dict[str, str]: } -def _get_env_input_data() -> Dict[str, str]: +def _get_env_input_data() -> dict[str, str]: """Gets the env variable for input data. This should only be added if the customer has provided input data to the hybrid job. Returns: - Dict[str, str]: The set of key/value pairs that should be added as environment variables + dict[str, str]: The set of key/value pairs that should be added as environment variables to the running container. """ return { @@ -161,12 +165,13 @@ def _get_env_input_data() -> Dict[str, str]: } -def _copy_hyperparameters(container: _LocalJobContainer, **creation_kwargs) -> bool: +def _copy_hyperparameters(container: _LocalJobContainer, **creation_kwargs: str) -> bool: """If hyperpameters are present, this function will store them as a JSON object in the container in the appropriate location on disk. Args: container(_LocalJobContainer): The container to save hyperparameters to. + **creation_kwargs (str): Arbitrary keyword arguments. Returns: bool: True if any hyperparameters were copied to the container. @@ -185,15 +190,20 @@ def _copy_hyperparameters(container: _LocalJobContainer, **creation_kwargs) -> b def _download_input_data( aws_session: AwsSession, download_dir: str, - input_data: Dict[str, Any], + input_data: dict[str, Any], ) -> None: """Downloads input data for a hybrid job. Args: aws_session (AwsSession): AwsSession for connecting to AWS Services. download_dir (str): The directory path to download to. - input_data (Dict[str, Any]): One of the input data in the boto3 input parameters for + input_data (dict[str, Any]): One of the input data in the boto3 input parameters for running a Braket Hybrid Job. + + Raises: + ValueError: File already exists. + RuntimeError: The item is not found. + """ # If s3 prefix is the full name of a directory and all keys are inside # that directory, the contents of said directory will be copied into a @@ -243,7 +253,7 @@ def _is_dir(prefix: str, keys: Iterable[str]) -> bool: def _copy_input_data_list( - container: _LocalJobContainer, aws_session: AwsSession, **creation_kwargs + container: _LocalJobContainer, aws_session: AwsSession, **creation_kwargs: str ) -> bool: """If the input data list is not empty, this function will download the input files and store them in the container. @@ -251,6 +261,7 @@ def _copy_input_data_list( Args: container (_LocalJobContainer): The container to save input data to. aws_session (AwsSession): AwsSession for connecting to AWS Services. + **creation_kwargs (str): Arbitrary keyword arguments. Returns: bool: True if any input data was copied to the container. diff --git a/src/braket/jobs/logs.py b/src/braket/jobs/logs.py index 734d51123..5e2f12f82 100644 --- a/src/braket/jobs/logs.py +++ b/src/braket/jobs/logs.py @@ -14,30 +14,31 @@ import collections import os import sys +from collections.abc import Generator ############################################################################## # # Support for reading logs # ############################################################################## -from typing import Dict, List, Optional, Tuple +from typing import ClassVar, Optional from botocore.exceptions import ClientError from braket.aws.aws_session import AwsSession -class ColorWrap(object): +class ColorWrap: """A callable that prints text in a different color depending on the instance. Up to 5 if the standard output is a terminal or a Jupyter notebook cell. """ # For what color each number represents, see # https://misc.flogisoft.com/bash/tip_colors_and_formatting#colors - _stream_colors = [34, 35, 32, 36, 33] + _stream_colors: ClassVar = [34, 35, 32, 36, 33] - def __init__(self, force=False): - """Initialize the class. + def __init__(self, force: bool = False): + """Initialize a `ColorWrap`. Args: force (bool): If True, the render output is colorized wherever the @@ -45,7 +46,7 @@ def __init__(self, force=False): """ self.colorize = force or sys.stdout.isatty() or os.environ.get("JPY_PARENT_PID", None) - def __call__(self, index, s): + def __call__(self, index: int, s: str): """Prints the string, colorized or not, depending on the environment. Args: @@ -73,8 +74,8 @@ def _color_wrap(self, index: int, s: str) -> None: def multi_stream_iter( - aws_session: AwsSession, log_group: str, streams: List[str], positions: Dict[str, Position] -) -> Tuple[int, Dict]: + aws_session: AwsSession, log_group: str, streams: list[str], positions: dict[str, Position] +) -> Generator[tuple[int, dict]]: """Iterates over the available events coming from a set of log streams. Log streams are in a single log group interleaving the events from each stream, so they yield in timestamp order. @@ -82,13 +83,13 @@ def multi_stream_iter( Args: aws_session (AwsSession): The AwsSession for interfacing with CloudWatch. log_group (str): The name of the log group. - streams (List[str]): A list of the log stream names. The the stream number is + streams (list[str]): A list of the log stream names. The the stream number is the position of the stream in this list. - positions (Dict[str, Position]): A list of (timestamp, skip) pairs which represent + positions (dict[str, Position]): A list of (timestamp, skip) pairs which represent the last record read from each stream. Yields: - Tuple[int, Dict]: A tuple of (stream number, cloudwatch log event). + Generator[tuple[int, dict]]: A tuple of (stream number, cloudwatch log event). """ event_iters = [ log_stream(aws_session, log_group, s, positions[s].timestamp, positions[s].skip) @@ -112,7 +113,7 @@ def multi_stream_iter( def log_stream( aws_session: AwsSession, log_group: str, stream_name: str, start_time: int = 0, skip: int = 0 -) -> Dict: +) -> Generator[dict]: """A generator for log items in a single stream. This yields all the items that are available at the current moment. @@ -125,12 +126,11 @@ def log_stream( when there are multiple entries at the same timestamp.) Yields: - Dict: A CloudWatch log event with the following key-value pairs: + Generator[dict]: A CloudWatch log event with the following key-value pairs: 'timestamp' (int): The time of the event. 'message' (str): The log event data. 'ingestionTime' (int): The time the event was ingested. """ - next_token = None event_count = 1 @@ -151,16 +151,15 @@ def log_stream( else: skip = skip - event_count events = [] - for ev in events: - yield ev + yield from events def flush_log_streams( # noqa C901 aws_session: AwsSession, log_group: str, stream_prefix: str, - stream_names: List[str], - positions: Dict[str, Position], + stream_names: list[str], + positions: dict[str, Position], stream_count: int, has_streams: bool, color_wrap: ColorWrap, @@ -173,11 +172,11 @@ def flush_log_streams( # noqa C901 aws_session (AwsSession): The AwsSession for interfacing with CloudWatch. log_group (str): The name of the log group. stream_prefix (str): The prefix for log streams to flush. - stream_names (List[str]): A list of the log stream names. The position of the stream in + stream_names (list[str]): A list of the log stream names. The position of the stream in this list is the stream number. If incomplete, the function will check for remaining streams and mutate this list to add stream names when available, up to the `stream_count` limit. - positions (Dict[str, Position]): A dict mapping stream numbers to (timestamp, skip) pairs + positions (dict[str, Position]): A dict mapping stream numbers to (timestamp, skip) pairs which represent the last record read from each stream. The function will update this list after being called to represent the new last record read from each stream. stream_count (int): The number of streams expected. @@ -189,6 +188,9 @@ def flush_log_streams( # noqa C901 queue_position (Optional[str]): The current queue position. This is not passed in if the job is ran with `quiet=True` + Raises: + Exception: Any exception found besides a ResourceNotFoundException. + Returns: bool: Returns 'True' if any streams have been flushed. """ diff --git a/src/braket/jobs/metrics.py b/src/braket/jobs/metrics.py index 462501cb6..991370f35 100644 --- a/src/braket/jobs/metrics.py +++ b/src/braket/jobs/metrics.py @@ -21,19 +21,17 @@ def log_metric( timestamp: Optional[float] = None, iteration_number: Optional[int] = None, ) -> None: - """ - Records Braket Hybrid Job metrics. + """Records Braket Hybrid Job metrics. Args: - metric_name (str) : The name of the metric. + metric_name (str): The name of the metric. - value (Union[float, int]) : The value of the metric. + value (Union[float, int]): The value of the metric. - timestamp (Optional[float]) : The time the metric data was received, expressed - as the number of seconds - since the epoch. Default: Current system time. + timestamp (Optional[float]): The time the metric data was received, expressed + as the number of seconds since the epoch. Default: Current system time. - iteration_number (Optional[int]) : The iteration number of the metric. + iteration_number (Optional[int]): The iteration number of the metric. """ logged_timestamp = timestamp or time.time() metric_list = [f"Metrics - timestamp={logged_timestamp}; {metric_name}={value};"] diff --git a/src/braket/jobs/metrics_data/cwl_insights_metrics_fetcher.py b/src/braket/jobs/metrics_data/cwl_insights_metrics_fetcher.py index b32cd6b9c..be4e72541 100644 --- a/src/braket/jobs/metrics_data/cwl_insights_metrics_fetcher.py +++ b/src/braket/jobs/metrics_data/cwl_insights_metrics_fetcher.py @@ -15,7 +15,7 @@ import time from logging import Logger, getLogger -from typing import Any, Dict, List, Optional, Union +from typing import Any, Optional, Union from braket.aws.aws_session import AwsSession from braket.jobs.metrics_data.definitions import MetricStatistic, MetricType @@ -23,7 +23,7 @@ from braket.jobs.metrics_data.log_metrics_parser import LogMetricsParser -class CwlInsightsMetricsFetcher(object): +class CwlInsightsMetricsFetcher: LOG_GROUP_NAME = "/aws/braket/jobs" QUERY_DEFAULT_JOB_DURATION = 3 * 60 * 60 @@ -34,7 +34,8 @@ def __init__( poll_interval_seconds: float = 1, logger: Logger = getLogger(__name__), ): - """ + """Initializes a `CwlInsightsMetricsFetcher`. + Args: aws_session (AwsSession): AwsSession to connect to AWS with. poll_timeout_seconds (float): The polling timeout for retrieving the metrics, @@ -52,32 +53,33 @@ def __init__( @staticmethod def _get_element_from_log_line( - element_name: str, log_line: List[Dict[str, Any]] + element_name: str, log_line: list[dict[str, Any]] ) -> Optional[str]: - """ - Finds and returns an element of a log line from CloudWatch Insights results. + """Finds and returns an element of a log line from CloudWatch Insights results. Args: element_name (str): The element to find. - log_line (List[Dict[str, Any]]): An iterator for RegEx matches on a log line. + log_line (list[dict[str, Any]]): An iterator for RegEx matches on a log line. Returns: - Optional[str] : The value of the element with the element name, or None if no such + Optional[str]: The value of the element with the element name, or None if no such element is found. """ return next( (element["value"] for element in log_line if element["field"] == element_name), None ) - def _get_metrics_results_sync(self, query_id: str) -> List[Any]: - """ - Waits for the CloudWatch Insights query to complete and then returns all the results. + def _get_metrics_results_sync(self, query_id: str) -> list[Any]: + """Waits for the CloudWatch Insights query to complete and then returns all the results. Args: query_id (str): CloudWatch Insights query ID. + Raises: + MetricsRetrievalError: Raised if the query is Failed or Cancelled. + Returns: - List[Any]: The results from CloudWatch insights 'GetQueryResults' operation. + list[Any]: The results from CloudWatch insights 'GetQueryResults' operation. """ timeout_time = time.time() + self._poll_timeout_seconds while time.time() < timeout_time: @@ -92,13 +94,12 @@ def _get_metrics_results_sync(self, query_id: str) -> List[Any]: self._logger.warning(f"Timed out waiting for query {query_id}.") return [] - def _parse_log_line(self, result_entry: List[Dict[str, Any]], parser: LogMetricsParser) -> None: - """ - Parses the single entry from CloudWatch Insights results and adds any metrics it finds + def _parse_log_line(self, result_entry: list[dict[str, Any]], parser: LogMetricsParser) -> None: + """Parses the single entry from CloudWatch Insights results and adds any metrics it finds to 'all_metrics' along with the timestamp for the entry. Args: - result_entry (List[Dict[str, Any]]): A structured result from calling CloudWatch + result_entry (list[dict[str, Any]]): A structured result from calling CloudWatch Insights to get logs that contain metrics. A single entry contains the message (the actual line logged to output), the timestamp (generated by CloudWatch Logs), and other metadata that we (currently) do not use. @@ -110,20 +111,19 @@ def _parse_log_line(self, result_entry: List[Dict[str, Any]], parser: LogMetrics parser.parse_log_message(timestamp, message) def _parse_log_query_results( - self, results: List[Any], metric_type: MetricType, statistic: MetricStatistic - ) -> Dict[str, List[Union[str, float, int]]]: - """ - Parses CloudWatch Insights results and returns all found metrics. + self, results: list[Any], metric_type: MetricType, statistic: MetricStatistic + ) -> dict[str, list[Union[str, float, int]]]: + """Parses CloudWatch Insights results and returns all found metrics. Args: - results (List[Any]): A structured result from calling CloudWatch Insights to get + results (list[Any]): A structured result from calling CloudWatch Insights to get logs that contain metrics. metric_type (MetricType): The type of metrics to get. statistic (MetricStatistic): The statistic to determine which metric value to use when there is a conflict. Returns: - Dict[str, List[Union[str, float, int]]] : The metrics data. + dict[str, list[Union[str, float, int]]]: The metrics data. """ parser = LogMetricsParser() for result in results: @@ -137,9 +137,8 @@ def get_metrics_for_job( statistic: MetricStatistic = MetricStatistic.MAX, job_start_time: int | None = None, job_end_time: int | None = None, - ) -> Dict[str, List[Union[str, float, int]]]: - """ - Synchronously retrieves all the algorithm metrics logged by a given Hybrid Job. + ) -> dict[str, list[Union[str, float, int]]]: + """Synchronously retrieves all the algorithm metrics logged by a given Hybrid Job. Args: job_name (str): The name of the Hybrid Job. The name must be exact to ensure only the @@ -153,7 +152,7 @@ def get_metrics_for_job( which the hybrid job finished. Default: current time. Returns: - Dict[str, List[Union[str, float, int]]] : The metrics data, where the keys + dict[str, list[Union[str, float, int]]]: The metrics data, where the keys are the column names and the values are a list containing the values in each row. Example: diff --git a/src/braket/jobs/metrics_data/cwl_metrics_fetcher.py b/src/braket/jobs/metrics_data/cwl_metrics_fetcher.py index 5e3ef28f2..8a5a5333d 100644 --- a/src/braket/jobs/metrics_data/cwl_metrics_fetcher.py +++ b/src/braket/jobs/metrics_data/cwl_metrics_fetcher.py @@ -13,14 +13,14 @@ import time from logging import Logger, getLogger -from typing import Dict, List, Union +from typing import Union from braket.aws.aws_session import AwsSession from braket.jobs.metrics_data.definitions import MetricStatistic, MetricType from braket.jobs.metrics_data.log_metrics_parser import LogMetricsParser -class CwlMetricsFetcher(object): +class CwlMetricsFetcher: LOG_GROUP_NAME = "/aws/braket/jobs" def __init__( @@ -29,7 +29,8 @@ def __init__( poll_timeout_seconds: float = 10, logger: Logger = getLogger(__name__), ): - """ + """Initializes a `CwlMetricsFetcher`. + Args: aws_session (AwsSession): AwsSession to connect to AWS with. poll_timeout_seconds (float): The polling timeout for retrieving the metrics, @@ -44,8 +45,7 @@ def __init__( @staticmethod def _is_metrics_message(message: str) -> bool: - """ - Returns true if a given message is designated as containing Metrics. + """Returns true if a given message is designated as containing Metrics. Args: message (str): The message to check. @@ -63,8 +63,7 @@ def _parse_metrics_from_log_stream( timeout_time: float, parser: LogMetricsParser, ) -> None: - """ - Synchronously retrieves the algorithm metrics logged in a given hybrid job log stream. + """Synchronously retrieves the algorithm metrics logged in a given hybrid job log stream. Args: stream_name (str): The name of the log stream. @@ -93,16 +92,16 @@ def _parse_metrics_from_log_stream( kwargs["nextToken"] = next_token self._logger.warning("Timed out waiting for all metrics. Data may be incomplete.") - def _get_log_streams_for_job(self, job_name: str, timeout_time: float) -> List[str]: - """ - Retrieves the list of log streams relevant to a hybrid job. + def _get_log_streams_for_job(self, job_name: str, timeout_time: float) -> list[str]: + """Retrieves the list of log streams relevant to a hybrid job. Args: job_name (str): The name of the hybrid job. timeout_time (float) : Metrics cease getting streamed if the current time exceeds the timeout time. + Returns: - List[str] : A list of log stream names for the given hybrid job. + list[str]: A list of log stream names for the given hybrid job. """ kwargs = { "logGroupName": self.LOG_GROUP_NAME, @@ -129,9 +128,8 @@ def get_metrics_for_job( job_name: str, metric_type: MetricType = MetricType.TIMESTAMP, statistic: MetricStatistic = MetricStatistic.MAX, - ) -> Dict[str, List[Union[str, float, int]]]: - """ - Synchronously retrieves all the algorithm metrics logged by a given Hybrid Job. + ) -> dict[str, list[Union[str, float, int]]]: + """Synchronously retrieves all the algorithm metrics logged by a given Hybrid Job. Args: job_name (str): The name of the Hybrid Job. The name must be exact to ensure only the @@ -141,7 +139,7 @@ def get_metrics_for_job( when there is a conflict. Default is MetricStatistic.MAX. Returns: - Dict[str, List[Union[str, float, int]]] : The metrics data, where the keys + dict[str, list[Union[str, float, int]]]: The metrics data, where the keys are the column names and the values are a list containing the values in each row. Example: diff --git a/src/braket/jobs/metrics_data/log_metrics_parser.py b/src/braket/jobs/metrics_data/log_metrics_parser.py index 7187486c7..82142a589 100644 --- a/src/braket/jobs/metrics_data/log_metrics_parser.py +++ b/src/braket/jobs/metrics_data/log_metrics_parser.py @@ -12,15 +12,15 @@ # language governing permissions and limitations under the License. import re +from collections.abc import Iterator from logging import Logger, getLogger -from typing import Dict, Iterator, List, Optional, Tuple, Union +from typing import Optional, Union from braket.jobs.metrics_data.definitions import MetricStatistic, MetricType -class LogMetricsParser(object): - """ - This class is used to parse metrics from log lines, and return them in a more +class LogMetricsParser: + """This class is used to parse metrics from log lines, and return them in a more convenient format. """ @@ -43,8 +43,7 @@ def _get_value( new_value: Union[str, float, int], statistic: MetricStatistic, ) -> Union[str, float, int]: - """ - Gets the value based on a statistic. + """Gets the value based on a statistic. Args: current_value (Optional[Union[str, float, int]]): The current value. @@ -64,15 +63,14 @@ def _get_value( def _get_metrics_from_log_line_matches( self, all_matches: Iterator - ) -> Dict[str, Union[str, float, int]]: - """ - Converts matches from a RegEx to a set of metrics. + ) -> dict[str, Union[str, float, int]]: + """Converts matches from a RegEx to a set of metrics. Args: all_matches (Iterator): An iterator for RegEx matches on a log line. Returns: - Dict[str, Union[str, float, int]]: The set of metrics found by the RegEx. The result + dict[str, Union[str, float, int]]: The set of metrics found by the RegEx. The result is in the format { : }. This implies that multiple metrics with the same name are deduped to the last instance of that metric. """ @@ -87,8 +85,7 @@ def _get_metrics_from_log_line_matches( return metrics def parse_log_message(self, timestamp: str, message: str) -> None: - """ - Parses a line from logs, adding all the metrics that have been logged + """Parses a line from logs, adding all the metrics that have been logged on that line. The timestamp is also added to match the corresponding values. Args: @@ -111,19 +108,19 @@ def parse_log_message(self, timestamp: str, message: str) -> None: def get_columns_and_pivot_indices( self, pivot: str - ) -> Tuple[Dict[str, List[Union[str, float, int]]], Dict[Tuple[int, str], int]]: - """ - Parses the metrics to find all the metrics that have the pivot column. The values of the + ) -> tuple[dict[str, list[Union[str, float, int]]], dict[tuple[int, str], int]]: + """Parses the metrics to find all the metrics that have the pivot column. The values of the pivot column are paired with the node_id and assigned a row index, so that all metrics with the same pivot value and node_id are stored in the same row. + Args: pivot (str): The name of the pivot column. Must be TIMESTAMP or ITERATION_NUMBER. Returns: - Tuple[Dict[str, List[Union[str, float, int]]], Dict[Tuple[int, str], int]]: Contains: - The Dict[str, List[Any]] is the result table with all the metrics values initialized + tuple[dict[str, list[Union[str, float, int]]], dict[tuple[int, str], int]]: Contains: + The dict[str, list[Any]] is the result table with all the metrics values initialized to None. - The Dict[Tuple[int, str], int] is the list of pivot indices, where the value of a + The dict[tuple[int, str], int] is the list of pivot indices, where the value of a pivot column and node_id is mapped to a row index. """ row_count = 0 @@ -144,9 +141,8 @@ def get_columns_and_pivot_indices( def get_metric_data_with_pivot( self, pivot: str, statistic: MetricStatistic - ) -> Dict[str, List[Union[str, float, int]]]: - """ - Gets the metric data for a given pivot column name. Metrics without the pivot column + ) -> dict[str, list[Union[str, float, int]]]: + """Gets the metric data for a given pivot column name. Metrics without the pivot column are not included in the results. Metrics that have the same value in the pivot column from the same node are returned in the same row. Metrics from different nodes are stored in different rows. If the metric has multiple values for the row, the statistic is used @@ -169,7 +165,7 @@ def get_metric_data_with_pivot( statistic (MetricStatistic): The statistic to determine which value to use. Returns: - Dict[str, List[Union[str, float, int]]] : The metrics data. + dict[str, list[Union[str, float, int]]]: The metrics data. """ table, pivot_indices = self.get_columns_and_pivot_indices(pivot) for metric in self.all_metrics: @@ -184,9 +180,8 @@ def get_metric_data_with_pivot( def get_parsed_metrics( self, metric_type: MetricType, statistic: MetricStatistic - ) -> Dict[str, List[Union[str, float, int]]]: - """ - Gets all the metrics data, where the keys are the column names and the values are a list + ) -> dict[str, list[Union[str, float, int]]]: + """Gets all the metrics data, where the keys are the column names and the values are a list containing the values in each row. Args: @@ -196,7 +191,7 @@ def get_parsed_metrics( when there is a conflict. Returns: - Dict[str, List[Union[str, float, int]]] : The metrics data. + dict[str, list[Union[str, float, int]]]: The metrics data. Example: timestamp energy diff --git a/src/braket/jobs/quantum_job.py b/src/braket/jobs/quantum_job.py index a84118991..32c660bcf 100644 --- a/src/braket/jobs/quantum_job.py +++ b/src/braket/jobs/quantum_job.py @@ -13,7 +13,7 @@ from __future__ import annotations from abc import ABC, abstractmethod -from typing import Any, Dict, List +from typing import Any from braket.jobs.metrics_data.definitions import MetricStatistic, MetricType @@ -26,6 +26,7 @@ class QuantumJob(ABC): @abstractmethod def arn(self) -> str: """The ARN (Amazon Resource Name) of the hybrid job. + Returns: str: The ARN (Amazon Resource Name) of the hybrid job. """ @@ -34,6 +35,7 @@ def arn(self) -> str: @abstractmethod def name(self) -> str: """The name of the hybrid job. + Returns: str: The name of the hybrid job. """ @@ -47,6 +49,7 @@ def state(self, use_cached_value: bool = False) -> str: value from the Amazon Braket `GetJob` operation. If `False`, calls the `GetJob` operation to retrieve metadata, which also updates the cached value. Default = `False`. + Returns: str: The value of `status` in `metadata()`. This is the value of the `status` key in the Amazon Braket `GetJob` operation. @@ -95,7 +98,7 @@ def logs(self, wait: bool = False, poll_interval_seconds: int = 5) -> None: # Cloudwatch after the job was marked complete. @abstractmethod - def metadata(self, use_cached_value: bool = False) -> Dict[str, Any]: + def metadata(self, use_cached_value: bool = False) -> dict[str, Any]: """Gets the job metadata defined in Amazon Braket. Args: @@ -103,8 +106,9 @@ def metadata(self, use_cached_value: bool = False) -> Dict[str, Any]: from the Amazon Braket `GetJob` operation, if it exists; if does not exist, `GetJob` is called to retrieve the metadata. If `False`, always calls `GetJob`, which also updates the cached value. Default: `False`. + Returns: - Dict[str, Any]: Dict that specifies the hybrid job metadata defined in Amazon Braket. + dict[str, Any]: Dict that specifies the hybrid job metadata defined in Amazon Braket. """ @abstractmethod @@ -112,7 +116,7 @@ def metrics( self, metric_type: MetricType = MetricType.TIMESTAMP, statistic: MetricStatistic = MetricStatistic.MAX, - ) -> Dict[str, List[Any]]: + ) -> dict[str, list[Any]]: """Gets all the metrics data, where the keys are the column names, and the values are a list containing the values in each row. @@ -123,7 +127,7 @@ def metrics( when there is a conflict. Default: MetricStatistic.MAX. Returns: - Dict[str, List[Any]] : The metrics data. + dict[str, list[Any]]: The metrics data. Example: timestamp energy @@ -150,7 +154,7 @@ def result( self, poll_timeout_seconds: float = DEFAULT_RESULTS_POLL_TIMEOUT, poll_interval_seconds: float = DEFAULT_RESULTS_POLL_INTERVAL, - ) -> Dict[str, Any]: + ) -> dict[str, Any]: """Retrieves the hybrid job result persisted using save_job_result() function. Args: @@ -162,7 +166,7 @@ def result( Returns: - Dict[str, Any]: Dict specifying the hybrid job results. + dict[str, Any]: Dict specifying the hybrid job results. Raises: RuntimeError: if hybrid job is in a FAILED or CANCELLED state. diff --git a/src/braket/jobs/quantum_job_creation.py b/src/braket/jobs/quantum_job_creation.py index 9e18faeab..98905dc56 100644 --- a/src/braket/jobs/quantum_job_creation.py +++ b/src/braket/jobs/quantum_job_creation.py @@ -258,8 +258,7 @@ def prepare_quantum_job( def _generate_default_job_name( image_uri: str | None = None, func: Callable | None = None, timestamp: int | str | None = None ) -> str: - """ - Generate default job name using the image uri and entrypoint function. + """Generate default job name using the image uri and entrypoint function. Args: image_uri (str | None): URI for the image container. @@ -277,25 +276,25 @@ def _generate_default_job_name( if len(name) + len(timestamp) > max_length: name = name[: max_length - len(timestamp) - 1] warnings.warn( - f"Job name exceeded {max_length} characters. Truncating name to {name}-{timestamp}." + f"Job name exceeded {max_length} characters. " + f"Truncating name to {name}-{timestamp}.", + stacklevel=1, ) + elif not image_uri: + name = "braket-job-default" else: - if not image_uri: - name = "braket-job-default" - else: - job_type_match = re.search("/amazon-braket-(.*)-jobs:", image_uri) or re.search( - "/amazon-braket-([^:/]*)", image_uri - ) - container = f"-{job_type_match.groups()[0]}" if job_type_match else "" - name = f"braket-job{container}" + job_type_match = re.search("/amazon-braket-(.*)-jobs:", image_uri) or re.search( + "/amazon-braket-([^:/]*)", image_uri + ) + container = f"-{job_type_match.groups()[0]}" if job_type_match else "" + name = f"braket-job{container}" return f"{name}-{timestamp}" def _process_s3_source_module( source_module: str, entry_point: str, aws_session: AwsSession, code_location: str ) -> None: - """ - Check that the source module is an S3 URI of the correct type and that entry point is + """Check that the source module is an S3 URI of the correct type and that entry point is provided. Args: @@ -304,6 +303,9 @@ def _process_s3_source_module( aws_session (AwsSession): AwsSession to copy source module to code location. code_location (str): S3 URI pointing to the location where the code will be copied to. + + Raises: + ValueError: The entry point is None or does not end with .tar.gz. """ if entry_point is None: raise ValueError("If source_module is an S3 URI, entry_point must be provided.") @@ -318,9 +320,9 @@ def _process_s3_source_module( def _process_local_source_module( source_module: str, entry_point: str, aws_session: AwsSession, code_location: str ) -> str: - """ - Check that entry point is valid with respect to source module, or provide a default + """Check that entry point is valid with respect to source module, or provide a default value if entry point is not given. Tar and upload source module to code location in S3. + Args: source_module (str): Local path pointing to the source module. entry_point (str): Entry point relative to the source module. @@ -328,6 +330,9 @@ def _process_local_source_module( code_location (str): S3 URI pointing to the location where the code will be uploaded to. + Raises: + ValueError: Raised if the source module file is not found. + Returns: str: Entry point. """ @@ -344,12 +349,14 @@ def _process_local_source_module( def _validate_entry_point(source_module_path: Path, entry_point: str) -> None: - """ - Confirm that a valid entry point relative to source module is given. + """Confirm that a valid entry point relative to source module is given. Args: source_module_path (Path): Path to source module. entry_point (str): Entry point relative to source module. + + Raises: + ValueError: Raised if the module was not found. """ importable, _, _method = entry_point.partition(":") sys.path.append(str(source_module_path.parent)) @@ -357,7 +364,8 @@ def _validate_entry_point(source_module_path: Path, entry_point: str) -> None: # second argument allows relative imports importlib.invalidate_caches() module = importlib.util.find_spec(importable, source_module_path.stem) - assert module is not None + if module is None: + raise AssertionError # if entry point is nested (ie contains '.'), parent modules are imported except (ModuleNotFoundError, AssertionError): raise ValueError(f"Entry point module was not found: {importable}") @@ -368,8 +376,7 @@ def _validate_entry_point(source_module_path: Path, entry_point: str) -> None: def _tar_and_upload_to_code_location( source_module_path: Path, aws_session: AwsSession, code_location: str ) -> None: - """ - Tar and upload source module to code location. + """Tar and upload source module to code location. Args: source_module_path (Path): Path to source module. @@ -384,12 +391,14 @@ def _tar_and_upload_to_code_location( def _validate_params(dict_arr: dict[str, tuple[any, any]]) -> None: - """ - Validate that config parameters are of the right type. + """Validate that config parameters are of the right type. Args: dict_arr (dict[str, tuple[any, any]]): dict mapping parameter names to a tuple containing the provided value and expected type. + + Raises: + ValueError: If the user_input is not the same as the expected data type. """ for parameter_name, value_tuple in dict_arr.items(): user_input, expected_datatype = value_tuple @@ -407,8 +416,8 @@ def _process_input_data( aws_session: AwsSession, subdirectory: str, ) -> list[dict[str, Any]]: - """ - Convert input data into a list of dicts compatible with the Braket API. + """Convert input data into a list of dicts compatible with the Braket API. + Args: input_data (str | dict | S3DataSourceConfig): Either a channel definition or a dictionary mapping channel names to channel definitions, where a channel definition @@ -437,8 +446,8 @@ def _process_channel( channel_name: str, subdirectory: str, ) -> S3DataSourceConfig: - """ - Convert a location to an S3DataSourceConfig, uploading local data to S3, if necessary. + """Convert a location to an S3DataSourceConfig, uploading local data to S3, if necessary. + Args: location (str): Local prefix or S3 prefix. job_name (str): Hybrid job name. @@ -469,8 +478,7 @@ def _process_channel( def _convert_input_to_config(input_data: dict[str, S3DataSourceConfig]) -> list[dict[str, Any]]: - """ - Convert a dictionary mapping channel names to S3DataSourceConfigs into a list of channel + """Convert a dictionary mapping channel names to S3DataSourceConfigs into a list of channel configs compatible with the Braket API. Args: diff --git a/src/braket/jobs/serialization.py b/src/braket/jobs/serialization.py index f8c854d03..179a44970 100644 --- a/src/braket/jobs/serialization.py +++ b/src/braket/jobs/serialization.py @@ -13,26 +13,25 @@ import codecs import pickle -from typing import Any, Dict +from typing import Any from braket.jobs_data import PersistedJobDataFormat def serialize_values( - data_dictionary: Dict[str, Any], data_format: PersistedJobDataFormat -) -> Dict[str, Any]: - """ - Serializes the `data_dictionary` values to the format specified by `data_format`. + data_dictionary: dict[str, Any], data_format: PersistedJobDataFormat +) -> dict[str, Any]: + """Serializes the `data_dictionary` values to the format specified by `data_format`. Args: - data_dictionary (Dict[str, Any]): Dict whose values are to be serialized. + data_dictionary (dict[str, Any]): Dict whose values are to be serialized. data_format (PersistedJobDataFormat): The data format used to serialize the values. Note that for `PICKLED` data formats, the values are base64 encoded after serialization, so that they represent valid UTF-8 text and are compatible with `PersistedJobData.json()`. Returns: - Dict[str, Any]: Dict with same keys as `data_dictionary` and values serialized to + dict[str, Any]: Dict with same keys as `data_dictionary` and values serialized to the specified `data_format`. """ return ( @@ -46,18 +45,17 @@ def serialize_values( def deserialize_values( - data_dictionary: Dict[str, Any], data_format: PersistedJobDataFormat -) -> Dict[str, Any]: - """ - Deserializes the `data_dictionary` values from the format specified by `data_format`. + data_dictionary: dict[str, Any], data_format: PersistedJobDataFormat +) -> dict[str, Any]: + """Deserializes the `data_dictionary` values from the format specified by `data_format`. Args: - data_dictionary (Dict[str, Any]): Dict whose values are to be deserialized. + data_dictionary (dict[str, Any]): Dict whose values are to be deserialized. data_format (PersistedJobDataFormat): The data format that the `data_dictionary` values are currently serialized with. Returns: - Dict[str, Any]: Dict with same keys as `data_dictionary` and values deserialized from + dict[str, Any]: Dict with same keys as `data_dictionary` and values deserialized from the specified `data_format` to plaintext. """ return ( diff --git a/src/braket/parametric/free_parameter.py b/src/braket/parametric/free_parameter.py index db22f5f60..9d5826520 100644 --- a/src/braket/parametric/free_parameter.py +++ b/src/braket/parametric/free_parameter.py @@ -22,8 +22,7 @@ class FreeParameter(FreeParameterExpression): - """ - Class 'FreeParameter' + """Class 'FreeParameter' Free parameters can be used in parameterized circuits. Objects that can take a parameter all inherit from :class:'Parameterizable'. The FreeParameter can be swapped in to a circuit @@ -39,8 +38,7 @@ class FreeParameter(FreeParameterExpression): """ def __init__(self, name: str): - """ - Initializes a new :class:'FreeParameter' object. + """Initializes a new :class:'FreeParameter' object. Args: name (str): Name of the :class:'FreeParameter'. Can be a unicode value. @@ -54,14 +52,11 @@ def __init__(self, name: str): @property def name(self) -> str: - """ - str: Name of this parameter. - """ + """str: Name of this parameter.""" return self._name.name def subs(self, parameter_values: dict[str, Number]) -> Union[FreeParameter, Number]: - """ - Substitutes a value in if the parameter exists within the mapping. + """Substitutes a value in if the parameter exists within the mapping. Args: parameter_values (dict[str, Number]): A mapping of parameter to its @@ -79,14 +74,13 @@ def __str__(self): def __hash__(self) -> int: return hash(tuple(self.name)) - def __eq__(self, other): + def __eq__(self, other: FreeParameter): if isinstance(other, FreeParameter): return self._name == other._name return super().__eq__(other) def __repr__(self) -> str: - """ - The representation of the :class:'FreeParameter'. + """The representation of the :class:'FreeParameter'. Returns: str: The name of the class:'FreeParameter' to represent the class. diff --git a/src/braket/parametric/free_parameter_expression.py b/src/braket/parametric/free_parameter_expression.py index fdfa1469a..d3ad91259 100644 --- a/src/braket/parametric/free_parameter_expression.py +++ b/src/braket/parametric/free_parameter_expression.py @@ -25,8 +25,7 @@ class FreeParameterExpression: - """ - Class 'FreeParameterExpression' + """Class 'FreeParameterExpression' Objects that can take a parameter all inherit from :class:'Parameterizable'. FreeParametersExpressions can hold FreeParameters that can later be @@ -35,8 +34,7 @@ class FreeParameterExpression: """ def __init__(self, expression: Union[FreeParameterExpression, Number, sympy.Expr, str]): - """ - Initializes a FreeParameterExpression. Best practice is to initialize using + """Initializes a FreeParameterExpression. Best practice is to initialize using FreeParameters and Numbers. Not meant to be initialized directly. Below are examples of how FreeParameterExpressions should be made. @@ -44,6 +42,10 @@ def __init__(self, expression: Union[FreeParameterExpression, Number, sympy.Expr Args: expression (Union[FreeParameterExpression, Number, Expr, str]): The expression to use. + Raises: + NotImplementedError: Raised if the expression is not of type + [FreeParameterExpression, Number, Expr, str] + Examples: >>> expression_1 = FreeParameter("theta") * FreeParameter("alpha") >>> expression_2 = 1 + FreeParameter("beta") + 2 * FreeParameter("alpha") @@ -67,6 +69,7 @@ def __init__(self, expression: Union[FreeParameterExpression, Number, sympy.Expr @property def expression(self) -> Union[Number, sympy.Expr]: """Gets the expression. + Returns: Union[Number, Expr]: The expression for the FreeParameterExpression. """ @@ -87,7 +90,7 @@ def subs( Union[FreeParameterExpression, Number, Expr]: A numerical value if there are no symbols left in the expression otherwise returns a new FreeParameterExpression. """ - new_parameter_values = dict() + new_parameter_values = {} for key, val in parameter_values.items(): if issubclass(type(key), FreeParameterExpression): new_parameter_values[key.expression] = val @@ -121,53 +124,52 @@ def _eval_operation(self, node: Any) -> FreeParameterExpression: else: raise ValueError(f"Unsupported string detected: {node}") - def __add__(self, other): + def __add__(self, other: FreeParameterExpression): if issubclass(type(other), FreeParameterExpression): return FreeParameterExpression(self.expression + other.expression) else: return FreeParameterExpression(self.expression + other) - def __radd__(self, other): + def __radd__(self, other: FreeParameterExpression): return FreeParameterExpression(other + self.expression) - def __sub__(self, other): + def __sub__(self, other: FreeParameterExpression): if issubclass(type(other), FreeParameterExpression): return FreeParameterExpression(self.expression - other.expression) else: return FreeParameterExpression(self.expression - other) - def __rsub__(self, other): + def __rsub__(self, other: FreeParameterExpression): return FreeParameterExpression(other - self.expression) - def __mul__(self, other): + def __mul__(self, other: FreeParameterExpression): if issubclass(type(other), FreeParameterExpression): return FreeParameterExpression(self.expression * other.expression) else: return FreeParameterExpression(self.expression * other) - def __rmul__(self, other): + def __rmul__(self, other: FreeParameterExpression): return FreeParameterExpression(other * self.expression) - def __pow__(self, other, modulo=None): + def __pow__(self, other: FreeParameterExpression, modulo: float = None): if issubclass(type(other), FreeParameterExpression): return FreeParameterExpression(self.expression**other.expression) else: return FreeParameterExpression(self.expression**other) - def __rpow__(self, other): + def __rpow__(self, other: FreeParameterExpression): return FreeParameterExpression(other**self.expression) def __neg__(self): return FreeParameterExpression(-1 * self.expression) - def __eq__(self, other): + def __eq__(self, other: FreeParameterExpression): if isinstance(other, FreeParameterExpression): return sympy.sympify(self.expression).equals(sympy.sympify(other.expression)) return False def __repr__(self) -> str: - """ - The representation of the :class:'FreeParameterExpression'. + """The representation of the :class:'FreeParameterExpression'. Returns: str: The expression of the class:'FreeParameterExpression' to represent the class. @@ -199,11 +201,12 @@ def _to_oqpy_expression(self) -> OQPyExpression: return fvar -def subs_if_free_parameter(parameter: Any, **kwargs) -> Any: +def subs_if_free_parameter(parameter: Any, **kwargs: Union[FreeParameterExpression, str]) -> Any: """Substitute a free parameter with the given kwargs, if any. + Args: parameter (Any): The parameter. - ``**kwargs``: The kwargs to use to substitute. + **kwargs (Union[FreeParameterExpression, str]): The kwargs to use to substitute. Returns: Any: The substituted parameters. @@ -217,8 +220,7 @@ def subs_if_free_parameter(parameter: Any, **kwargs) -> Any: def _is_float(argument: str) -> bool: - """ - Checks if a string can be cast into a float. + """Checks if a string can be cast into a float. Args: argument (str): String to check. diff --git a/src/braket/parametric/parameterizable.py b/src/braket/parametric/parameterizable.py index bd5dbc5a7..90c4dc589 100644 --- a/src/braket/parametric/parameterizable.py +++ b/src/braket/parametric/parameterizable.py @@ -21,8 +21,7 @@ class Parameterizable(ABC): - """ - A parameterized object is the abstract definition of an object + """A parameterized object is the abstract definition of an object that can take in FreeParameterExpressions. """ @@ -38,11 +37,13 @@ def parameters(self) -> list[Union[FreeParameterExpression, FreeParameter, float """ @abstractmethod - def bind_values(self, **kwargs) -> Any: - """ - Takes in parameters and returns an object with specified parameters + def bind_values(self, **kwargs: Union[FreeParameter, str]) -> Any: + """Takes in parameters and returns an object with specified parameters replaced with their values. + Args: + **kwargs (Union[FreeParameter, str]): Arbitrary keyword arguments. + Returns: Any: The result object will depend on the implementation of the object being bound. """ diff --git a/src/braket/pulse/ast/approximation_parser.py b/src/braket/pulse/ast/approximation_parser.py index 4398d2816..f7ec9d3bf 100644 --- a/src/braket/pulse/ast/approximation_parser.py +++ b/src/braket/pulse/ast/approximation_parser.py @@ -15,7 +15,7 @@ from collections import defaultdict from collections.abc import KeysView from dataclasses import dataclass -from typing import Any, Optional, Union +from typing import Any, ClassVar, Optional, Union import numpy as np from openpulse import ast @@ -50,15 +50,16 @@ class _ParseState: class _ApproximationParser(QASMVisitor[_ParseState]): """Walk the AST and build the output signal amplitude, frequency and phases - for each channel.""" + for each channel. + """ - TIME_UNIT_TO_EXP = {"dt": 4, "ns": 3, "us": 2, "ms": 1, "s": 0} + TIME_UNIT_TO_EXP: ClassVar = {"dt": 4, "ns": 3, "us": 2, "ms": 1, "s": 0} def __init__(self, program: Program, frames: dict[str, Frame]): self.amplitudes = defaultdict(TimeSeries) self.frequencies = defaultdict(TimeSeries) self.phases = defaultdict(TimeSeries) - context = _ParseState(variables=dict(), frame_data=_init_frame_data(frames)) + context = _ParseState(variables={}, frame_data=_init_frame_data(frames)) self._qubit_frames_mapping: dict[str, list[str]] = _init_qubit_frame_mapping(frames) self.visit(program.to_ast(include_externs=False), context) @@ -66,11 +67,13 @@ def visit( self, node: Union[ast.QASMNode, ast.Expression], context: Optional[_ParseState] = None ) -> Any: """Visit a node. + Args: node (Union[ast.QASMNode, ast.Expression]): The node to visit. context (Optional[_ParseState]): The parse state context. + Returns: - Any: The parse return value. + Any: The parsed return value. """ return super().visit(node, context) @@ -103,6 +106,7 @@ def _delay_frame(self, frame_id: str, to_delay_time: float, context: _ParseState def visit_Program(self, node: ast.Program, context: _ParseState = None) -> None: """Visit a Program. + Args: node (ast.Program): The program. context (_ParseState): The parse state context. @@ -112,23 +116,35 @@ def visit_Program(self, node: ast.Program, context: _ParseState = None) -> None: def visit_ExpressionStatement(self, node: ast.ExpressionStatement, context: _ParseState) -> Any: """Visit an Expression. + Args: node (ast.ExpressionStatement): The expression. context (_ParseState): The parse state context. + + Returns: + Any: The parsed return value. """ return self.visit(node.expression, context) # need to check def visit_ClassicalDeclaration( self, node: ast.ClassicalDeclaration, context: _ParseState - ) -> None: + ) -> Union[dict, None]: """Visit a Classical Declaration. node.type, node.identifier, node.init_expression angle[20] a = 1+2; waveform wf = []; port a; + Args: node (ast.ClassicalDeclaration): The classical declaration. context (_ParseState): The parse state context. + + Raises: + NotImplementedError: Raised if the node is not a PortType, FrameType, or + WaveformType. + + Returns: + Union[dict, None]: Returns a dict if WaveformType, None otherwise. """ identifier = self.visit(node.identifier, context) if type(node.type) == ast.WaveformType: @@ -144,6 +160,7 @@ def visit_DelayInstruction(self, node: ast.DelayInstruction, context: _ParseStat """Visit a Delay Instruction. node.duration, node.qubits delay[100ns] $0; + Args: node (ast.DelayInstruction): The classical declaration. context (_ParseState): The parse state context. @@ -168,9 +185,13 @@ def visit_QuantumBarrier(self, node: ast.QuantumBarrier, context: _ParseState) - barrier $0; barrier; barrier frame, frame1; + Args: node (ast.QuantumBarrier): The quantum barrier. context (_ParseState): The parse state context. + + Returns: + None: No return value. """ frames = self._get_frame_parameters(node.qubits, context) if len(frames) == 0: @@ -190,9 +211,13 @@ def visit_FunctionCall(self, node: ast.FunctionCall, context: _ParseState) -> An """Visit a Quantum Barrier. node.name, node.arguments f(args,arg2) + Args: node (ast.FunctionCall): The function call. context (_ParseState): The parse state context. + + Returns: + Any: The parsed return value. """ func_name = node.name.name return getattr(self, func_name)(node, context) @@ -204,6 +229,9 @@ def visit_Identifier(self, node: ast.Identifier, context: _ParseState) -> Any: Args: node (ast.Identifier): The identifier. context (_ParseState): The parse state context. + + Returns: + Any: The parsed return value. """ if node.name in context.variables: return context.variables[node.name] @@ -214,9 +242,16 @@ def visit_UnaryExpression(self, node: ast.UnaryExpression, context: _ParseState) """Visit Unary Expression. node.op, node.expression ~ ! - + Args: node (ast.UnaryExpression): The unary expression. context (_ParseState): The parse state context. + + Returns: + bool: The parsed boolean operator. + + Raises: + NotImplementedError: Raised for unsupported boolean operators. """ if node.op == ast.UnaryOperator["-"]: return -1 * self.visit(node.expression, context) @@ -234,9 +269,17 @@ def visit_BinaryExpression(self, node: ast.BinaryExpression, context: _ParseStat 1+2 a.b > < >= <= == != && || | ^ & << >> + - * / % ** . + Args: node (ast.BinaryExpression): The binary expression. context (_ParseState): The parse state context. + + Raises: + NotImplementedError: Raised if the binary operator is not in + [> < >= <= == != && || | ^ & << >> + - * / % ** ] + + Returns: + Any: The parsed binary operator. """ lhs = self.visit(node.lhs, context) rhs = self.visit(node.rhs, context) @@ -284,63 +327,85 @@ def visit_BinaryExpression(self, node: ast.BinaryExpression, context: _ParseStat else: raise NotImplementedError - def visit_ArrayLiteral(self, node: ast.ArrayLiteral, context: _ParseState) -> Any: + def visit_ArrayLiteral(self, node: ast.ArrayLiteral, context: _ParseState) -> list[Any]: """Visit Array Literal. node.values {1,2,4} + Args: node (ast.ArrayLiteral): The array literal. context (_ParseState): The parse state context. + + Returns: + list[Any]: The parsed ArrayLiteral. """ return [self.visit(e, context) for e in node.values] - def visit_IntegerLiteral(self, node: ast.IntegerLiteral, context: _ParseState) -> Any: + def visit_IntegerLiteral(self, node: ast.IntegerLiteral, context: _ParseState) -> int: """Visit Integer Literal. node.value 1 Args: node (ast.IntegerLiteral): The integer literal. context (_ParseState): The parse state context. + + Returns: + int: The parsed int value. """ return int(node.value) - def visit_ImaginaryLiteral(self, node: ast.ImaginaryLiteral, context: _ParseState) -> Any: + def visit_ImaginaryLiteral(self, node: ast.ImaginaryLiteral, context: _ParseState) -> complex: """Visit Imaginary Number Literal. node.value 1.3im Args: - node (ast.visit_ImaginaryLiteral): The imaginary number literal. + node (ast.ImaginaryLiteral): The imaginary number literal. context (_ParseState): The parse state context. + + Returns: + complex: The parsed complex value. """ return complex(node.value * 1j) - def visit_FloatLiteral(self, node: ast.FloatLiteral, context: _ParseState) -> Any: + def visit_FloatLiteral(self, node: ast.FloatLiteral, context: _ParseState) -> float: """Visit Float Literal. node.value 1.1 Args: node (ast.FloatLiteral): The float literal. context (_ParseState): The parse state context. + + Returns: + float: The parsed float value. """ return float(node.value) - def visit_BooleanLiteral(self, node: ast.BooleanLiteral, context: _ParseState) -> Any: + def visit_BooleanLiteral(self, node: ast.BooleanLiteral, context: _ParseState) -> bool: """Visit Boolean Literal. node.value true Args: node (ast.BooleanLiteral): The boolean literal. context (_ParseState): The parse state context. + + Returns: + bool: The parsed boolean value. """ return True if node.value else False - def visit_DurationLiteral(self, node: ast.DurationLiteral, context: _ParseState) -> Any: + def visit_DurationLiteral(self, node: ast.DurationLiteral, context: _ParseState) -> float: """Visit Duration Literal. node.value, node.unit (node.unit.name, node.unit.value) 1 Args: node (ast.DurationLiteral): The duration literal. context (_ParseState): The parse state context. + + Raises: + ValueError: Raised based on time unit not being in `self.TIME_UNIT_TO_EXP`. + + Returns: + float: The duration represented as a float """ if node.unit.name not in self.TIME_UNIT_TO_EXP: raise ValueError(f"Unexpected duration specified: {node.unit.name}:{node.unit.value}") @@ -351,6 +416,7 @@ def visit_DurationLiteral(self, node: ast.DurationLiteral, context: _ParseState) def set_frequency(self, node: ast.FunctionCall, context: _ParseState) -> None: """A 'set_frequency' Function call. + Args: node (ast.FunctionCall): The function call node. context (_ParseState): The parse state. @@ -361,6 +427,7 @@ def set_frequency(self, node: ast.FunctionCall, context: _ParseState) -> None: def shift_frequency(self, node: ast.FunctionCall, context: _ParseState) -> None: """A 'shift_frequency' Function call. + Args: node (ast.FunctionCall): The function call node. context (_ParseState): The parse state. @@ -371,6 +438,7 @@ def shift_frequency(self, node: ast.FunctionCall, context: _ParseState) -> None: def set_phase(self, node: ast.FunctionCall, context: _ParseState) -> None: """A 'set_phase' Function call. + Args: node (ast.FunctionCall): The function call node. context (_ParseState): The parse state. @@ -381,6 +449,7 @@ def set_phase(self, node: ast.FunctionCall, context: _ParseState) -> None: def shift_phase(self, node: ast.FunctionCall, context: _ParseState) -> None: """A 'shift_phase' Function call. + Args: node (ast.FunctionCall): The function call node. context (_ParseState): The parse state. @@ -392,6 +461,7 @@ def shift_phase(self, node: ast.FunctionCall, context: _ParseState) -> None: def set_scale(self, node: ast.FunctionCall, context: _ParseState) -> None: """A 'set_scale' Function call. + Args: node (ast.FunctionCall): The function call node. context (_ParseState): The parse state. @@ -402,6 +472,7 @@ def set_scale(self, node: ast.FunctionCall, context: _ParseState) -> None: def capture_v0(self, node: ast.FunctionCall, context: _ParseState) -> None: """A 'capture_v0' Function call. + Args: node (ast.FunctionCall): The function call node. context (_ParseState): The parse state. @@ -410,9 +481,17 @@ def capture_v0(self, node: ast.FunctionCall, context: _ParseState) -> None: def play(self, node: ast.FunctionCall, context: _ParseState) -> None: """A 'play' Function call. + Args: node (ast.FunctionCall): The function call node. context (_ParseState): The parse state. + + Raises: + NotImplementedError: Raises if not of type + [ast.Identifier, ast.FunctionCall, ast.ArrayLiteral] + + Returns: + None: Returns None """ frame_id = self.visit(node.arguments[0], context) if isinstance(node.arguments[1], ast.ArrayLiteral): @@ -436,9 +515,11 @@ def play(self, node: ast.FunctionCall, context: _ParseState) -> None: def constant(self, node: ast.FunctionCall, context: _ParseState) -> Waveform: """A 'constant' Waveform Function call. + Args: node (ast.FunctionCall): The function call node. context (_ParseState): The parse state. + Returns: Waveform: The waveform object representing the function call. """ @@ -447,9 +528,11 @@ def constant(self, node: ast.FunctionCall, context: _ParseState) -> Waveform: def gaussian(self, node: ast.FunctionCall, context: _ParseState) -> Waveform: """A 'gaussian' Waveform Function call. + Args: node (ast.FunctionCall): The function call node. context (_ParseState): The parse state. + Returns: Waveform: The waveform object representing the function call. """ @@ -458,9 +541,11 @@ def gaussian(self, node: ast.FunctionCall, context: _ParseState) -> Waveform: def drag_gaussian(self, node: ast.FunctionCall, context: _ParseState) -> Waveform: """A 'drag_gaussian' Waveform Function call. + Args: node (ast.FunctionCall): The function call node. context (_ParseState): The parse state. + Returns: Waveform: The waveform object representing the function call. """ @@ -469,7 +554,7 @@ def drag_gaussian(self, node: ast.FunctionCall, context: _ParseState) -> Wavefor def _init_frame_data(frames: dict[str, Frame]) -> dict[str, _FrameState]: - frame_states = dict() + frame_states = {} for frameId, frame in frames.items(): frame_states[frameId] = _FrameState( frame.port.dt, frame.frequency, frame.phase % (2 * np.pi) @@ -500,8 +585,10 @@ def _lcm_floats(*dts: list[float]) -> float: Args: *dts (list[float]): list of time resolutions - """ + Returns: + float: The LCM of time increments for a list of frames. + """ sample_rates = [round(1 / dt) for dt in dts] res_gcd = sample_rates[0] for sr in sample_rates[1:]: diff --git a/src/braket/pulse/ast/qasm_parser.py b/src/braket/pulse/ast/qasm_parser.py index 0146eca66..25832aa58 100644 --- a/src/braket/pulse/ast/qasm_parser.py +++ b/src/braket/pulse/ast/qasm_parser.py @@ -40,6 +40,7 @@ def visit_ClassicalDeclaration( angle[20] a = 1+2; waveform wf = []; port a; + Args: node (ast.ClassicalDeclaration): The classical declaration. context (PrinterState): The printer state context. @@ -53,7 +54,7 @@ def ast_to_qasm(ast: ast.Program) -> str: """Converts an AST program to OpenQASM Args: - ast (Program): The AST program. + ast (ast.Program): The AST program. Returns: str: a str representing the OpenPulse program encoding the program. diff --git a/src/braket/pulse/ast/qasm_transformer.py b/src/braket/pulse/ast/qasm_transformer.py index f5e350883..3d7adb4a3 100644 --- a/src/braket/pulse/ast/qasm_transformer.py +++ b/src/braket/pulse/ast/qasm_transformer.py @@ -18,8 +18,7 @@ class _IRQASMTransformer(QASMTransformer): - """ - QASMTransformer which walks the AST and makes the necessary modifications needed + """QASMTransformer which walks the AST and makes the necessary modifications needed for IR generation. Currently, it performs the following operations: * Replaces capture_v0 function calls with assignment statements, assigning the readout value to a bit register element. @@ -32,8 +31,10 @@ def __init__(self, register_identifier: Optional[str] = None): def visit_ExpressionStatement(self, expression_statement: ast.ExpressionStatement) -> Any: """Visit an Expression. + Args: expression_statement (ast.ExpressionStatement): The expression statement. + Returns: Any: The expression statement. """ diff --git a/src/braket/pulse/frame.py b/src/braket/pulse/frame.py index b84e4a440..63700d22e 100644 --- a/src/braket/pulse/frame.py +++ b/src/braket/pulse/frame.py @@ -11,6 +11,8 @@ # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. +from __future__ import annotations + import math from typing import Any, Optional @@ -21,9 +23,9 @@ class Frame: - """ - Frame tracks the frame of reference, when interacting with the qubits, throughout the execution - of a program. See https://openqasm.com/language/openpulse.html#frames for more details. + """Frame tracks the frame of reference, when interacting with the qubits, throughout the + execution of a program. See https://openqasm.com/language/openpulse.html#frames for more + details. """ def __init__( @@ -35,7 +37,8 @@ def __init__( is_predefined: bool = False, properties: Optional[dict[str, Any]] = None, ): - """ + """Initializes a Frame. + Args: frame_id (str): str identifying a unique frame. port (Port): port that this frame is attached to. @@ -58,7 +61,7 @@ def id(self) -> str: """Returns a str indicating the frame id.""" return self._frame_id - def __eq__(self, other) -> bool: + def __eq__(self, other: Frame) -> bool: return ( ( (self.id == other.id) diff --git a/src/braket/pulse/port.py b/src/braket/pulse/port.py index 2b1760415..99b1acca5 100644 --- a/src/braket/pulse/port.py +++ b/src/braket/pulse/port.py @@ -11,6 +11,8 @@ # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. +from __future__ import annotations + from typing import Any, Optional from oqpy import PortVar @@ -18,13 +20,13 @@ class Port: - """ - Ports represent any input or output component meant to manipulate and observe qubits on + """Ports represent any input or output component meant to manipulate and observe qubits on a device. See https://openqasm.com/language/openpulse.html#ports for more details. """ def __init__(self, port_id: str, dt: float, properties: Optional[dict[str, Any]] = None): - """ + """Initializes a Port. + Args: port_id (str): str identifying a unique port on the device. dt (float): The smallest time step that may be used on the control hardware. @@ -45,7 +47,7 @@ def dt(self) -> float: """Returns the smallest time step that may be used on the control hardware.""" return self._dt - def __eq__(self, other) -> bool: + def __eq__(self, other: Port) -> bool: return self.id == other.id if isinstance(other, Port) else False def _to_oqpy_expression(self) -> OQPyExpression: diff --git a/src/braket/pulse/pulse_sequence.py b/src/braket/pulse/pulse_sequence.py index ac6f49067..e6d78f11f 100644 --- a/src/braket/pulse/pulse_sequence.py +++ b/src/braket/pulse/pulse_sequence.py @@ -35,8 +35,7 @@ class PulseSequence: - """ - A representation of a collection of instructions to be performed on a quantum device + """A representation of a collection of instructions to be performed on a quantum device and the requested results. """ @@ -70,8 +69,7 @@ def parameters(self) -> set[FreeParameter]: def set_frequency( self, frame: Frame, frequency: Union[float, FreeParameterExpression] ) -> PulseSequence: - """ - Adds an instruction to set the frequency of the frame to the specified `frequency` value. + """Adds an instruction to set the frequency of the frame to the specified `frequency` value. Args: frame (Frame): Frame for which the frequency needs to be set. @@ -81,7 +79,6 @@ def set_frequency( Returns: PulseSequence: self, with the instruction added. """ - _validate_uniqueness(self._frames, frame) self._register_free_parameters(frequency) self._program.set_frequency(frame=frame, freq=frequency) @@ -91,8 +88,8 @@ def set_frequency( def shift_frequency( self, frame: Frame, frequency: Union[float, FreeParameterExpression] ) -> PulseSequence: - """ - Adds an instruction to shift the frequency of the frame by the specified `frequency` value. + """Adds an instruction to shift the frequency of the frame by the specified `frequency` + value. Args: frame (Frame): Frame for which the frequency needs to be shifted. @@ -111,8 +108,7 @@ def shift_frequency( def set_phase( self, frame: Frame, phase: Union[float, FreeParameterExpression] ) -> PulseSequence: - """ - Adds an instruction to set the phase of the frame to the specified `phase` value. + """Adds an instruction to set the phase of the frame to the specified `phase` value. Args: frame (Frame): Frame for which the frequency needs to be set. @@ -131,8 +127,7 @@ def set_phase( def shift_phase( self, frame: Frame, phase: Union[float, FreeParameterExpression] ) -> PulseSequence: - """ - Adds an instruction to shift the phase of the frame by the specified `phase` value. + """Adds an instruction to shift the phase of the frame by the specified `phase` value. Args: frame (Frame): Frame for which the phase needs to be shifted. @@ -151,8 +146,7 @@ def shift_phase( def set_scale( self, frame: Frame, scale: Union[float, FreeParameterExpression] ) -> PulseSequence: - """ - Adds an instruction to set the scale on the frame to the specified `scale` value. + """Adds an instruction to set the scale on the frame to the specified `scale` value. Args: frame (Frame): Frame for which the scale needs to be set. @@ -173,14 +167,14 @@ def delay( qubits_or_frames: Union[Frame, list[Frame], QubitSet], duration: Union[float, FreeParameterExpression], ) -> PulseSequence: - """ - Adds an instruction to advance the frame clock by the specified `duration` value. + """Adds an instruction to advance the frame clock by the specified `duration` value. Args: qubits_or_frames (Union[Frame, list[Frame], QubitSet]): Qubits or frame(s) on which the delay needs to be introduced. duration (Union[float, FreeParameterExpression]): value (in seconds) defining the duration of the delay. + Returns: PulseSequence: self, with the instruction added. """ @@ -193,13 +187,12 @@ def delay( for frame in qubits_or_frames: self._frames[frame.id] = frame else: - physical_qubits = list(PhysicalQubits[int(x)] for x in qubits_or_frames) + physical_qubits = [PhysicalQubits[int(x)] for x in qubits_or_frames] self._program.delay(time=duration, qubits_or_frames=physical_qubits) return self def barrier(self, qubits_or_frames: Union[list[Frame], QubitSet]) -> PulseSequence: - """ - Adds an instruction to align the frame clocks to the latest time across all the specified + """Adds an instruction to align the frame clocks to the latest time across all the specified frames. Args: @@ -215,7 +208,7 @@ def barrier(self, qubits_or_frames: Union[list[Frame], QubitSet]) -> PulseSequen for frame in qubits_or_frames: self._frames[frame.id] = frame else: - physical_qubits = list(PhysicalQubits[int(x)] for x in qubits_or_frames) + physical_qubits = [PhysicalQubits[int(x)] for x in qubits_or_frames] self._program.barrier(qubits_or_frames=physical_qubits) return self @@ -241,8 +234,7 @@ def play(self, frame: Frame, waveform: Waveform) -> PulseSequence: return self def capture_v0(self, frame: Frame) -> PulseSequence: - """ - Adds an instruction to capture the bit output from measuring the specified frame. + """Adds an instruction to capture the bit output from measuring the specified frame. Args: frame (Frame): Frame on which the capture operation needs @@ -258,8 +250,7 @@ def capture_v0(self, frame: Frame) -> PulseSequence: return self def make_bound_pulse_sequence(self, param_values: dict[str, float]) -> PulseSequence: - """ - Binds FreeParameters based upon their name and values passed in. If parameters + """Binds FreeParameters based upon their name and values passed in. If parameters share the same name, all the parameters of that name will be set to the mapped value. Args: @@ -298,9 +289,9 @@ def make_bound_pulse_sequence(self, param_values: dict[str, float]) -> PulseSequ ]._to_oqpy_expression() new_pulse_sequence._capture_v0_count = self._capture_v0_count - new_pulse_sequence._free_parameters = set( - [p for p in self._free_parameters if p.name not in param_values] - ) + new_pulse_sequence._free_parameters = { + p for p in self._free_parameters if p.name not in param_values + } return new_pulse_sequence @@ -347,8 +338,8 @@ def _parse_arg_from_calibration_schema( self, argument: dict, waveforms: dict[Waveform], frames: dict[Frame] ) -> Any: nonprimitive_arg_type = { - "frame": getattr(frames, "get"), - "waveform": getattr(waveforms, "get"), + "frame": frames.get, + "waveform": waveforms.get, "expr": FreeParameterExpression, } if argument["type"] in nonprimitive_arg_type.keys(): @@ -360,17 +351,19 @@ def _parse_arg_from_calibration_schema( def _parse_from_calibration_schema( cls, calibration: dict, waveforms: dict[Waveform], frames: dict[Frame] ) -> PulseSequence: - """ - Parsing a JSON input based on https://github.com/aws/amazon-braket-schemas-python/blob/main/src/braket/device_schema/pulse/native_gate_calibrations_v1.py#L26. + """Parsing a JSON input based on https://github.com/aws/amazon-braket-schemas-python/blob/main/src/braket/device_schema/pulse/native_gate_calibrations_v1.py#L26. # noqa: E501 Args: calibration (dict): The pulse instruction to parse waveforms (dict[Waveform]): The waveforms supplied for the pulse sequences. frames (dict[Frame]): A dictionary of frame objects to use. + Raises: + ValueError: If the requested instruction has not been implemented for pulses. + Returns: PulseSequence: The parse sequence obtain from parsing a pulse instruction. - """ # noqa: E501 + """ calibration_sequence = cls() for instr in calibration: if hasattr(PulseSequence, f"{instr['name']}"): @@ -409,18 +402,20 @@ def _parse_from_calibration_schema( raise ValueError(f"The {instr['name']} instruction has not been implemented") return calibration_sequence - def __call__(self, arg: Any | None = None, **kwargs) -> PulseSequence: - """ - Implements the call function to easily make a bound PulseSequence. + def __call__( + self, arg: Any | None = None, **kwargs: Union[FreeParameter, str] + ) -> PulseSequence: + """Implements the call function to easily make a bound PulseSequence. Args: arg (Any | None): A value to bind to all parameters. Defaults to None and can be overridden if the parameter is in kwargs. + **kwargs (Union[FreeParameter, str]): Arbitrary keyword arguments. Returns: PulseSequence: A pulse sequence with the specified parameters bound. """ - param_values = dict() + param_values = {} if arg is not None: for param in self.parameters: param_values[str(param)] = arg @@ -428,7 +423,7 @@ def __call__(self, arg: Any | None = None, **kwargs) -> PulseSequence: param_values[str(key)] = val return self.make_bound_pulse_sequence(param_values) - def __eq__(self, other): + def __eq__(self, other: PulseSequence): sort_input_parameters = True return ( isinstance(other, PulseSequence) diff --git a/src/braket/pulse/waveforms.py b/src/braket/pulse/waveforms.py index 971321a71..9ca43050a 100644 --- a/src/braket/pulse/waveforms.py +++ b/src/braket/pulse/waveforms.py @@ -31,11 +31,10 @@ class Waveform(ABC): - """ - A waveform is a time-dependent envelope that can be used to emit signals on an output port + """A waveform is a time-dependent envelope that can be used to emit signals on an output port or receive signals from an input port. As such, when transmitting signals to the qubit, a frame determines time at which the waveform envelope is emitted, its carrier frequency, and - it’s phase offset. When capturing signals from a qubit, at minimum a frame determines the + it's phase offset. When capturing signals from a qubit, at minimum a frame determines the time at which the signal is captured. See https://openqasm.com/language/openpulse.html#waveforms for more details. """ @@ -47,32 +46,35 @@ def _to_oqpy_expression(self) -> OQPyExpression: @abstractmethod def sample(self, dt: float) -> np.ndarray: """Generates a sample of amplitudes for this Waveform based on the given time resolution. + Args: dt (float): The time resolution. + Returns: - ndarray: The sample amplitudes for this waveform. + np.ndarray: The sample amplitudes for this waveform. """ @staticmethod @abstractmethod def _from_calibration_schema(waveform_json: dict) -> Waveform: - """ - Parses a JSON input and returns the BDK waveform. See https://github.com/aws/amazon-braket-schemas-python/blob/main/src/braket/device_schema/pulse/native_gate_calibrations_v1.py#L104 + """Parses a JSON input and returns the BDK waveform. See https://github.com/aws/amazon-braket-schemas-python/blob/main/src/braket/device_schema/pulse/native_gate_calibrations_v1.py#L104 # noqa: E501 Args: waveform_json (dict): A JSON object with the needed parameters for making the Waveform. Returns: Waveform: A Waveform object parsed from the supplied JSON. - """ # noqa: E501 + """ class ArbitraryWaveform(Waveform): """An arbitrary waveform with amplitudes at each timestep explicitly specified using - an array.""" + an array. + """ def __init__(self, amplitudes: list[complex], id: Optional[str] = None): - """ + """Initializes an `ArbitraryWaveform`. + Args: amplitudes (list[complex]): Array of complex values specifying the waveform amplitude at each timestep. The timestep is determined by the sampling rate @@ -86,7 +88,7 @@ def __init__(self, amplitudes: list[complex], id: Optional[str] = None): def __repr__(self) -> str: return f"ArbitraryWaveform('id': {self.id}, 'amplitudes': {self.amplitudes})" - def __eq__(self, other): + def __eq__(self, other: ArbitraryWaveform): return isinstance(other, ArbitraryWaveform) and (self.amplitudes, self.id) == ( other.amplitudes, other.id, @@ -94,6 +96,7 @@ def __eq__(self, other): def _to_oqpy_expression(self) -> OQPyExpression: """Returns an OQPyExpression defining this waveform. + Returns: OQPyExpression: The OQPyExpression. """ @@ -101,10 +104,15 @@ def _to_oqpy_expression(self) -> OQPyExpression: def sample(self, dt: float) -> np.ndarray: """Generates a sample of amplitudes for this Waveform based on the given time resolution. + Args: dt (float): The time resolution. + + Raises: + NotImplementedError: This class does not implement sample. + Returns: - ndarray: The sample amplitudes for this waveform. + np.ndarray: The sample amplitudes for this waveform. """ raise NotImplementedError @@ -117,12 +125,14 @@ def _from_calibration_schema(waveform_json: dict) -> ArbitraryWaveform: class ConstantWaveform(Waveform, Parameterizable): """A constant waveform which holds the supplied `iq` value as its amplitude for the - specified length.""" + specified length. + """ def __init__( self, length: Union[float, FreeParameterExpression], iq: complex, id: Optional[str] = None ): - """ + """Initializes a `ConstantWaveform`. + Args: length (Union[float, FreeParameterExpression]): Value (in seconds) specifying the duration of the waveform. @@ -140,13 +150,20 @@ def __repr__(self) -> str: @property def parameters(self) -> list[Union[FreeParameterExpression, FreeParameter, float]]: """Returns the parameters associated with the object, either unbound free parameter - expressions or bound values.""" + expressions or bound values. + + Returns: + list[Union[FreeParameterExpression, FreeParameter, float]]: a list of parameters. + """ return [self.length] - def bind_values(self, **kwargs) -> ConstantWaveform: + def bind_values(self, **kwargs: Union[FreeParameter, str]) -> ConstantWaveform: """Takes in parameters and returns an object with specified parameters replaced with their values. + Args: + **kwargs (Union[FreeParameter, str]): Arbitrary keyword arguments. + Returns: ConstantWaveform: A copy of this waveform with the requested parameters bound. """ @@ -157,7 +174,7 @@ def bind_values(self, **kwargs) -> ConstantWaveform: } return ConstantWaveform(**constructor_kwargs) - def __eq__(self, other): + def __eq__(self, other: ConstantWaveform): return isinstance(other, ConstantWaveform) and (self.length, self.iq, self.id) == ( other.length, other.iq, @@ -166,6 +183,7 @@ def __eq__(self, other): def _to_oqpy_expression(self) -> OQPyExpression: """Returns an OQPyExpression defining this waveform. + Returns: OQPyExpression: The OQPyExpression. """ @@ -179,10 +197,12 @@ def _to_oqpy_expression(self) -> OQPyExpression: def sample(self, dt: float) -> np.ndarray: """Generates a sample of amplitudes for this Waveform based on the given time resolution. + Args: dt (float): The time resolution. + Returns: - ndarray: The sample amplitudes for this waveform. + np.ndarray: The sample amplitudes for this waveform. """ # Amplitudes should be gated by [0:self.length] sample_range = np.arange(0, self.length, dt) @@ -221,7 +241,8 @@ def __init__( zero_at_edges: bool = False, id: Optional[str] = None, ): - """ + """Initializes a `DragGaussianWaveform`. + Args: length (Union[float, FreeParameterExpression]): Value (in seconds) specifying the duration of the waveform. @@ -252,13 +273,17 @@ def __repr__(self) -> str: @property def parameters(self) -> list[Union[FreeParameterExpression, FreeParameter, float]]: """Returns the parameters associated with the object, either unbound free parameter - expressions or bound values.""" + expressions or bound values. + """ return [self.length, self.sigma, self.beta, self.amplitude] - def bind_values(self, **kwargs) -> DragGaussianWaveform: + def bind_values(self, **kwargs: Union[FreeParameter, str]) -> DragGaussianWaveform: """Takes in parameters and returns an object with specified parameters replaced with their values. + Args: + **kwargs (Union[FreeParameter, str]): Arbitrary keyword arguments. + Returns: DragGaussianWaveform: A copy of this waveform with the requested parameters bound. """ @@ -272,7 +297,7 @@ def bind_values(self, **kwargs) -> DragGaussianWaveform: } return DragGaussianWaveform(**constructor_kwargs) - def __eq__(self, other): + def __eq__(self, other: DragGaussianWaveform): return isinstance(other, DragGaussianWaveform) and ( self.length, self.sigma, @@ -284,6 +309,7 @@ def __eq__(self, other): def _to_oqpy_expression(self) -> OQPyExpression: """Returns an OQPyExpression defining this waveform. + Returns: OQPyExpression: The OQPyExpression. """ @@ -310,10 +336,12 @@ def _to_oqpy_expression(self) -> OQPyExpression: def sample(self, dt: float) -> np.ndarray: """Generates a sample of amplitudes for this Waveform based on the given time resolution. + Args: dt (float): The time resolution. + Returns: - ndarray: The sample amplitudes for this waveform. + np.ndarray: The sample amplitudes for this waveform. """ sample_range = np.arange(0, self.length, dt) t0 = self.length / 2 @@ -354,7 +382,8 @@ def __init__( zero_at_edges: bool = False, id: Optional[str] = None, ): - """ + """Initializes a `GaussianWaveform`. + Args: length (Union[float, FreeParameterExpression]): Value (in seconds) specifying the duration of the waveform. @@ -382,13 +411,17 @@ def __repr__(self) -> str: @property def parameters(self) -> list[Union[FreeParameterExpression, FreeParameter, float]]: """Returns the parameters associated with the object, either unbound free parameter - expressions or bound values.""" + expressions or bound values. + """ return [self.length, self.sigma, self.amplitude] - def bind_values(self, **kwargs) -> GaussianWaveform: + def bind_values(self, **kwargs: Union[FreeParameter, str]) -> GaussianWaveform: """Takes in parameters and returns an object with specified parameters replaced with their values. + Args: + **kwargs (Union[FreeParameter, str]): Arbitrary keyword arguments. + Returns: GaussianWaveform: A copy of this waveform with the requested parameters bound. """ @@ -401,7 +434,7 @@ def bind_values(self, **kwargs) -> GaussianWaveform: } return GaussianWaveform(**constructor_kwargs) - def __eq__(self, other): + def __eq__(self, other: GaussianWaveform): return isinstance(other, GaussianWaveform) and ( self.length, self.sigma, @@ -412,6 +445,7 @@ def __eq__(self, other): def _to_oqpy_expression(self) -> OQPyExpression: """Returns an OQPyExpression defining this waveform. + Returns: OQPyExpression: The OQPyExpression. """ @@ -436,10 +470,12 @@ def _to_oqpy_expression(self) -> OQPyExpression: def sample(self, dt: float) -> np.ndarray: """Generates a sample of amplitudes for this Waveform based on the given time resolution. + Args: dt (float): The time resolution. + Returns: - ndarray: The sample amplitudes for this waveform. + np.ndarray: The sample amplitudes for this waveform. """ sample_range = np.arange(0, self.length, dt) t0 = self.length / 2 @@ -466,7 +502,7 @@ def _from_calibration_schema(waveform_json: dict) -> GaussianWaveform: def _make_identifier_name() -> str: - return "".join([random.choice(string.ascii_letters) for _ in range(10)]) + return "".join([random.choice(string.ascii_letters) for _ in range(10)]) # noqa S311 def _parse_waveform_from_calibration_schema(waveform: dict) -> Waveform: diff --git a/src/braket/quantum_information/pauli_string.py b/src/braket/quantum_information/pauli_string.py index 1e4624e01..9064b942a 100644 --- a/src/braket/quantum_information/pauli_string.py +++ b/src/braket/quantum_information/pauli_string.py @@ -35,17 +35,19 @@ class PauliString: - """ - A lightweight representation of a Pauli string with its phase. - """ + """A lightweight representation of a Pauli string with its phase.""" def __init__(self, pauli_string: Union[str, PauliString]): - """ + """Initializes a `PauliString`. + Args: pauli_string (Union[str, PauliString]): The representation of the pauli word, either a string or another PauliString object. A valid string consists of an optional phase, specified by an optional sign +/- followed by an uppercase string in {I, X, Y, Z}. Example valid strings are: XYZ, +YIZY, -YX + + Raises: + ValueError: If the Pauli String is empty. """ if not pauli_string: raise ValueError("pauli_string must not be empty") @@ -343,7 +345,7 @@ def to_circuit(self) -> Circuit: circ = circ.z(qubit) return circ - def __eq__(self, other): + def __eq__(self, other: PauliString): if isinstance(other, PauliString): return ( self._phase == other._phase @@ -352,7 +354,7 @@ def __eq__(self, other): ) return False - def __getitem__(self, item): + def __getitem__(self, item: int): if item >= self._qubit_count: raise IndexError(item) return _PAULI_INDICES[self._nontrivial.get(item, "I")] diff --git a/src/braket/registers/qubit.py b/src/braket/registers/qubit.py index 479a453e3..4be98b640 100644 --- a/src/braket/registers/qubit.py +++ b/src/braket/registers/qubit.py @@ -20,19 +20,22 @@ class Qubit(int): - """ - A quantum bit index. The index of this qubit is locally scoped towards the contained + """A quantum bit index. The index of this qubit is locally scoped towards the contained circuit. This may not be the exact qubit index on the quantum device. """ - def __new__(cls, index: int): - """ + def __new__(cls, index: int) -> Qubit: + """Creates a new `Qubit`. + Args: index (int): Index of the qubit. Raises: ValueError: If `index` is less than zero. + Returns: + Qubit: Returns a new Qubit object. + Examples: >>> Qubit(0) >>> Qubit(1) @@ -51,8 +54,7 @@ def __str__(self): @staticmethod def new(qubit: QubitInput) -> Qubit: - """ - Helper constructor - if input is a `Qubit` it returns the same value, + """Helper constructor - if input is a `Qubit` it returns the same value, else a new `Qubit` is constructed. Args: @@ -61,7 +63,6 @@ def new(qubit: QubitInput) -> Qubit: Returns: Qubit: The qubit. """ - if isinstance(qubit, Qubit): return qubit else: diff --git a/src/braket/registers/qubit_set.py b/src/braket/registers/qubit_set.py index 0f9d0a7ac..e7bed6aa8 100644 --- a/src/braket/registers/qubit_set.py +++ b/src/braket/registers/qubit_set.py @@ -32,8 +32,7 @@ def _flatten(other: Any) -> Any: class QubitSet(IndexedSet): - """ - An ordered, unique set of quantum bits. + """An ordered, unique set of quantum bits. Note: QubitSet implements `__hash__()` but is a mutable object, therefore be careful when @@ -41,7 +40,8 @@ class QubitSet(IndexedSet): """ def __init__(self, qubits: QubitSetInput | None = None): - """ + """Initializes a `QubitSet`. + Args: qubits (QubitSetInput | None): Qubits to be included in the `QubitSet`. Default is `None`. @@ -63,13 +63,11 @@ def __init__(self, qubits: QubitSetInput | None = None): Qubit(2) Qubit(3) """ - _qubits = [Qubit.new(qubit) for qubit in _flatten(qubits)] if qubits is not None else None super().__init__(_qubits) def map(self, mapping: dict[QubitInput, QubitInput]) -> QubitSet: - """ - Creates a new `QubitSet` where this instance's qubits are mapped to the values in `mapping`. + """Creates a new `QubitSet` where this instance's qubits are mapped to the values in `mapping`. If this instance contains a qubit that is not in the `mapping` that qubit is not modified. Args: @@ -85,8 +83,7 @@ def map(self, mapping: dict[QubitInput, QubitInput]) -> QubitSet: >>> mapping = {0: 10, Qubit(1): Qubit(11)} >>> qubits.map(mapping) QubitSet([Qubit(10), Qubit(11)]) - """ - + """ # noqa E501 new_qubits = [mapping.get(qubit, qubit) for qubit in self] return QubitSet(new_qubits) diff --git a/src/braket/tasks/__init__.py b/src/braket/tasks/__init__.py index bb6cc6e77..d40b0547c 100644 --- a/src/braket/tasks/__init__.py +++ b/src/braket/tasks/__init__.py @@ -11,7 +11,7 @@ # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. -import braket.ipython_utils as ipython_utils +from braket import ipython_utils from braket.tasks.analog_hamiltonian_simulation_quantum_task_result import ( # noqa: F401 AnalogHamiltonianSimulationQuantumTaskResult, AnalogHamiltonianSimulationShotStatus, diff --git a/src/braket/tasks/analog_hamiltonian_simulation_quantum_task_result.py b/src/braket/tasks/analog_hamiltonian_simulation_quantum_task_result.py index abc39753d..ade8a0f79 100644 --- a/src/braket/tasks/analog_hamiltonian_simulation_quantum_task_result.py +++ b/src/braket/tasks/analog_hamiltonian_simulation_quantum_task_result.py @@ -38,7 +38,7 @@ class ShotResult: pre_sequence: np.ndarray = None post_sequence: np.ndarray = None - def __eq__(self, other) -> bool: + def __eq__(self, other: ShotResult) -> bool: if isinstance(other, ShotResult): return ( self.status == other.status @@ -54,7 +54,7 @@ class AnalogHamiltonianSimulationQuantumTaskResult: additional_metadata: AdditionalMetadata measurements: list[ShotResult] = None - def __eq__(self, other) -> bool: + def __eq__(self, other: AnalogHamiltonianSimulationQuantumTaskResult) -> bool: if isinstance(other, AnalogHamiltonianSimulationQuantumTaskResult): return ( self.task_metadata.id == other.task_metadata.id @@ -118,7 +118,6 @@ def get_counts(self) -> dict[str, int]: Returns None if none of shot measurements are successful. Only succesful shots contribute to the state count. """ - state_counts = Counter() states = ["e", "r", "g"] for shot in self.measurements: @@ -129,7 +128,7 @@ def get_counts(self) -> dict[str, int]: state_idx = [ 0 if pre_i == 0 else 1 if post_i == 0 else 2 for pre_i, post_i in zip(pre, post) ] - state = "".join(map(lambda s_idx: states[s_idx], state_idx)) + state = "".join(states[s_idx] for s_idx in state_idx) state_counts.update((state,)) return dict(state_counts) @@ -138,9 +137,8 @@ def get_avg_density(self) -> np.ndarray: """Get the average Rydberg state densities from the result Returns: - ndarray: The average densities from the result + np.ndarray: The average densities from the result """ - counts = self.get_counts() N_ryd, N_ground = [], [] diff --git a/src/braket/tasks/annealing_quantum_task_result.py b/src/braket/tasks/annealing_quantum_task_result.py index 1a5fbc2cb..bf5e9900d 100644 --- a/src/braket/tasks/annealing_quantum_task_result.py +++ b/src/braket/tasks/annealing_quantum_task_result.py @@ -13,10 +13,11 @@ from __future__ import annotations +from collections.abc import Generator from dataclasses import dataclass -from typing import List, Optional, Tuple +from typing import Optional -import numpy +import numpy as np from braket.annealing import ProblemType from braket.task_result import AdditionalMetadata, AnnealingTaskResult, TaskMetadata @@ -24,12 +25,11 @@ @dataclass class AnnealingQuantumTaskResult: - """ - Result of an annealing problem quantum task execution. This class is intended + """Result of an annealing problem quantum task execution. This class is intended to be initialized by a QuantumTask class. Args: - record_array (numpy.recarray): numpy array with keys 'solution' (numpy.ndarray) + record_array (np.recarray): numpy array with keys 'solution' (np.ndarray) where row is solution, column is value of the variable, 'solution_count' (numpy.ndarray) the number of times the solutions occurred, and 'value' (numpy.ndarray) the output or energy of the solutions. @@ -39,7 +39,7 @@ class AnnealingQuantumTaskResult: additional_metadata (AdditionalMetadata): Additional metadata about the quantum task """ - record_array: numpy.recarray + record_array: np.recarray variable_count: int problem_type: ProblemType task_metadata: TaskMetadata @@ -47,38 +47,37 @@ class AnnealingQuantumTaskResult: def data( self, - selected_fields: Optional[List[str]] = None, + selected_fields: Optional[list[str]] = None, sorted_by: str = "value", reverse: bool = False, - ) -> Tuple: - """ - Iterate over the data in record_array + ) -> Generator[tuple]: + """Yields the data in record_array Args: - selected_fields (Optional[List[str]]): selected fields to return. + selected_fields (Optional[list[str]]): selected fields to return. Options are 'solution', 'value', and 'solution_count'. Default is None. sorted_by (str): Sorts the data by this field. Options are 'solution', 'value', and 'solution_count'. Default is 'value'. reverse (bool): If True, returns the data in reverse order. Default is False. Yields: - Tuple: data in record_array + Generator[tuple]: data in record_array """ if selected_fields is None: selected_fields = ["solution", "value", "solution_count"] if sorted_by is None: - order = numpy.arange(len(self.record_array)) + order = np.arange(len(self.record_array)) else: - order = numpy.argsort(self.record_array[sorted_by]) + order = np.argsort(self.record_array[sorted_by]) if reverse: - order = numpy.flip(order) + order = np.flip(order) for i in order: yield tuple(self.record_array[field][i] for field in selected_fields) - def __eq__(self, other) -> bool: + def __eq__(self, other: AnnealingQuantumTaskResult) -> bool: if isinstance(other, AnnealingQuantumTaskResult): # __eq__ on numpy arrays results in an array of booleans and therefore can't use # the default dataclass __eq__ implementation. Override equals to check if all @@ -100,8 +99,7 @@ def __eq__(self, other) -> bool: @staticmethod def from_object(result: AnnealingTaskResult) -> AnnealingQuantumTaskResult: - """ - Create AnnealingQuantumTaskResult from AnnealingTaskResult object + """Create AnnealingQuantumTaskResult from AnnealingTaskResult object Args: result (AnnealingTaskResult): AnnealingTaskResult object @@ -114,8 +112,7 @@ def from_object(result: AnnealingTaskResult) -> AnnealingQuantumTaskResult: @staticmethod def from_string(result: str) -> AnnealingQuantumTaskResult: - """ - Create AnnealingQuantumTaskResult from string + """Create AnnealingQuantumTaskResult from string Args: result (str): JSON object string @@ -127,12 +124,12 @@ def from_string(result: str) -> AnnealingQuantumTaskResult: @classmethod def _from_object(cls, result: AnnealingTaskResult) -> AnnealingQuantumTaskResult: - solutions = numpy.asarray(result.solutions, dtype=int) - values = numpy.asarray(result.values, dtype=float) + solutions = np.asarray(result.solutions, dtype=int) + values = np.asarray(result.values, dtype=float) if not result.solutionCounts: - solution_counts = numpy.ones(len(solutions), dtype=int) + solution_counts = np.ones(len(solutions), dtype=int) else: - solution_counts = numpy.asarray(result.solutionCounts, dtype=int) + solution_counts = np.asarray(result.solutionCounts, dtype=int) record_array = AnnealingQuantumTaskResult._create_record_array( solutions, solution_counts, values ) @@ -150,15 +147,17 @@ def _from_object(cls, result: AnnealingTaskResult) -> AnnealingQuantumTaskResult @staticmethod def _create_record_array( - solutions: numpy.ndarray, solution_counts: numpy.ndarray, values: numpy.ndarray - ) -> numpy.recarray: - """ - Create a solutions record for AnnealingQuantumTaskResult + solutions: np.ndarray, solution_counts: np.ndarray, values: np.ndarray + ) -> np.recarray: + """Create a solutions record for AnnealingQuantumTaskResult Args: - solutions (numpy.ndarray): row is solution, column is value of the variable - solution_counts (numpy.ndarray): list of number of times the solutions occurred - values (numpy.ndarray): list of the output or energy of the solutions + solutions (np.ndarray): row is solution, column is value of the variable + solution_counts (np.ndarray): list of number of times the solutions occurred + values (np.ndarray): list of the output or energy of the solutions + + Returns: + np.recarray: A record array for solutions, value, and solution_count. """ num_solutions, variable_count = solutions.shape datatypes = [ @@ -167,7 +166,7 @@ def _create_record_array( ("solution_count", solution_counts.dtype), ] - record = numpy.rec.array(numpy.zeros(num_solutions, dtype=datatypes)) + record = np.rec.array(np.zeros(num_solutions, dtype=datatypes)) record["solution"] = solutions record["value"] = values record["solution_count"] = solution_counts diff --git a/src/braket/tasks/gate_model_quantum_task_result.py b/src/braket/tasks/gate_model_quantum_task_result.py index 631ca45e7..dec914ba7 100644 --- a/src/braket/tasks/gate_model_quantum_task_result.py +++ b/src/braket/tasks/gate_model_quantum_task_result.py @@ -36,8 +36,7 @@ @dataclass class GateModelQuantumTaskResult: - """ - Result of a gate model quantum task execution. This class is intended + """Result of a gate model quantum task execution. This class is intended to be initialized by a QuantumTask class. Args: @@ -96,16 +95,15 @@ class GateModelQuantumTaskResult: def __post_init__(self): if self.result_types is not None: - self._result_types_indices = dict( - (GateModelQuantumTaskResult._result_type_hash(rt.type), i) + self._result_types_indices = { + GateModelQuantumTaskResult._result_type_hash(rt.type): i for i, rt in enumerate(self.result_types) - ) + } else: self._result_types_indices = {} def get_value_by_result_type(self, result_type: ResultType) -> Any: - """ - Get value by result type. The result type must have already been + """Get value by result type. The result type must have already been requested in the circuit sent to the device for this quantum task result. Args: @@ -126,17 +124,16 @@ def get_value_by_result_type(self, result_type: ResultType) -> Any: except KeyError: raise ValueError( "Result type not found in result. " - + "Result types must be added to circuit before circuit is run on device." + "Result types must be added to circuit before circuit is run on device." ) - def __eq__(self, other) -> bool: + def __eq__(self, other: GateModelQuantumTaskResult) -> bool: if isinstance(other, GateModelQuantumTaskResult): return self.task_metadata.id == other.task_metadata.id return NotImplemented def get_compiled_circuit(self) -> Optional[str]: - """ - Get the compiled circuit, if one is available. + """Get the compiled circuit, if one is available. Returns: Optional[str]: The compiled circuit or None. @@ -153,11 +150,10 @@ def get_compiled_circuit(self) -> Optional[str]: @staticmethod def measurement_counts_from_measurements(measurements: np.ndarray) -> Counter: - """ - Creates measurement counts from measurements + """Creates measurement counts from measurements Args: - measurements (ndarray): 2d array - row is shot and column is qubit. + measurements (np.ndarray): 2d array - row is shot and column is qubit. Returns: Counter: A Counter of measurements. Key is the measurements in a big endian binary @@ -172,8 +168,7 @@ def measurement_counts_from_measurements(measurements: np.ndarray) -> Counter: def measurement_probabilities_from_measurement_counts( measurement_counts: Counter, ) -> dict[str, float]: - """ - Creates measurement probabilities from measurement counts + """Creates measurement probabilities from measurement counts Args: measurement_counts (Counter): A Counter of measurements. Key is the measurements @@ -195,8 +190,7 @@ def measurement_probabilities_from_measurement_counts( def measurements_from_measurement_probabilities( measurement_probabilities: dict[str, float], shots: int ) -> np.ndarray: - """ - Creates measurements from measurement probabilities. + """Creates measurements from measurement probabilities. Args: measurement_probabilities (dict[str, float]): A dictionary of probabilistic results. @@ -205,7 +199,7 @@ def measurements_from_measurement_probabilities( shots (int): number of iterations on device. Returns: - ndarray: A dictionary of probabilistic results. + np.ndarray: A dictionary of probabilistic results. Key is the measurements in a big endian binary string. Value is the probability the measurement occurred. """ @@ -220,8 +214,7 @@ def measurements_from_measurement_probabilities( @staticmethod def from_object(result: GateModelTaskResult) -> GateModelQuantumTaskResult: - """ - Create GateModelQuantumTaskResult from GateModelTaskResult object. + """Create GateModelQuantumTaskResult from GateModelTaskResult object. Args: result (GateModelTaskResult): GateModelTaskResult object @@ -237,8 +230,7 @@ def from_object(result: GateModelTaskResult) -> GateModelQuantumTaskResult: @staticmethod def from_string(result: str) -> GateModelQuantumTaskResult: - """ - Create GateModelQuantumTaskResult from string. + """Create GateModelQuantumTaskResult from string. Args: result (str): JSON object string, with GateModelQuantumTaskResult attributes as keys. @@ -350,8 +342,7 @@ def _from_dict_internal_simulator_only( @staticmethod def cast_result_types(gate_model_task_result: GateModelTaskResult) -> None: - """ - Casts the result types to the types expected by the SDK. + """Casts the result types to the types expected by the SDK. Args: gate_model_task_result (GateModelTaskResult): GateModelTaskResult representing the diff --git a/src/braket/tasks/local_quantum_task.py b/src/braket/tasks/local_quantum_task.py index 69a0f1bd6..8417c71b2 100644 --- a/src/braket/tasks/local_quantum_task.py +++ b/src/braket/tasks/local_quantum_task.py @@ -39,6 +39,11 @@ def __init__( @property def id(self) -> str: + """Gets the task ID. + + Returns: + str: The ID of the task. + """ return str(self._id) def cancel(self) -> None: @@ -46,6 +51,11 @@ def cancel(self) -> None: raise NotImplementedError("Cannot cancel completed local task") def state(self) -> str: + """Gets the state of the task. + + Returns: + str: Returns COMPLETED + """ return "COMPLETED" def result( @@ -57,8 +67,12 @@ def result( def async_result(self) -> asyncio.Task: """Get the quantum task result asynchronously. + + Raises: + NotImplementedError: Asynchronous local simulation unsupported + Returns: - Task: Get the quantum task result asynchronously. + asyncio.Task: Get the quantum task result asynchronously. """ # TODO: Allow for asynchronous simulation raise NotImplementedError("Asynchronous local simulation unsupported") diff --git a/src/braket/tasks/photonic_model_quantum_task_result.py b/src/braket/tasks/photonic_model_quantum_task_result.py index 4d2fa0201..59eba68ac 100644 --- a/src/braket/tasks/photonic_model_quantum_task_result.py +++ b/src/braket/tasks/photonic_model_quantum_task_result.py @@ -26,15 +26,14 @@ class PhotonicModelQuantumTaskResult: additional_metadata: AdditionalMetadata measurements: np.ndarray = None - def __eq__(self, other) -> bool: + def __eq__(self, other: PhotonicModelQuantumTaskResult) -> bool: if isinstance(other, PhotonicModelQuantumTaskResult): return self.task_metadata.id == other.task_metadata.id return NotImplemented @staticmethod def from_object(result: PhotonicModelTaskResult) -> PhotonicModelQuantumTaskResult: - """ - Create PhotonicModelQuantumTaskResult from PhotonicModelTaskResult object. + """Create PhotonicModelQuantumTaskResult from PhotonicModelTaskResult object. Args: result (PhotonicModelTaskResult): PhotonicModelTaskResult object diff --git a/src/braket/tasks/quantum_task.py b/src/braket/tasks/quantum_task.py index c306078ca..f07a1be7b 100644 --- a/src/braket/tasks/quantum_task.py +++ b/src/braket/tasks/quantum_task.py @@ -27,6 +27,7 @@ class QuantumTask(ABC): @abstractmethod def id(self) -> str: """Get the quantum task ID. + Returns: str: The quantum task ID. """ @@ -38,6 +39,7 @@ def cancel(self) -> None: @abstractmethod def state(self) -> str: """Get the state of the quantum task. + Returns: str: State of the quantum task. """ @@ -49,22 +51,23 @@ def result( GateModelQuantumTaskResult, AnnealingQuantumTaskResult, PhotonicModelQuantumTaskResult ]: """Get the quantum task result. + Returns: - Union[GateModelQuantumTaskResult, AnnealingQuantumTaskResult, PhotonicModelQuantumTaskResult]: # noqa - Get the quantum task result. Call async_result if you want the result in an + Union[GateModelQuantumTaskResult, AnnealingQuantumTaskResult, PhotonicModelQuantumTaskResult]: Get + the quantum task result. Call async_result if you want the result in an asynchronous way. - """ + """ # noqa E501 @abstractmethod def async_result(self) -> asyncio.Task: """Get the quantum task result asynchronously. + Returns: - Task: Get the quantum task result asynchronously. + asyncio.Task: Get the quantum task result asynchronously. """ - def metadata(self, use_cached_value: bool = False) -> dict[str, Any]: - """ - Get task metadata. + def metadata(self, use_cached_value: bool = False) -> dict[str, Any]: # noqa B027 + """Get task metadata. Args: use_cached_value (bool): If True, uses the value retrieved from the previous diff --git a/src/braket/tasks/quantum_task_batch.py b/src/braket/tasks/quantum_task_batch.py index ff0a0b82a..790f6e19a 100644 --- a/src/braket/tasks/quantum_task_batch.py +++ b/src/braket/tasks/quantum_task_batch.py @@ -31,7 +31,8 @@ def results( ] ]: """Get the quantum task results. + Returns: - list[Union[GateModelQuantumTaskResult, AnnealingQuantumTaskResult, PhotonicModelQuantumTaskResult]]:: # noqa - Get the quantum task results. - """ + list[Union[GateModelQuantumTaskResult, AnnealingQuantumTaskResult, PhotonicModelQuantumTaskResult]]: Get + the quantum task results. + """ # noqa: E501 diff --git a/src/braket/timings/time_series.py b/src/braket/timings/time_series.py index 9d2b9cf00..a558bec71 100644 --- a/src/braket/timings/time_series.py +++ b/src/braket/timings/time_series.py @@ -19,7 +19,6 @@ from decimal import Decimal from enum import Enum from numbers import Number -from typing import Union @dataclass @@ -105,6 +104,9 @@ def from_lists(times: list[float], values: list[float]) -> TimeSeries: Returns: TimeSeries: time series constructed from lists + + Raises: + ValueError: If the len of `times` does not equal len of `values`. """ if len(times) != len(values): raise ValueError( @@ -118,12 +120,12 @@ def from_lists(times: list[float], values: list[float]) -> TimeSeries: return ts @staticmethod - def constant_like(times: Union[list[float], TimeSeries], constant: float = 0.0) -> TimeSeries: + def constant_like(times: list | float | TimeSeries, constant: float = 0.0) -> TimeSeries: """Obtain a constant time series given another time series or the list of time points, - and the constant values + and the constant values. Args: - times (Union[list[float], TimeSeries]): list of time points or a time series + times (list | float | TimeSeries): list of time points or a time series constant (float): constant value Returns: @@ -154,6 +156,10 @@ def concatenate(self, other: TimeSeries) -> TimeSeries: Returns: TimeSeries: The concatenated time series. + Raises: + ValueError: If the timeseries is not empty and time points in the first + TimeSeries are not strictly smaller than in the second. + Example: :: time_series_1 = TimeSeries.from_lists(times=[0, 0.1], values=[1, 2]) @@ -165,7 +171,6 @@ def concatenate(self, other: TimeSeries) -> TimeSeries: concat_ts.times() = [0, 0.1, 0.2, 0.3] concat_ts.values() = [1, 2, 4, 5] """ - not_empty_ts = len(other.times()) * len(self.times()) != 0 if not_empty_ts and min(other.times()) <= max(self.times()): raise ValueError( @@ -202,6 +207,9 @@ def stitch( Returns: TimeSeries: The stitched time series. + Raises: + ValueError: If boundary is not one of {"mean", "left", "right"}. + Example (StitchBoundaryCondition.MEAN): :: time_series_1 = TimeSeries.from_lists(times=[0, 0.1], values=[1, 2]) @@ -229,7 +237,6 @@ def stitch( stitch_ts.times() = [0, 0.1, 0.3] stitch_ts.values() = [1, 4, 5] """ - if len(self.times()) == 0: return TimeSeries.from_lists(times=other.times(), values=other.values()) if len(other.times()) == 0: @@ -287,18 +294,20 @@ def periodic_signal(times: list[float], values: list[float], num_repeat: int = 1 Args: times (list[float]): List of time points in a single block values (list[float]): Values for the time series in a single block - num_repeat (int): Number of block repeatitions + num_repeat (int): Number of block repetitions + + Raises: + ValueError: If the first and last values are not the same Returns: TimeSeries: A new periodic time series. """ - if not (values[0] == values[-1]): - raise ValueError("The first and last values must coinscide to guarantee periodicity") + raise ValueError("The first and last values must coincide to guarantee periodicity") new_time_series = TimeSeries() repeating_block = TimeSeries.from_lists(times=times, values=values) - for index in range(num_repeat): + for _index in range(num_repeat): new_time_series = new_time_series.stitch(repeating_block) return new_time_series @@ -316,6 +325,9 @@ def trapezoidal_signal( slew_rate_max (float): The maximum slew rate time_separation_min (float): The minimum separation of time points + Raises: + ValueError: If the time separation is negative + Returns: TimeSeries: A trapezoidal time series @@ -324,7 +336,6 @@ def trapezoidal_signal( f(t) from t=0 to t=T, where T is the duration. We also assume the trapezoidal time series starts and ends at zero. """ - if area <= 0.0: raise ValueError("The area of the trapezoidal time series has to be positive.") if value_max <= 0.0: @@ -370,8 +381,7 @@ def trapezoidal_signal( # TODO: Verify if this belongs here. def _all_close(first: TimeSeries, second: TimeSeries, tolerance: Number = 1e-7) -> bool: - """ - Returns True if the times and values in two time series are all within (less than) + """Returns True if the times and values in two time series are all within (less than) a given tolerance range. The values in the TimeSeries must be numbers that can be subtracted from each-other, support getting the absolute value, and can be compared against the tolerance. diff --git a/src/braket/tracking/pricing.py b/src/braket/tracking/pricing.py index 2b049b251..c269208c2 100644 --- a/src/braket/tracking/pricing.py +++ b/src/braket/tracking/pricing.py @@ -53,9 +53,13 @@ def get_prices(self) -> None: text_response.readline() self._price_list = list(csv.DictReader(text_response)) - @lru_cache() - def price_search(self, **kwargs) -> list[dict[str, str]]: + @lru_cache + def price_search(self, **kwargs: str) -> list[dict[str, str]]: """Searches the price list for a given set of parameters. + + Args: + **kwargs (str): Arbitrary keyword arguments. + Returns: list[dict[str, str]]: The price list. """ diff --git a/src/braket/tracking/tracker.py b/src/braket/tracking/tracker.py index 84b294ad2..2f77eec66 100644 --- a/src/braket/tracking/tracker.py +++ b/src/braket/tracking/tracker.py @@ -30,8 +30,7 @@ class Tracker: - """ - Amazon Braket cost tracker. + """Amazon Braket cost tracker. Use this class to track costs incurred from quantum tasks on Amazon Braket. """ @@ -47,6 +46,7 @@ def __exit__(self, *args): def start(self) -> Tracker: """Start tracking resources with this tracker. + Returns: Tracker: self. """ @@ -54,6 +54,7 @@ def start(self) -> Tracker: def stop(self) -> Tracker: """Stop tracking resources with this tracker. + Returns: Tracker: self. """ @@ -61,14 +62,14 @@ def stop(self) -> Tracker: def receive_event(self, event: _TaskCreationEvent) -> None: """Process a Tack Creation Event. + Args: event (_TaskCreationEvent): The event to process. """ self._recieve_internal(event) def tracked_resources(self) -> list[str]: - """ - Resources tracked by this tracker. + """Resources tracked by this tracker. Returns: list[str]: The list of quantum task ids for quantum tasks tracked by this tracker. @@ -76,8 +77,7 @@ def tracked_resources(self) -> list[str]: return list(self._resources.keys()) def qpu_tasks_cost(self) -> Decimal: - """ - Estimate cost of all quantum tasks tracked by this tracker that use Braket qpu devices. + """Estimate cost of all quantum tasks tracked by this tracker that use Braket qpu devices. Note: Charges shown are estimates based on your Amazon Braket simulator and quantum processing unit (QPU) task usage. Estimated charges shown may differ from your actual @@ -95,8 +95,8 @@ def qpu_tasks_cost(self) -> Decimal: return total_cost def simulator_tasks_cost(self) -> Decimal: - """ - Estimate cost of all quantum tasks tracked by this tracker using Braket simulator devices. + """Estimate cost of all quantum tasks tracked by this tracker using Braket simulator + devices. Note: The cost of a simulator quantum task is not available until after the results for the task have been fetched. Call `result()` on an `AwsQuantumTask` before estimating its cost @@ -118,11 +118,10 @@ def simulator_tasks_cost(self) -> Decimal: return total_cost def quantum_tasks_statistics(self) -> dict[str, dict[str, Any]]: - """ - Get a summary of quantum tasks grouped by device. + """Get a summary of quantum tasks grouped by device. Returns: - dict[str,dict[str,Any]] : A dictionary where each key is a device arn, and maps to + dict[str, dict[str, Any]]: A dictionary where each key is a device arn, and maps to a dictionary sumarizing the quantum tasks run on the device. The summary includes the total shots sent to the device and the most recent status of the quantum tasks created on this device. For finished quantum tasks on simulator devices, the summary diff --git a/src/braket/tracking/tracking_context.py b/src/braket/tracking/tracking_context.py index 128af025d..37f4a3dc0 100644 --- a/src/braket/tracking/tracking_context.py +++ b/src/braket/tracking/tracking_context.py @@ -20,6 +20,7 @@ def __init__(self): def register_tracker(self, tracker: Tracker) -> None: # noqa F821 """Registers a tracker. + Args: tracker (Tracker): The tracker. """ @@ -27,6 +28,7 @@ def register_tracker(self, tracker: Tracker) -> None: # noqa F821 def deregister_tracker(self, tracker: Tracker) -> None: # noqa F821 """Deregisters a tracker. + Args: tracker (Tracker): The tracker. """ @@ -34,13 +36,19 @@ def deregister_tracker(self, tracker: Tracker) -> None: # noqa F821 def broadcast_event(self, event: _TrackingEvent) -> None: # noqa F821 """Broadcasts an event to all trackers. + Args: event (_TrackingEvent): The event to broadcast. """ for tracker in self._trackers: tracker.receive_event(event) - def active_trackers(self) -> None: + def active_trackers(self) -> set: + """Gets the active trackers. + + Returns: + set: The set of active trackers. + """ return self._trackers diff --git a/test/integ_tests/gate_model_device_testing_utils.py b/test/integ_tests/gate_model_device_testing_utils.py index 6ccd6f05b..63b03bfd6 100644 --- a/test/integ_tests/gate_model_device_testing_utils.py +++ b/test/integ_tests/gate_model_device_testing_utils.py @@ -139,7 +139,7 @@ def result_types_bell_pair_full_probability_testing(device: Device, run_kwargs: assert np.allclose( result.get_value_by_result_type(ResultType.Probability()), np.array([0.5, 0, 0, 0.5]), - **tol + **tol, ) @@ -154,7 +154,7 @@ def result_types_bell_pair_marginal_probability_testing(device: Device, run_kwar assert np.allclose( result.get_value_by_result_type(ResultType.Probability(target=0)), np.array([0.5, 0.5]), - **tol + **tol, ) @@ -592,7 +592,7 @@ def noisy_circuit_1qubit_noise_full_probability(device: Device, run_kwargs: Dict assert np.allclose( result.get_value_by_result_type(ResultType.Probability()), np.array([0.0, 0.1, 0, 0.9]), - **tol + **tol, ) @@ -611,7 +611,7 @@ def noisy_circuit_2qubit_noise_full_probability(device: Device, run_kwargs: Dict assert np.allclose( result.get_value_by_result_type(ResultType.Probability()), np.array([0.1, 0.0, 0, 0.9]), - **tol + **tol, ) @@ -671,7 +671,7 @@ def openqasm_noisy_circuit_1qubit_noise_full_probability( assert np.allclose( result.get_value_by_result_type(ResultType.Probability(target=[0, 1])), np.array([0.0, 0.1, 0, 0.9]), - **tol + **tol, ) diff --git a/test/unit_tests/braket/circuits/test_noises.py b/test/unit_tests/braket/circuits/test_noises.py index 2b55dfa4f..a9bd3f5a3 100644 --- a/test/unit_tests/braket/circuits/test_noises.py +++ b/test/unit_tests/braket/circuits/test_noises.py @@ -225,7 +225,7 @@ def multi_probability_invalid_input(**kwargs): "TwoDimensionalMatrixList": two_dimensional_matrix_list_valid_input, "DoubleTarget": double_target_valid_input, "DoubleControl": double_control_valid_input, - } + }, ) diff --git a/test/unit_tests/braket/devices/test_local_simulator.py b/test/unit_tests/braket/devices/test_local_simulator.py index a2203ee60..4877a0b8f 100644 --- a/test/unit_tests/braket/devices/test_local_simulator.py +++ b/test/unit_tests/braket/devices/test_local_simulator.py @@ -118,7 +118,7 @@ def run( shots: Optional[int], inputs: Optional[Dict[str, float]], *args, - **kwargs + **kwargs, ) -> Dict[str, Any]: self._shots = shots self._qubits = qubits