def test_run_gate_model():
    dummy = DummyCircuitSimulator()
    sim = LocalSimulator(dummy)
    task = sim.run(Circuit().h(0).cnot(0, 1), 10)
    dummy.assert_shots(10)
    dummy.assert_qubits(2)
    assert task.result() == GateModelQuantumTaskResult.from_object(GATE_MODEL_RESULT)
Esempio n. 2
0
def bell_state_example():
    # Our Quantum Circuit
    # (h) Apply the Hadamard gate to the first qubit, this puts it into superposition
    # (cnot) Apply a Controlled Not gate to the first qubit (control) and a second qubit (target)
    # This entagles the two qubits. This is known as the Bell State.

    bell_state = Circuit().h(0).cnot(0, 1)

    # AWS Braket can print a textual representation of your circuit
    print(bell_state)

    # This will run a quantum simulation on your local machine, try to keep below 20-ish qubits
    simulator = LocalSimulator()

    # AWS Braket simulations are ran async, but here we can block on the result for a local simulation.
    # Shots is unique to quantum computing, you must run the same algorithm multiple times to get ample
    # enough results for your probability distribution of results. This is where you decide the most
    # probable result of your algorithm, which may be the "right" result
    simulation = simulator.run(bell_state, shots=1000)
    result = simulation.result()

    # Measure our results
    counts = result.measurement_counts

    # What this displays is how often your entagled qubits ended up in the states of '11' or '00'.
    # This sums to the number of shots
    print(counts)

    return
Esempio n. 3
0
def test_run_program_model():
    dummy = DummyProgramSimulator()
    sim = LocalSimulator(dummy)
    task = sim.run(
        Program(source="""
qubit[2] q;
bit[2] c;

h q[0];
cnot q[0], q[1];

c = measure q;
"""))
    assert task.result() == GateModelQuantumTaskResult.from_object(
        GATE_MODEL_RESULT)
Esempio n. 4
0
    def test_convert_experiment(self):
        creg = qiskit.ClassicalRegister(3)
        qreg = qiskit.QuantumRegister(3)
        qc = qiskit.QuantumCircuit(qreg, creg, name='test')
        qc.h(0)
        qc.cx(0, 1)
        qc.ry(theta=numpy.pi / 2, qubit=2)
        qc.ccx(0, 2, 1)
        qiskit.circuit.measure.measure(qc, qreg, creg)
        # qiskit.circuit.measure.measure(qc, qreg[0:2], creg[1:3])
        # qiskit.circuit.measure.measure(qc, qreg[2], creg[0])

        qc_transpiled = qiskit.transpile(
            qc, basis_gates=['u1', 'u2', 'u3', 'cx', 'id'])
        qobj = qiskit.assemble(qc_transpiled, shots=100000)

        aws_qc: Circuit = convert_experiment(qobj.experiments[0])

        logging.info('Qiskit Circuit:\n' + str(qc.draw()))
        logging.info('Qiskit Circuit (transpiled):\n' +
                     str(qc_transpiled.draw(fold=200)))
        logging.info('Braket Circuit:\n' + str(aws_qc.diagram()))

        measured_qubits = set(
            [rt.target.item_list[0] for rt in aws_qc.result_types])
        self.assertTrue(set(range(3)) == measured_qubits)

        backend: AerBackend = qiskit.Aer.get_backend('qasm_simulator')
        qiskit_result: Result = backend.run(qobj).result()

        sim = LocalSimulator()
        task: LocalQuantumTask = sim.run(aws_qc, shots=100000)
        braket_result: GateModelQuantumTaskResult = task.result()
        qiskit_counts: Dict[str, int] = qiskit_result.get_counts()
        braket_counts = braket_result.measurement_counts
        # Braket has Big Endian, while qiskit uses Little Endian
        self.assertTrue(qiskit_counts.keys() == set(
            [k[::-1] for k in braket_counts.keys()]))
        self.assertTrue(
            all(
                numpy.abs(c / 100000 - 0.25) < 1e-2
                for c in qiskit_counts.values()))
        self.assertTrue(
            all(
                numpy.abs(c / 100000 - 0.25) < 1e-2
                for c in braket_counts.values()))
Esempio n. 5
0
def qice_simulation(circ: Circuit) -> int:
    local_sim = LocalSimulator()
    result = local_sim.run(circ, shots=1).result()
    counts = result.measurement_counts
    result_int = int(list(counts.keys())[0], 2)
    return result_int
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
#     http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.

from braket.circuits import Circuit, Noise
from braket.devices import LocalSimulator

device = LocalSimulator("braket_dm")

circuit = Circuit().x(0).x(1).bit_flip(0, probability=0.1)
print("First example: ")
print(circuit)
print(device.run(circuit, shots=1000).result().measurement_counts)


