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
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)
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)
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()))
def __init__( self, wires: Union[int, Iterable], backend: Union[str, BraketSimulator] = "default", *, shots: int = 0, **run_kwargs, ): device = LocalSimulator(backend) super().__init__(wires, device, shots=shots, **run_kwargs)
def test_run_unsupported_type(): sim = LocalSimulator(DummyCircuitSimulator()) sim.run("I'm unsupported")
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
result_types_hermitian_testing, result_types_noncommuting_all, result_types_noncommuting_flipped_targets_testing, result_types_noncommuting_testing, result_types_nonzero_shots_bell_pair_testing, result_types_tensor_hermitian_hermitian_testing, result_types_tensor_x_y_testing, result_types_tensor_y_hermitian_testing, result_types_tensor_z_h_y_testing, result_types_tensor_z_hermitian_testing, result_types_tensor_z_z_testing, ) from braket.devices import LocalSimulator DEVICE = LocalSimulator("braket_dm") SHOTS = 8000 def test_no_result_types_bell_pair(): no_result_types_bell_pair_testing(DEVICE, {"shots": SHOTS}) def test_qubit_ordering(): qubit_ordering_testing(DEVICE, {"shots": SHOTS}) def test_result_types_nonzero_shots_bell_pair(): result_types_nonzero_shots_bell_pair_testing(DEVICE, {"shots": SHOTS})
# # 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, Observable from braket.devices import LocalSimulator device = LocalSimulator() print("Example for shots=0") # Result types can be requested in the circuit # 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
def test_local_simulator_device_names(backend, device_name): local_simulator_device = LocalSimulator(backend) assert local_simulator_device.name == device_name
def test_properties(): dummy = DummyCircuitSimulator() sim = LocalSimulator(dummy) expected_properties = dummy.properties assert sim.properties == expected_properties
# 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)
def test_local_simulator_device_names(backend, device_name, caplog): local_simulator_device = LocalSimulator(backend) assert local_simulator_device.name == device_name assert not caplog.text
def __init__( self, local: bool = False, s3_bucket: str = "", s3_folder: str = "", device_type: str = "quantum-simulator", provider: str = "amazon", device: str = "sv1", ): """ Construct a new braket backend. If `local=True`, other parameters are ignored. :param local: use simulator running on local machine :param s3_bucket: name of S3 bucket to store results :param s3_folder: name of folder ("key") in S3 bucket to store results in :param device_type: device type from device ARN (e.g. "qpu") :param provider: provider name from device ARN (e.g. "ionq", "rigetti", ...) :paran device: device name from device ARN (e.g. "ionQdevice", "Aspen-8", ...) """ super().__init__() if local: self._device = LocalSimulator() self._device_type = _DeviceType.LOCAL else: self._device = AwsDevice( "arn:aws:braket:::" + "/".join(["device", device_type, provider, device])) self._s3_dest = (s3_bucket, s3_folder) aws_device_type = self._device.type if aws_device_type == AwsDeviceType.SIMULATOR: self._device_type = _DeviceType.SIMULATOR elif aws_device_type == AwsDeviceType.QPU: self._device_type = _DeviceType.QPU else: raise ValueError(f"Unsupported device type {aws_device_type}") props = self._device.properties.dict() paradigm = props["paradigm"] n_qubits = paradigm["qubitCount"] connectivity_graph = None # None means "fully connected" if self._device_type == _DeviceType.QPU: connectivity = paradigm["connectivity"] if connectivity["fullyConnected"]: self._all_qubits: List = list(range(n_qubits)) else: connectivity_graph = connectivity["connectivityGraph"] # Convert strings to ints connectivity_graph = dict( (int(k), [int(v) for v in l]) for k, l in connectivity_graph.items()) self._all_qubits = sorted(connectivity_graph.keys()) if n_qubits < len(self._all_qubits): # This can happen, at least on rigetti devices, and causes errors. # As a kludgy workaround, remove some qubits from the architecture. self._all_qubits = self._all_qubits[:( n_qubits - len(self._all_qubits))] connectivity_graph = dict( (k, [v for v in l if v in self._all_qubits]) for k, l in connectivity_graph.items() if k in self._all_qubits) self._characteristics: Optional[Dict] = props["provider"] else: self._all_qubits = list(range(n_qubits)) self._characteristics = None device_info = props["action"][DeviceActionType.JAQCD] supported_ops = set(op.lower() for op in device_info["supportedOperations"]) supported_result_types = device_info["supportedResultTypes"] self._result_types = set() for rt in supported_result_types: rtname = rt["name"] rtminshots = rt["minShots"] rtmaxshots = rt["maxShots"] self._result_types.add(rtname) if rtname == "StateVector": self._supports_state = True # Always use n_shots = 0 for StateVector elif rtname == "Amplitude": pass # Always use n_shots = 0 for Amplitude elif rtname == "Probability": self._probability_min_shots = rtminshots self._probability_max_shots = rtmaxshots elif rtname == "Expectation": self._supports_expectation = True self._expectation_allows_nonhermitian = False self._expectation_min_shots = rtminshots self._expectation_max_shots = rtmaxshots elif rtname == "Sample": self._supports_shots = True self._supports_counts = True self._sample_min_shots = rtminshots self._sample_max_shots = rtmaxshots elif rtname == "Variance": self._variance_min_shots = rtminshots self._variance_max_shots = rtmaxshots self._multiqs = set() self._singleqs = set() if not {"cnot", "rx", "rz"} <= supported_ops: # This is so that we can define RebaseCustom without prior knowledge of the # gate set. We could do better than this, by having a few different options # for the CX- and tk1-replacement circuits. But it seems all existing # backends support these gates. raise NotImplementedError( "Device must support cnot, rx and rz gates.") for t in supported_ops: tkt = _gate_types[t] if tkt is not None: if t in _multiq_gate_types: if self._device_type == _DeviceType.QPU and t in [ "ccnot", "cswap" ]: # FullMappingPass can't handle 3-qubit gates, so ignore them. continue self._multiqs.add(tkt) else: self._singleqs.add(tkt) self._req_preds = [ NoClassicalControlPredicate(), NoFastFeedforwardPredicate(), NoMidMeasurePredicate(), NoSymbolsPredicate(), GateSetPredicate(self._multiqs | self._singleqs), MaxNQubitsPredicate(n_qubits), ] if connectivity_graph is None: arch = FullyConnected(n_qubits) else: arch = Architecture([(k, v) for k, l in connectivity_graph.items() for v in l]) if self._device_type == _DeviceType.QPU: assert self._characteristics is not None node_errs = {} edge_errs = {} schema = self._characteristics["braketSchemaHeader"] if schema == IONQ_SCHEMA: fid = self._characteristics["fidelity"] mean_1q_err = 1 - fid["1Q"]["mean"] mean_2q_err = 1 - fid["2Q"]["mean"] err_1q_cont = QubitErrorContainer(self._singleqs) for optype in self._singleqs: err_1q_cont.add_error((optype, mean_1q_err)) err_2q_cont = QubitErrorContainer(self._multiqs) for optype in self._multiqs: err_2q_cont.add_error((optype, mean_2q_err)) for node in arch.nodes: node_errs[node] = err_1q_cont for coupling in arch.coupling: edge_errs[coupling] = err_2q_cont elif schema == RIGETTI_SCHEMA: specs = self._characteristics["specs"] specs1q, specs2q = specs["1Q"], specs["2Q"] for node in arch.nodes: nodespecs = specs1q[f"{node.index[0]}"] err_1q_cont = QubitErrorContainer(self._singleqs) for optype in self._singleqs: err_1q_cont.add_error( (optype, 1 - nodespecs.get("f1QRB", 1))) err_1q_cont.add_readout(nodespecs.get("fRO", 1)) node_errs[node] = err_1q_cont for coupling in arch.coupling: node0, node1 = coupling n0, n1 = node0.index[0], node1.index[0] couplingspecs = specs2q[f"{min(n0,n1)}-{max(n0,n1)}"] err_2q_cont = QubitErrorContainer({OpType.CZ}) err_2q_cont.add_error( (OpType.CZ, 1 - couplingspecs.get("fCZ", 1))) edge_errs[coupling] = err_2q_cont self._tket_device = Device(node_errs, edge_errs, arch) if connectivity_graph is not None: self._req_preds.append(ConnectivityPredicate( self._tket_device)) else: self._tket_device = None self._rebase_pass = RebaseCustom( self._multiqs, Circuit(), self._singleqs, lambda a, b, c: Circuit(1).Rz(c, 0).Rx(b, 0).Rz(a, 0), ) self._squash_pass = SquashCustom( self._singleqs, lambda a, b, c: Circuit(1).Rz(c, 0).Rx(b, 0).Rz(a, 0), )
def test_registered_backends(): assert LocalSimulator.registered_backends() == { "dummy", "dummy_oq3", "dummy_jaqcd" }
def test_run_annealing_unsupported(): sim = LocalSimulator(DummyCircuitSimulator()) sim.run(Problem(ProblemType.ISING))
def test_run_qubit_gate_unsupported(): sim = LocalSimulator(DummyAnnealingSimulator()) sim.run(Circuit().h(0).cnot(0, 1), 1000)
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)
result_types_noncommuting_flipped_targets_testing, result_types_noncommuting_testing, result_types_nonzero_shots_bell_pair_testing, result_types_observable_not_in_instructions, result_types_tensor_hermitian_hermitian_testing, result_types_tensor_x_y_testing, result_types_tensor_y_hermitian_testing, result_types_tensor_z_h_y_testing, result_types_tensor_z_hermitian_testing, result_types_tensor_z_z_testing, result_types_zero_shots_bell_pair_testing, ) from braket.devices import LocalSimulator DEVICE = LocalSimulator() SHOTS = 8000 def test_multithreaded_bell_pair(): multithreaded_bell_pair_testing(DEVICE, {"shots": SHOTS}) def test_no_result_types_bell_pair(): no_result_types_bell_pair_testing(DEVICE, {"shots": SHOTS}) def test_qubit_ordering(): qubit_ordering_testing(DEVICE, {"shots": SHOTS})
def test_run_gate_model_value_error(): dummy = DummyCircuitSimulator() sim = LocalSimulator(dummy) sim.run(Circuit().h(0).cnot(0, 1))
def test_run_annealing(): sim = LocalSimulator(DummyAnnealingSimulator()) task = sim.run(Problem(ProblemType.ISING)) assert task.result() == AnnealingQuantumTaskResult.from_object( ANNEALING_RESULT)
def test_registered_backends(): assert LocalSimulator.registered_backends() == {"dummy"}
# In[1]: 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())
def test_init_invalid_backend_type(): LocalSimulator(1234)
# 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)
def test_init_unregistered_backend(): LocalSimulator("foo")
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
# In[1]: get_ipython().system('pip install amazon-braket-sdk') # # 1量子ビットの量子回路 # In[2]: from braket.circuits import Circuit from braket.devices import LocalSimulator device = LocalSimulator() circuit = Circuit().h(0) print(circuit) # In[3]: from braket.circuits import Circuit from braket.devices import LocalSimulator device = LocalSimulator() circuit = Circuit().x(0)