Ejemplo n.º 1
0
    def to_ir(
        self,
        target: QubitSet,
        ir_type: IRType = IRType.JAQCD,
        serialization_properties: SerializationProperties = None,
    ) -> Any:
        """Returns IR object of quantum operator and target

        Args:
            target (QubitSet): target qubit(s).
            ir_type(IRType) : The IRType to use for converting the gate object to its
                IR representation. Defaults to IRType.JAQCD.
            serialization_properties (SerializationProperties): 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

        Raises:
            ValueError: If the supplied `ir_type` is not supported, or if the supplied serialization
            properties don't correspond to the `ir_type`.
        """
        if ir_type == IRType.JAQCD:
            return self._to_jaqcd(target)
        elif ir_type == IRType.OPENQASM:
            if serialization_properties and not isinstance(
                    serialization_properties, OpenQASMSerializationProperties):
                raise ValueError(
                    "serialization_properties must be of type OpenQASMSerializationProperties "
                    "for IRType.OPENQASM.")
            return self._to_openqasm(
                target, serialization_properties
                or OpenQASMSerializationProperties())
        else:
            raise ValueError(f"Supplied ir_type {ir_type} is not supported.")
def test_from_circuit_with_verbatim(device_arn, device_parameters_class,
                                    disable_qubit_rewiring, aws_session):
    circ = Circuit().add_verbatim_box(Circuit().h(0))
    mocked_task_arn = "task-arn-1"
    aws_session.create_quantum_task.return_value = mocked_task_arn
    shots = 1337

    task = AwsQuantumTask.create(
        aws_session,
        device_arn,
        circ,
        S3_TARGET,
        shots,
        disable_qubit_rewiring=disable_qubit_rewiring,
    )
    assert task == AwsQuantumTask(mocked_task_arn, aws_session)

    serialization_properties = OpenQASMSerializationProperties(
        qubit_reference_type=QubitReferenceType.PHYSICAL)

    _assert_create_quantum_task_called_with(
        aws_session,
        device_arn,
        circ.to_ir(
            ir_type=IRType.OPENQASM,
            serialization_properties=serialization_properties,
        ).json(),
        S3_TARGET,
        shots,
        device_parameters_class(paradigmParameters=GateModelParameters(
            qubitCount=circ.qubit_count,
            disableQubitRewiring=disable_qubit_rewiring)),
    )
def test_from_circuit_with_disabled_rewiring(device_arn,
                                             device_parameters_class,
                                             aws_session, circuit):
    mocked_task_arn = "task-arn-1"
    aws_session.create_quantum_task.return_value = mocked_task_arn
    shots = 53

    task = AwsQuantumTask.create(aws_session,
                                 device_arn,
                                 circuit,
                                 S3_TARGET,
                                 shots,
                                 disable_qubit_rewiring=True)
    assert task == AwsQuantumTask(mocked_task_arn, aws_session)

    _assert_create_quantum_task_called_with(
        aws_session,
        device_arn,
        circuit.to_ir(
            ir_type=IRType.OPENQASM,
            serialization_properties=OpenQASMSerializationProperties(
                QubitReferenceType.PHYSICAL),
        ).json(),
        S3_TARGET,
        shots,
        device_parameters_class(paradigmParameters=GateModelParameters(
            qubitCount=circuit.qubit_count, disableQubitRewiring=True)),
    )
Ejemplo n.º 4
0
 def _to_openqasm(self, serialization_properties: OpenQASMSerializationProperties) -> str:
     if not self.target:
         return "#pragma braket result probability all"
     targets = ", ".join(
         serialization_properties.format_target(int(target)) for target in self.target
     )
     return f"#pragma braket result probability {targets}"
Ejemplo n.º 5
0
 def _to_openqasm(
         self, target: QubitSet,
         serialization_properties: OpenQASMSerializationProperties) -> str:
     target_qubit_0 = serialization_properties.format_target(int(target[0]))
     target_qubit_1 = serialization_properties.format_target(int(target[1]))
     return (
         f"#pragma braket noise two_qubit_dephasing({self.probability}) "
         f"{target_qubit_0}, {target_qubit_1}")
def _(
    circuit: Circuit,
    aws_session: AwsSession,
    create_task_kwargs: Dict[str, Any],
    device_arn: str,
    device_parameters: Union[
        dict, BraketSchemaBase],  # Not currently used for circuits
    disable_qubit_rewiring: bool,
    *args,
    **kwargs,
) -> AwsQuantumTask:
    validate_circuit_and_shots(circuit, create_task_kwargs["shots"])
    # TODO: Update this to use `deviceCapabilities` from Amazon Braket's GetDevice operation
    # in order to decide what parameters to build.
    paradigm_parameters = GateModelParameters(
        qubitCount=circuit.qubit_count,
        disableQubitRewiring=disable_qubit_rewiring)
    if "ionq" in device_arn:
        device_parameters = IonqDeviceParameters(
            paradigmParameters=paradigm_parameters)
    elif "rigetti" in device_arn:
        device_parameters = RigettiDeviceParameters(
            paradigmParameters=paradigm_parameters)
    elif "oqc" in device_arn:
        device_parameters = OqcDeviceParameters(
            paradigmParameters=paradigm_parameters)
    else:  # default to use simulator
        device_parameters = GateModelSimulatorDeviceParameters(
            paradigmParameters=paradigm_parameters)

    qubit_reference_type = QubitReferenceType.VIRTUAL

    if disable_qubit_rewiring or Instruction(
            StartVerbatimBox()) in circuit.instructions:
        qubit_reference_type = QubitReferenceType.PHYSICAL

    serialization_properties = OpenQASMSerializationProperties(
        qubit_reference_type=qubit_reference_type)

    create_task_kwargs.update({
        "action":
        circuit.to_ir(
            ir_type=IRType.OPENQASM,
            serialization_properties=serialization_properties,
        ).json(),
        "deviceParameters":
        device_parameters.json(),
    })
    task_arn = aws_session.create_quantum_task(**create_task_kwargs)
    return AwsQuantumTask(task_arn, aws_session, *args, **kwargs)