circuit = Circuit().x(0).x(1)
noise = Noise.BitFlip(probability=0.1)
circuit.apply_gate_noise(noise)
print("Second example: ")
print(circuit)
print(device.run(circuit, shots=1000).result().measurement_counts)
Esempio n. 7
0
from braket.circuits import Circuit

# 量子回路の組み立て
circuit = Circuit().h(0).cnot(0, 1)

# ## リスト6.2: 実行と結果取得(実行する毎に結果は変化します)

# In[2]:

from braket.devices import LocalSimulator

# デバイス指定
device = LocalSimulator()

# 実行と結果取得
task = device.run(circuit, shots=1000)  # 量子プログラムを実行
result = task.result()  # 結果を取得
counts = result.measurement_counts  # 各測定値を得た回数を取得
print(counts)  # 結果をテキスト表示

# ## リスト6.4: ヒストグラム表示(実行する毎に結果は変化します)

# In[3]:

import matplotlib.pyplot as plt

# ヒストグラム表示
plt.bar(counts.keys(), counts.values())
plt.xlabel('bitstrings')
plt.ylabel('counts')
# Example of result types for shots=0
bell = (
    Circuit()
    .h(0)
    .cnot(0, 1)
    .probability(target=[0])
    .expectation(observable=Observable.Z(), target=[1])
    .amplitude(state=["00"])
    .state_vector()
)

# State vector and amplitude can only be requested when shots=0 for a simulator
# When shots=0 for a simulator, probability, expectation, variance are the exact values,
# not calculated from measurements
# Users cannot request Sample as a result when shots=0
result = device.run(bell).result()
print("Marginal probability for target 0 in computational basis:", result.values[0])
print("Expectation of target 1 in the computational basis:", result.values[1])
print("Amplitude of state 00:", result.values[2])
print("State vector:", result.values[3])

print("\nExample for shots>0")
# Example of result types for shots > 0
bell = (
    Circuit()
    .h(0)
    .cnot(0, 1)
    .expectation(observable=Observable.Y() @ Observable.X(), target=[0, 1])
    .variance(observable=Observable.Y() @ Observable.X(), target=[0, 1])
    .sample(observable=Observable.Y() @ Observable.X(), target=[0, 1])
)
def test_run_qubit_gate_unsupported():
    sim = LocalSimulator(DummyAnnealingSimulator())
    sim.run(Circuit().h(0).cnot(0, 1), 1000)
def test_run_annealing_unsupported():
    sim = LocalSimulator(DummyCircuitSimulator())
    sim.run(Problem(ProblemType.ISING))
def test_run_unsupported_type():
    sim = LocalSimulator(DummyCircuitSimulator())
    sim.run("I'm unsupported")
def test_run_annealing():
    sim = LocalSimulator(DummyAnnealingSimulator())
    task = sim.run(Problem(ProblemType.ISING))
    assert task.result() == AnnealingQuantumTaskResult.from_object(
        ANNEALING_RESULT)
def test_run_gate_model_value_error():
    dummy = DummyCircuitSimulator()
    sim = LocalSimulator(dummy)
    sim.run(Circuit().h(0).cnot(0, 1))
def test_load_from_entry_point():
    sim = LocalSimulator("dummy")
    task = sim.run(Circuit().h(0).cnot(0, 1), 10)
    assert task.result() == GateModelQuantumTaskResult.from_object(
        GATE_MODEL_RESULT)
Esempio n. 15
0
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
#     http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.

from braket.circuits import Circuit
from braket.devices import LocalSimulator

device = LocalSimulator()

bell = Circuit().h(0).cnot(0, 1)
print(device.run(bell, shots=100).result().measurement_counts)
Esempio n. 16
0
def run(qcirc=None, shots=1, cid=None, backend=None, out_state=False):
    """ run the quantum circuit on braket_sv """

    if qcirc is None:
        raise ValueError("quantum circuit must be specified.")

    qubit_num = qcirc.qubit_num
    cmem_num = qcirc.cmem_num

    qc, measured_info = __convert_to_braket_circuit(qcirc, backend.product)

    if backend.product == 'braket_local':
        if backend.device == 'braket_sv':
            device = LocalSimulator(backend="braket_sv")
        else:
            raise ValueError("device:'{}' is unknown for product:'{}'.".format(
                backend.device, backend.product))
        task = device.run(qc, shots=shots)

    elif backend.product == 'braket_aws':
        if backend.device == 'sv1':
            device = AwsDevice(
                "arn:aws:braket:::device/quantum-simulator/amazon/sv1")
            s3_folder = (backend.config_braket['backet_name'], "sv1")
        elif backend.device == 'tn1':
            device = AwsDevice(
                "arn:aws:braket:::device/quantum-simulator/amazon/tn1")
            s3_folder = (backend.config_braket['backet_name'], "tn1")
        elif backend.device == 'dm1':
            device = AwsDevice(
                "arn:aws:braket:::device/quantum-simulator/amazon/dm1")
            s3_folder = (backend.config_braket['backet_name'], "dm1")
        else:
            raise ValueError("device:'{}' is unknown for product:'{}'.".format(
                backend.device, backend.product))

        if backend.config_braket['poll_timeout_seconds'] is None:
            task = device.run(qc, s3_folder, shots=shots)
        else:
            task = device.run(qc,
                              s3_folder,
                              shots=shots,
                              poll_timeout_seconds=backend.
                              config_braket['poll_timeout_seconds'])

    elif backend.product == 'braket_ionq':
        if backend.device == 'ionq':
            device = AwsDevice("arn:aws:braket:::device/qpu/ionq/ionQdevice")
            s3_folder = (backend.config_braket['backet_name'], "ionq")
        else:
            raise ValueError("device:'{}' is unknown for product:'{}'.".format(
                backend.device, backend.product))

        if backend.config_braket['poll_timeout_seconds'] is None:
            task = device.run(qc, s3_folder, shots=shots)
        else:
            task = device.run(qc,
                              s3_folder,
                              shots=shots,
                              poll_timeout_seconds=backend.
                              config_braket['poll_timeout_seconds'])

    elif backend.product == 'braket_rigetti':
        if backend.device == 'aspen_11':
            device = AwsDevice("arn:aws:braket:::device/qpu/rigetti/Aspen-11")
            s3_folder = (backend.config_braket['backet_name'], "aspen_11")
        elif backend.device == 'aspen_m_1':
            device = AwsDevice(
                "arn:aws:braket:us-west-1::device/qpu/rigetti/Aspen-M-1")
            s3_folder = (backend.config_braket['backet_name'], "aspen_m_1")
        else:
            raise ValueError("device:'{}' is unknown for product:'{}'.".format(
                backend.device, backend.product))

        if backend.config_braket['poll_timeout_seconds'] is None:
            task = device.run(qc, s3_folder, shots=shots)
        else:
            task = device.run(qc,
                              s3_folder,
                              shots=shots,
                              poll_timeout_seconds=backend.
                              config_braket['poll_timeout_seconds'])

    elif backend.product == 'braket_oqc':
        if backend.device == 'lucy':
            device = AwsDevice("arn:aws:braket:eu-west-2::device/qpu/oqc/Lucy")
            s3_folder = (backend.config_braket['backet_name'], "lucy")
        else:
            raise ValueError("device:'{}' is unknown for product:'{}'.".format(
                backend.device, backend.product))

        if backend.config_braket['poll_timeout_seconds'] is None:
            task = device.run(qc, s3_folder, shots=shots)
        else:
            task = device.run(qc,
                              s3_folder,
                              shots=shots,
                              poll_timeout_seconds=backend.
                              config_braket['poll_timeout_seconds'])

    result = task.result()
    frequency_org = result.measurement_counts

    # redefine the measured info
    # ex) mesure(qid=[0,1,2], cid=[2,1,0]) -> measured_info = [2, 1, 0, -1, -1,...]
    #     cid = [1,2] -> measured_info = [1, 0, -1, -1,...]
    #     cid = [2,0] -> measured_info = [0, -1, 1, -1, -1,...]
    #     cid = None -> cid = [0,1,2] -> measured_info = [2, 1, 0, -1, -1,...]

    if cid is None:
        cid = list(range(cmem_num))

    if cmem_num < len(cid):
        raise ValueError(
            "length of cid must be less than classical resister size of qcirc")

    for i, m in enumerate(measured_info):
        if m == -1:
            continue

        if m in cid:
            measured_info[i] = cid.index(m)
        else:
            measured_info[i] = -1

    # marginal frequency
    if set(measured_info) == {-1}:  # no qubits is measured
        frequency = None
    else:
        frequency = Counter()
        for mstr, freq in frequency_org.items():
            mlist = list(mstr)
            mlist_new = ['0'] * len(cid)
            for i, m in enumerate(measured_info):
                if m >= 0:
                    mlist_new[m] = mlist[i]
            mstr_new = "".join(mlist_new)
            frequency[mstr_new] += freq

    info = {'braket': result}

    result = Result()
    result.backend = backend
    result.qubit_num = qubit_num
    result.cmem_num = cmem_num
    result.cid = cid
    result.shots = shots
    result.frequency = frequency
    result.info = info

    return result