Ejemplo n.º 7
0
 def _to_openqasm(
         self, target: QubitSet,
         serialization_properties: OpenQASMSerializationProperties) -> str:
     matrix_list = ", ".join(
         np.array2string(
             matrix,
             separator=", ",
             formatter={
                 "all": lambda x: format_complex(x)
             },
         ).replace("\n", "") for matrix in self._matrices)
     qubit_list = ", ".join(
         serialization_properties.format_target(int(qubit))
         for qubit in target)
     return f"#pragma braket noise kraus({matrix_list}) {qubit_list}"
Ejemplo n.º 8
0
def test_to_ir():
    expected_target = QubitSet([0, 1])
    expected_ir = "foo bar value"
    expected_ir_type = IRType.OPENQASM
    expected_serialization_properties = OpenQASMSerializationProperties(
        qubit_reference_type=QubitReferenceType.PHYSICAL)

    class FooGate(Gate):
        def __init__(self):
            super().__init__(qubit_count=2, ascii_symbols=["foo", "bar"])

        def to_ir(self, target, ir_type, serialization_properties):
            assert target == expected_target
            assert ir_type == expected_ir_type
            assert serialization_properties == expected_serialization_properties
            return expected_ir

    instr = Instruction(FooGate(), expected_target)
    assert instr.to_ir(expected_ir_type,
                       expected_serialization_properties) == expected_ir
Ejemplo n.º 9
0
    def to_ir(
        self,
        target: QubitSet = None,
        ir_type: IRType = IRType.JAQCD,
        serialization_properties: SerializationProperties = None,
    ) -> Union[str, List[Union[str, List[List[List[float]]]]]]:
        """Returns the IR representation for the observable

        Args:
            target (QubitSet): target qubit(s). Defaults to None.
            ir_type(IRType) : The IRType to use for converting the result type object to its
                IR representation. Defaults to IRType.JAQCD.
            serialization_properties (SerializationProperties): 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:
            Union[str, List[Union[str, List[List[List[float]]]]]]: The IR representation for
            the observable.

        Raises:
            ValueError: If the supplied `ir_type` is not supported, or if the supplied serialization
            properties don't correspond to the `ir_type`.
        """
        if ir_type == IRType.JAQCD:
            return self._to_jaqcd()
        elif ir_type == IRType.OPENQASM:
            if serialization_properties and not isinstance(
                    serialization_properties, OpenQASMSerializationProperties):
                raise ValueError(
                    "serialization_properties must be of type OpenQASMSerializationProperties "
                    "for IRType.OPENQASM.")
            return self._to_openqasm(
                serialization_properties or OpenQASMSerializationProperties(),
                target)
        else:
            raise ValueError(f"Supplied ir_type {ir_type} is not supported.")
Ejemplo n.º 10
0
def test_ir_gate_level(testclass, subroutine_name, irclass, irsubclasses,
                       kwargs):
    expected = irclass(**create_valid_ir_input(irsubclasses))
    actual = testclass(
        **create_valid_gate_class_input(irsubclasses, **kwargs)).to_ir(
            **create_valid_target_input(irsubclasses))
    assert actual == expected


@pytest.mark.parametrize(
    "gate, target, serialization_properties, expected_ir",
    [
        (
            Gate.Rx(angle=0.17),
            [4],
            OpenQASMSerializationProperties(
                qubit_reference_type=QubitReferenceType.VIRTUAL),
            "rx(0.17) q[4];",
        ),
        (
            Gate.Rx(angle=0.17),
            [4],
            OpenQASMSerializationProperties(
                qubit_reference_type=QubitReferenceType.PHYSICAL),
            "rx(0.17) $4;",
        ),
        (
            Gate.X(),
            [4],
            OpenQASMSerializationProperties(
                qubit_reference_type=QubitReferenceType.VIRTUAL),
            "x q[4];",
Ejemplo n.º 11
0
 def _to_openqasm(
         self, target: QubitSet,
         serialization_properties: OpenQASMSerializationProperties) -> str:
     target_qubit = serialization_properties.format_target(int(target[0]))
     return f"#pragma braket noise bit_flip({self.probability}) {target_qubit}"
Ejemplo n.º 12
0
 def _to_openqasm(
         self, target: QubitSet,
         serialization_properties: OpenQASMSerializationProperties) -> str:
     target_qubit = serialization_properties.format_target(int(target[0]))
     return (f"#pragma braket noise pauli_channel"
             f"({self.probX}, {self.probY}, {self.probZ}) {target_qubit}")
Ejemplo n.º 13
0
 def _to_openqasm(
         self, target: QubitSet,
         serialization_properties: OpenQASMSerializationProperties) -> str:
     target_qubit = serialization_properties.format_target(int(target[0]))
     return f"#pragma braket noise phase_damping({self.gamma}) {target_qubit}"
Ejemplo n.º 14
0
 def _to_openqasm(
         self, target: QubitSet,
         serialization_properties: OpenQASMSerializationProperties) -> str:
     target_qubit = serialization_properties.format_target(int(target[0]))
     return ("#pragma braket noise generalized_amplitude_damping("
             f"{self.gamma}, {self.probability}) {target_qubit}")