repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.pulse_v2 import draw from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() qc = transpile(qc, FakeBoeblingen(), layout_method='trivial') sched = schedule(qc, FakeBoeblingen()) draw(sched, backend=FakeBoeblingen())
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2024. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Sampler Pub class """ from __future__ import annotations from collections.abc import Mapping from numbers import Integral from typing import Tuple, Union from qiskit import QuantumCircuit from qiskit.circuit import CircuitInstruction from .bindings_array import BindingsArray, BindingsArrayLike from .shape import ShapedMixin # Public API classes __all__ = ["SamplerPubLike"] class SamplerPub(ShapedMixin): """Pub (Primitive Unified Bloc) for a Sampler. Pub is composed of tuple (circuit, parameter_values, shots). If shots are provided this number of shots will be run with the sampler, if ``shots=None`` the number of run shots is determined by the sampler. """ def __init__( self, circuit: QuantumCircuit, parameter_values: BindingsArray | None = None, shots: int | None = None, validate: bool = True, ): """Initialize a sampler pub. Args: circuit: A quantum circuit. parameter_values: A bindings array. shots: A specific number of shots to run with. This value takes precedence over any value owed by or supplied to a sampler. validate: If ``True``, the input data is validated during initialization. """ super().__init__() self._circuit = circuit self._parameter_values = parameter_values or BindingsArray() self._shots = shots self._shape = self._parameter_values.shape if validate: self.validate() @property def circuit(self) -> QuantumCircuit: """A quantum circuit.""" return self._circuit @property def parameter_values(self) -> BindingsArray: """A bindings array.""" return self._parameter_values @property def shots(self) -> int | None: """An specific number of shots to run with (optional). This value takes precedence over any value owed by or supplied to a sampler. """ return self._shots @classmethod def coerce(cls, pub: SamplerPubLike, shots: int | None = None) -> SamplerPub: """Coerce a :class:`~.SamplerPubLike` object into a :class:`~.SamplerPub` instance. Args: pub: An object to coerce. shots: An optional default number of shots to use if not already specified by the pub-like object. Returns: A coerced sampler pub. """ # Validate shots kwarg if provided if shots is not None: if not isinstance(shots, Integral) or isinstance(shots, bool): raise TypeError("shots must be an integer") if shots <= 0: raise ValueError("shots must be positive") if isinstance(pub, SamplerPub): if pub.shots is None and shots is not None: return cls( circuit=pub.circuit, parameter_values=pub.parameter_values, shots=shots, validate=False, # Assume Pub is already validated ) return pub if isinstance(pub, QuantumCircuit): return cls(circuit=pub, shots=shots, validate=True) if isinstance(pub, CircuitInstruction): raise ValueError( f"An invalid Sampler pub-like was given ({type(pub)}). " "If you want to run a single circuit, " "you need to wrap it with `[]` like `sampler.run([circuit])` " "instead of `sampler.run(circuit)`." ) if len(pub) not in [1, 2, 3]: raise ValueError( f"The length of pub must be 1, 2 or 3, but length {len(pub)} is given." ) circuit = pub[0] if len(pub) > 1 and pub[1] is not None: values = pub[1] if not isinstance(values, (BindingsArray, Mapping)): values = {tuple(circuit.parameters): values} parameter_values = BindingsArray.coerce(values) else: parameter_values = None if len(pub) > 2 and pub[2] is not None: shots = pub[2] return cls(circuit=circuit, parameter_values=parameter_values, shots=shots, validate=True) def validate(self): """Validate the pub.""" if not isinstance(self.circuit, QuantumCircuit): raise TypeError("circuit must be QuantumCircuit.") self.parameter_values.validate() if self.shots is not None: if not isinstance(self.shots, Integral) or isinstance(self.shots, bool): raise TypeError("shots must be an integer") if self.shots <= 0: raise ValueError("shots must be positive") # Cross validate circuits and parameter values num_parameters = self.parameter_values.num_parameters if num_parameters != self.circuit.num_parameters: message = ( f"The number of values ({num_parameters}) does not match " f"the number of parameters ({self.circuit.num_parameters}) for the circuit." ) if num_parameters == 0: message += ( " Note that if you want to run a single pub, you need to wrap it with `[]` like " "`sampler.run([(circuit, param_values)])` instead of " "`sampler.run((circuit, param_values))`." ) raise ValueError(message) SamplerPubLike = Union[ QuantumCircuit, Tuple[QuantumCircuit], Tuple[QuantumCircuit, BindingsArrayLike], Tuple[QuantumCircuit, BindingsArrayLike, Union[Integral, None]], ] """A Pub (Primitive Unified Bloc) for a Sampler. A fully specified sample Pub is a tuple ``(circuit, parameter_values, shots)``. If shots are provided this number of shots will be run with the sampler, if ``shots=None`` the number of run shots is determined by the sampler. .. note:: A Sampler Pub can also be initialized in the following formats which will be converted to the full Pub tuple: * ``circuit`` * ``(circuit,)`` * ``(circuit, parameter_values)`` """
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
MonitSharma
# importing Qiskit from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, transpile # import basic plot tools from qiskit.visualization import plot_histogram from qiskit_textbook.tools import simon_oracle b = '110' n = len(b) simon_circuit = QuantumCircuit(n*2, n) # Apply Hadamard gates before querying the oracle simon_circuit.h(range(n)) # Apply barrier for visual separation simon_circuit.barrier() simon_circuit = simon_circuit.compose(simon_oracle(b)) # Apply barrier for visual separation simon_circuit.barrier() # Apply Hadamard gates to the input register simon_circuit.h(range(n)) # Measure qubits simon_circuit.measure(range(n), range(n)) simon_circuit.draw("mpl") # use local simulator aer_sim = Aer.get_backend('aer_simulator') results = aer_sim.run(simon_circuit).result() counts = results.get_counts() print(f"Measured output: {counts}") plot_histogram(counts) from qiskit import QuantumCircuit, Aer, transpile, assemble from qiskit.visualization import plot_histogram # Function to create Simon's oracle for a given hidden string 's' def simon_oracle(s): n = len(s) oracle_circuit = QuantumCircuit(n*2, n) # Apply CNOT gates according to the hidden string 's' for qubit in range(n): if s[qubit] == '1': oracle_circuit.cx(qubit, n + qubit) return oracle_circuit # Hidden string 'b' b = '1101' # Number of qubits n = len(b) # Create a quantum circuit simon_circuit = QuantumCircuit(n*2, n) # Apply Hadamard gates to the first n qubits simon_circuit.h(range(n)) # Apply a barrier for visual separation simon_circuit.barrier() # Compose the circuit with the Simon oracle for the given hidden string 'b' simon_circuit = simon_circuit.compose(simon_oracle(b)) # Apply a barrier for visual separation simon_circuit.barrier() # Apply Hadamard gates to the first n qubits simon_circuit.h(range(n)) # Measure the qubits simon_circuit.measure(range(n), range(n)) # Visualize the circuit simon_circuit.draw("mpl") # Transpile the circuit for the simulator simon_circuit = transpile(simon_circuit, Aer.get_backend('qasm_simulator')) # Run the simulation simulator = Aer.get_backend('qasm_simulator') result = simulator.run(simon_circuit).result() # Display the measured output counts = result.get_counts(simon_circuit) print(f"Measured output: {counts}") # Plot the results plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(3, 'q') anc = QuantumRegister(1, 'ancilla') cr = ClassicalRegister(3, 'c') qc = QuantumCircuit(qr, anc, cr) qc.x(anc[0]) qc.h(anc[0]) qc.h(qr[0:3]) qc.cx(qr[0:3], anc[0]) qc.h(qr[0:3]) qc.barrier(qr) qc.measure(qr, cr) qc.draw('mpl')
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
https://github.com/AnikenC/JaxifiedQiskit
AnikenC
# All Imports import numpy as np import matplotlib.pyplot as plt import sympy as sym import qiskit from qiskit import pulse from qiskit_dynamics import Solver, DynamicsBackend from qiskit_dynamics.pulse import InstructionToSignals from qiskit_dynamics.array import Array from qiskit.quantum_info import Statevector, DensityMatrix, Operator, SparsePauliOp from qiskit.circuit.parameter import Parameter import jax import jax.numpy as jnp from jax import jit, vmap, block_until_ready, config import chex from typing import Optional, Union Array.set_default_backend('jax') config.update('jax_enable_x64', True) config.update('jax_platform_name', 'cpu') # Constructing a Two Qutrit Hamiltonian dim = 3 v0 = 4.86e9 anharm0 = -0.32e9 r0 = 0.22e9 v1 = 4.97e9 anharm1 = -0.32e9 r1 = 0.26e9 J = 0.002e9 a = np.diag(np.sqrt(np.arange(1, dim)), 1) adag = np.diag(np.sqrt(np.arange(1, dim)), -1) N = np.diag(np.arange(dim)) ident = np.eye(dim, dtype=complex) full_ident = np.eye(dim**2, dtype=complex) N0 = np.kron(ident, N) N1 = np.kron(N, ident) a0 = np.kron(ident, a) a1 = np.kron(a, ident) a0dag = np.kron(ident, adag) a1dag = np.kron(adag, ident) static_ham0 = 2 * np.pi * v0 * N0 + np.pi * anharm0 * N0 * (N0 - full_ident) static_ham1 = 2 * np.pi * v1 * N1 + np.pi * anharm1 * N1 * (N1 - full_ident) static_ham_full = static_ham0 + static_ham1 + 2 * np.pi * J * ((a0 + a0dag) @ (a1 + a1dag)) drive_op0 = 2 * np.pi * r0 * (a0 + a0dag) drive_op1 = 2 * np.pi * r1 * (a1 + a1dag) batchsize = 400 amp_vals = jnp.linspace(0.5, 0.99, batchsize, dtype=jnp.float64).reshape(-1, 1) sigma_vals = jnp.linspace(20, 80, batchsize, dtype=jnp.int8).reshape(-1, 1) freq_vals = jnp.linspace(-0.5, 0.5, batchsize, dtype=jnp.float64).reshape(-1, 1) * 1e6 batch_params = jnp.concatenate((amp_vals, sigma_vals, freq_vals), axis=-1) batch_y0 = jnp.tile(np.ones(9), (batchsize, 1)) batch_obs = jnp.tile(N0, (batchsize, 1, 1)) print(f"Batched Params Shape: {batch_params.shape}") # Constructing a custom function that takes as input a parameter vector and returns the simulated state def standard_func(params): amp, sigma, freq = params # Here we use a Drag Pulse as defined in qiskit pulse as its already a Scalable Symbolic Pulse special_pulse = pulse.Drag( duration=320, amp=amp, sigma=sigma, beta=0.1, angle=0.1, limit_amplitude=False ) with pulse.build(default_alignment='sequential') as sched: d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) u0 = pulse.ControlChannel(0) u1 = pulse.ControlChannel(1) pulse.shift_frequency(freq, d0) pulse.play(special_pulse, d0) pulse.shift_frequency(freq, d1) pulse.play(special_pulse, d1) pulse.shift_frequency(freq, u0) pulse.play(special_pulse, u0) pulse.shift_frequency(freq, u1) pulse.play(special_pulse, u1) return sched # Constructing the new solver dt = 1/4.5e9 atol = 1e-2 rtol = 1e-4 t_linspace = np.linspace(0.0, 400e-9, 11) t_span = np.array([t_linspace[0], t_linspace[-1]]) ham_ops = [drive_op0, drive_op1, drive_op0, drive_op1] ham_chans = ["d0", "d1", "u0", "u1"] chan_freqs = {"d0": v0, "d1": v1, "u0": v1, "u1": v0} solver = Solver( static_hamiltonian=static_ham_full, hamiltonian_operators=ham_ops, rotating_frame=static_ham_full, hamiltonian_channels=ham_chans, channel_carrier_freqs=chan_freqs, dt=dt, ) op_str = "XI" num_qubits = len(op_str) qudit_dim_size = 3 init_state = np.zeros(qudit_dim_size ** num_qubits, dtype=np.complex64) init_state[1] = 1 base_gates_dict = { "I": jnp.array([[1.0, 0.], [0., 1.]]), "X": jnp.array([[0., 1.], [1., 0.]]), "Y": jnp.array([[0., -1.0j], [1.0j, 0.]]), "Z": jnp.array([[1., 0.], [0., -1.]]) } def PauliToQuditMatrix(inp_str: str, qudit_dim_size: Optional[int] = 4): word_list = list(inp_str) qudit_op_list = [] for word in word_list: qubit_op = base_gates_dict[word] qud_op = np.identity(qudit_dim_size, dtype=np.complex64) qud_op[:2,:2] = qubit_op qudit_op_list.append(qud_op) complete_op = qudit_op_list[0] for i in range(1,len(qudit_op_list)): complete_op = np.kron(complete_op, qudit_op_list[i]) return complete_op def evolve_state(batch_state, batch_var_str): return_state = [] for state, var_str in zip(batch_state, batch_var_str): complete_op = PauliToQuditMatrix(var_str, qudit_dim_size) return_state.append(complete_op @ state) return return_state b_size = 400 batch_state = [init_state] * b_size batch_var_str = [op_str] * b_size %timeit evolve_state(batch_state, batch_var_str) class JaxedSolver: def __init__( self, schedule_func, dt, carrier_freqs, ham_chans, t_span, rtol, atol ): super().__init__() self.schedule_func = schedule_func self.dt = dt self.carrier_freqs = carrier_freqs self.ham_chans = ham_chans self.t_span = t_span self.rtol = rtol self.atol = atol self.fast_batched_sim = jit(vmap(self.run_sim)) def run_sim(self, y0, obs, params): sched = self.schedule_func(params) converter = InstructionToSignals(self.dt, carriers=self.carrier_freqs, channels=self.ham_chans) signals = converter.get_signals(sched) results = solver.solve( t_span=self.t_span, y0=y0 / jnp.linalg.norm(y0), t_eval=self.t_span, signals=signals, rtol=self.rtol, atol=self.atol, convert_results=False, method='jax_odeint' ) state_vec = results.y.data[-1] state_vec = state_vec / jnp.linalg.norm(state_vec) new_vec = obs @ state_vec probs_vec = jnp.abs(new_vec)**2 probs_vec = jnp.clip(probs_vec, a_min=0.0, a_max=1.0) # Shots instead of probabilities return probs_vec def estimate2(self, batch_y0, batch_params, batch_obs_str): batch_obs = jnp.zeros((batch_y0.shape[0], batch_y0.shape[1], batch_y0.shape[1]), dtype=jnp.complex64) for i, b_str in enumerate(batch_obs_str): batch_obs = batch_obs.at[i].set(PauliToQuditMatrix(b_str, dim)) return self.fast_batched_sim(batch_y0, batch_obs, batch_params) j_solver_2 = JaxedSolver( schedule_func=standard_func, dt=dt, carrier_freqs=chan_freqs, ham_chans=ham_chans, t_span=t_span, rtol=rtol, atol=atol ) ops_str_list = ["IX", "XY", "ZX", "ZI"] * 100 batch_res = j_solver_2.estimate2( batch_y0, batch_params, ops_str_list ) %timeit j_solver_2.estimate2(batch_y0, batch_params, ops_str_list)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Operator from qiskit.transpiler.passes import UnitarySynthesis circuit = QuantumCircuit(1) circuit.rx(0.8, 0) unitary = Operator(circuit).data unitary_circ = QuantumCircuit(1) unitary_circ.unitary(unitary, [0]) synth = UnitarySynthesis(basis_gates=["h", "s"], method="sk") out = synth(unitary_circ) out.draw('mpl')
https://github.com/HuangJunye/Qiskit-for-GameDev
HuangJunye
# # Copyright 2019 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License 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. # import numpy as np from qiskit import QuantumCircuit, QuantumRegister from model import circuit_node_types as node_types class CircuitGridModel(): """Grid-based model that is built when user interacts with circuit""" def __init__(self, max_wires, max_columns): self.max_wires = max_wires self.max_columns = max_columns self.nodes = np.empty((max_wires, max_columns), dtype = CircuitGridNode) def __str__(self): retval = '' for wire_num in range(self.max_wires): retval += '\n' for column_num in range(self.max_columns): # retval += str(self.nodes[wire_num][column_num]) + ', ' retval += str(self.get_node_gate_part(wire_num, column_num)) + ', ' return 'CircuitGridModel: ' + retval # def set_node(self, wire_num, column_num, node_type, radians=0, ctrl_a=-1, ctrl_b=-1, swap=-1): def set_node(self, wire_num, column_num, circuit_grid_node): self.nodes[wire_num][column_num] = \ CircuitGridNode(circuit_grid_node.node_type, circuit_grid_node.radians, circuit_grid_node.ctrl_a, circuit_grid_node.ctrl_b, circuit_grid_node.swap) # TODO: Decide whether to protect as shown below # if not self.nodes[wire_num][column_num]: # self.nodes[wire_num][column_num] = CircuitGridNode(node_type, radians) # else: # print('Node ', wire_num, column_num, ' not empty') def get_node(self, wire_num, column_num): return self.nodes[wire_num][column_num] def get_node_gate_part(self, wire_num, column_num): requested_node = self.nodes[wire_num][column_num] if requested_node and requested_node.node_type != node_types.EMPTY: # Node is occupied so return its gate return requested_node.node_type else: # Check for control nodes from gates in other nodes in this column nodes_in_column = self.nodes[:, column_num] for idx in range(self.max_wires): if idx != wire_num: other_node = nodes_in_column[idx] if other_node: if other_node.ctrl_a == wire_num or other_node.ctrl_b == wire_num: return node_types.CTRL elif other_node.swap == wire_num: return node_types.SWAP return node_types.EMPTY def get_gate_wire_for_control_node(self, control_wire_num, column_num): """Get wire for gate that belongs to a control node on the given wire""" gate_wire_num = -1 nodes_in_column = self.nodes[:, column_num] for wire_idx in range(self.max_wires): if wire_idx != control_wire_num: other_node = nodes_in_column[wire_idx] if other_node: if other_node.ctrl_a == control_wire_num or \ other_node.ctrl_b == control_wire_num: gate_wire_num = wire_idx print("Found gate: ", self.get_node_gate_part(gate_wire_num, column_num), " on wire: " , gate_wire_num) return gate_wire_num # def avail_gate_parts_for_node(self, wire_num, column_num): # retval = np.empty(0, dtype = np.int8) # node_gate_part = self.get_node_gate_part(wire_num, column_num) # if node_gate_part == node_types.EMPTY: # # No gate part in this node def compute_circuit(self): qr = QuantumRegister(self.max_wires, 'q') qc = QuantumCircuit(qr) for column_num in range(self.max_columns): for wire_num in range(self.max_wires): node = self.nodes[wire_num][column_num] if node: if node.node_type == node_types.IDEN: # Identity gate qc.iden(qr[wire_num]) elif node.node_type == node_types.X: if node.radians == 0: if node.ctrl_a != -1: if node.ctrl_b != -1: # Toffoli gate qc.ccx(qr[node.ctrl_a], qr[node.ctrl_b], qr[wire_num]) else: # Controlled X gate qc.cx(qr[node.ctrl_a], qr[wire_num]) else: # Pauli-X gate qc.x(qr[wire_num]) else: # Rotation around X axis qc.rx(node.radians, qr[wire_num]) elif node.node_type == node_types.Y: if node.radians == 0: if node.ctrl_a != -1: # Controlled Y gate qc.cy(qr[node.ctrl_a], qr[wire_num]) else: # Pauli-Y gate qc.y(qr[wire_num]) else: # Rotation around Y axis qc.ry(node.radians, qr[wire_num]) elif node.node_type == node_types.Z: if node.radians == 0: if node.ctrl_a != -1: # Controlled Z gate qc.cz(qr[node.ctrl_a], qr[wire_num]) else: # Pauli-Z gate qc.z(qr[wire_num]) else: if node.ctrl_a != -1: # Controlled rotation around the Z axis qc.crz(node.radians, qr[node.ctrl_a], qr[wire_num]) else: # Rotation around Z axis qc.rz(node.radians, qr[wire_num]) elif node.node_type == node_types.S: # S gate qc.s(qr[wire_num]) elif node.node_type == node_types.SDG: # S dagger gate qc.sdg(qr[wire_num]) elif node.node_type == node_types.T: # T gate qc.t(qr[wire_num]) elif node.node_type == node_types.TDG: # T dagger gate qc.tdg(qr[wire_num]) elif node.node_type == node_types.H: if node.ctrl_a != -1: # Controlled Hadamard qc.ch(qr[node.ctrl_a], qr[wire_num]) else: # Hadamard gate qc.h(qr[wire_num]) elif node.node_type == node_types.SWAP: if node.ctrl_a != -1: # Controlled Swap qc.cswap(qr[node.ctrl_a], qr[wire_num], qr[node.swap]) else: # Swap gate qc.swap(qr[wire_num], qr[node.swap]) return qc class CircuitGridNode(): """Represents a node in the circuit grid""" def __init__(self, node_type, radians=0.0, ctrl_a=-1, ctrl_b=-1, swap=-1): self.node_type = node_type self.radians = radians self.ctrl_a = ctrl_a self.ctrl_b = ctrl_b self.swap = swap def __str__(self): string = 'type: ' + str(self.node_type) string += ', radians: ' + str(self.radians) if self.radians != 0 else '' string += ', ctrl_a: ' + str(self.ctrl_a) if self.ctrl_a != -1 else '' string += ', ctrl_b: ' + str(self.ctrl_b) if self.ctrl_b != -1 else '' return string
https://github.com/hrahman12/IBM-Variational-Algorithm-Design-Challenge
hrahman12
answers = [3] from qc_grader.challenges.algorithm_design import grade_problem_3 grade_problem_3(answers)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import BasicAer from qiskit.compiler import transpile from qiskit.quantum_info.operators import Operator, Pauli from qiskit.quantum_info import process_fidelity from qiskit.extensions import RXGate, XGate, CXGate XX = Operator([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]]) XX XX.data input_dim, output_dim = XX.dim input_dim, output_dim op = Operator(np.random.rand(2 ** 1, 2 ** 2)) print('Input dimensions:', op.input_dims()) print('Output dimensions:', op.output_dims()) op = Operator(np.random.rand(6, 6)) print('Input dimensions:', op.input_dims()) print('Output dimensions:', op.output_dims()) # Force input dimension to be (4,) rather than (2, 2) op = Operator(np.random.rand(2 ** 1, 2 ** 2), input_dims=[4]) print('Input dimensions:', op.input_dims()) print('Output dimensions:', op.output_dims()) # Specify system is a qubit and qutrit op = Operator(np.random.rand(6, 6), input_dims=[2, 3], output_dims=[2, 3]) print('Input dimensions:', op.input_dims()) print('Output dimensions:', op.output_dims()) print('Dimension of input system 0:', op.input_dims([0])) print('Dimension of input system 1:', op.input_dims([1])) # Create an Operator from a Pauli object pauliXX = Pauli('XX') Operator(pauliXX) # Create an Operator for a Gate object Operator(CXGate()) # Create an operator from a parameterized Gate object Operator(RXGate(np.pi / 2)) # Create an operator from a QuantumCircuit object circ = QuantumCircuit(10) circ.h(0) for j in range(1, 10): circ.cx(j-1, j) # Convert circuit to an operator by implicit unitary simulation Operator(circ) # Create an operator XX = Operator(Pauli('XX')) # Add to a circuit circ = QuantumCircuit(2, 2) circ.append(XX, [0, 1]) circ.measure([0,1], [0,1]) circ.draw('mpl') backend = BasicAer.get_backend('qasm_simulator') circ = transpile(circ, backend, basis_gates=['u1','u2','u3','cx']) job = backend.run(circ) job.result().get_counts(0) # Add to a circuit circ2 = QuantumCircuit(2, 2) circ2.append(Pauli('XX'), [0, 1]) circ2.measure([0,1], [0,1]) circ2.draw() A = Operator(Pauli('X')) B = Operator(Pauli('Z')) A.tensor(B) A = Operator(Pauli('X')) B = Operator(Pauli('Z')) A.expand(B) A = Operator(Pauli('X')) B = Operator(Pauli('Z')) A.compose(B) A = Operator(Pauli('X')) B = Operator(Pauli('Z')) A.compose(B, front=True) # Compose XZ with an 3-qubit identity operator op = Operator(np.eye(2 ** 3)) XZ = Operator(Pauli('XZ')) op.compose(XZ, qargs=[0, 2]) # Compose YX in front of the previous operator op = Operator(np.eye(2 ** 3)) YX = Operator(Pauli('YX')) op.compose(XZ, qargs=[0, 2], front=True) XX = Operator(Pauli('XX')) YY = Operator(Pauli('YY')) ZZ = Operator(Pauli('ZZ')) op = 0.5 * (XX + YY - 3 * ZZ) op op.is_unitary() # Compose with a matrix passed as a list Operator(np.eye(2)).compose([[0, 1], [1, 0]]) Operator(Pauli('X')) == Operator(XGate()) Operator(XGate()) == np.exp(1j * 0.5) * Operator(XGate()) # Two operators which differ only by phase op_a = Operator(XGate()) op_b = np.exp(1j * 0.5) * Operator(XGate()) # Compute process fidelity F = process_fidelity(op_a, op_b) print('Process fidelity =', F) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/nahumsa/volta
nahumsa
# This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import unittest import qiskit from qiskit.circuit.library import TwoLocal from qiskit import QuantumCircuit, Aer from qiskit.utils import QuantumInstance from qiskit.opflow import Z, I from volta.ssvqe import SSVQE from volta.utils import classical_solver class TestSSVQD(unittest.TestCase): def setUp(self): optimizer = qiskit.algorithms.optimizers.COBYLA() backend = QuantumInstance( backend=Aer.get_backend("qasm_simulator"), shots=10000 ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=2) self.Algo = SSVQE( hamiltonian=hamiltonian, ansatz=ansatz, optimizer=optimizer, n_excited=2, backend=backend, ) self.energy = [] self.energy.append(self.Algo.run(index=0)[0]) self.energy.append(self.Algo.run(index=1)[0]) self.eigenvalues, _ = classical_solver(hamiltonian) def test_energies(self): want = self.eigenvalues[0] got = self.energy[0] decimalPlace = 1 message = "SSVQE not working for the ground state of 1/2*((Z^I) + (Z^Z))" self.assertAlmostEqual(want, got, decimalPlace, message) decimalPlace = 1 want = self.eigenvalues[1] got = self.energy[1] message = "SSVQE not working for the first excited state of 1/2*((Z^I) + (Z^Z))" self.assertAlmostEqual(want, got, decimalPlace, message) if __name__ == "__main__": unittest.main(argv=[""], verbosity=2, exit=False)
https://github.com/qiskit-community/qiskit-cold-atom
qiskit-community
import numpy as np from qiskit import QuantumCircuit circuit = QuantumCircuit(2) # initialization to create a 50 - 50 superposition circuit.h(0) circuit.h(1) # measurement circuit.measure_all() circuit.draw("mpl", style='clifford') from qiskit import Aer from qiskit.visualization import plot_histogram def bit_counts_to_Lz(counts): """transform bitstring counts to collective counts. Args: counts: a dict whose keys are the observed integers for the spin and whose values is the number of observations Returns: counts: a dict whose keys are the observed integers for the total observed numbers of up and whose values is the number of observations """ lz_counts = {} for bitstring, count in counts.items(): measured_label = bitstring.count("1") if str(measured_label) in lz_counts: lz_counts[str(measured_label)] += count else: lz_counts[str(measured_label)] = count return lz_counts qasm_simulator = Aer.get_backend("aer_simulator") job = qasm_simulator.run(circuit, shots=1000) counts = job.result().get_counts() lz_counts_uncorrelated = bit_counts_to_Lz(counts) plot_histogram(lz_counts_uncorrelated) circuit = QuantumCircuit(2) # initialization on x circuit.h(0) circuit.x(1) circuit.cx(0, 1) # measurement circuit.measure_all() circuit.draw("mpl", style='clifford') job = qasm_simulator.run(circuit, shots=1000) counts = job.result().get_counts() counts["00"] = 0 counts["11"] = 0 squeezed_lz_counts = bit_counts_to_Lz(counts) plot_histogram(squeezed_lz_counts) from qiskit_cold_atom.providers import ColdAtomProvider from qiskit_cold_atom.spins.spins_gate_library import OATGate from qiskit.circuit import Parameter import numpy as np provider = ColdAtomProvider() backend = provider.get_backend("collective_spin_simulator") qc = QuantumCircuit(1) alpha = Parameter("α") beta = Parameter("β") gamma = Parameter("γ") qc.rly(np.pi / 2, 0) qc.append(OATGate(chi=gamma, delta=0, omega=beta), qargs=[0]) qc.rlx(np.pi, 0) qc.append(OATGate(chi=gamma, delta=0, omega=beta), qargs=[0]) qc.rlx(alpha, 0) qc.measure_all() qc.draw("mpl", style='clifford') # Number of atoms Nat = 100 # The length of the spin l = Nat / 2 # Strength of the rotation around x omegax = 2 * np.pi * 20 # Time of the evolution time = 15e-3 # Strength of the Lz-squared operator Lambda = 1.5 chi = Lambda * abs(omegax) / Nat; alphas = np.array([50, 140]) / 180 * np.pi circuit = qc.assign_parameters( { alpha: np.pi - alphas[0], beta: omegax * time / 2, gamma: chi * time / 2, }, inplace=False, ) job = backend.run(circuit, shots=1000, spin=Nat / 2) counts1 = job.result().get_counts() circuit = qc.assign_parameters( { alpha: np.pi - alphas[1], beta: omegax * time / 2, gamma: chi * time / 2, }, inplace=False, ) job = backend.run(circuit, shots=1000, spin=Nat / 2) counts2 = job.result().get_counts() import matplotlib.pyplot as plt from scipy.special import binom f, ax = plt.subplots() obs_num = np.array([int(key) for key in counts1.keys()]) obs_vals = np.array([val for val in counts1.values()]) ax.bar( obs_num - Nat / 2, obs_vals / obs_vals.sum(), align="center", alpha=0.5, label="squeezed", ) obs_num = np.array([int(key) for key in counts2.keys()]) obs_vals = np.array([val for val in counts2.values()]) ax.bar( obs_num - Nat / 2, obs_vals / obs_vals.sum(), align="center", alpha=0.5, label="anti-squeezed", ) # and compare to the binomial distribution; ks = np.arange(Nat) pk = binom(Nat, ks) * 0.5 ** ks * 0.5 ** (Nat - ks) ax.plot(ks - Nat / 2, pk, label="uncorrelated noise", c="C2") ax.legend() ax.set_ylabel("Probability") ax.set_xlabel(r"$L_z$"); t1 = 15e-3 t2 = 25e-3 def mean_var_from_counts(counts): """calculate mean and variance from the counts. Args: counts: a dict whose keys are the observed integers for the spin and whose values is the number of observations Returns: mean, var: mean and variance of the observed counts """ mean, var, count_sum = 0, 0, 0 for k, v in counts.items(): mean += int(k) * v count_sum += v mean = mean / count_sum for k, v in counts.items(): var += (int(k) - mean) ** 2 * v / count_sum return mean, var alphas = np.linspace(0, np.pi, 15) variances_1 = np.zeros(len(alphas)) variances_2 = np.zeros(len(alphas)) for ii in range(len(alphas)): # first time step circuit = qc.assign_parameters( { alpha: alphas[ii], beta: omegax * t1 / 2, gamma: chi * t1 / 2, }, inplace=False, ) job = backend.run(circuit, shots=1000, spin=Nat / 2, seed=14) counts = job.result().get_counts() mean, var = mean_var_from_counts(counts) variances_1[ii] = var # and the second time step circuit = qc.assign_parameters( { alpha: alphas[ii], beta: omegax * t2 / 2, gamma: chi * t2 / 2, }, inplace=False, ) job = backend.run(circuit, shots=1000, spin=Nat / 2, seed=14) counts = job.result().get_counts() mean, var = mean_var_from_counts(counts) variances_2[ii] = var; # Import the data from the paper by Strobel et al. strobel_15_dB = np.array( [ 0.51993068, 10.39861352, 20.5372617, 30.41594454, 40.81455806, 45.49393414, 50.6932409, 56.152513, 60.05199307, 69.93067591, 79.80935875, 90.98786828, 100.08665511, 109.96533795, 120.36395147, 130.24263432, 139.86135182, 150.51993068, 160.13864818, 170.01733102, 180.1559792, ] ) strobel_15_alpha = np.array( [ 9.27455357, 8.03571429, 6.19419643, 3.54910714, -0.46875, -2.27678571, -4.11830357, -4.01785714, -2.94642857, 1.30580357, 4.55357143, 6.99776786, 8.50446429, 9.140625, 10.41294643, 10.546875, 10.64732143, 10.27901786, 9.74330357, 9.40848214, 8.27008929, ] ) # and the values for 25ms strobel_25_dB = np.array( [ 0.51993068, 10.39861352, 20.5372617, 30.41594454, 40.81455806, 45.49393414, 50.6932409, 56.152513, 60.05199307, 69.93067591, 79.80935875, 90.98786828, 100.08665511, 109.96533795, 120.36395147, 130.24263432, 139.86135182, 150.51993068, 160.13864818, 170.01733102, 180.1559792, ] ) strobel_25_alpha = np.array( [ 16.07142857, 15.46875, 14.02901786, 11.71875, 8.40401786, 4.72098214, 2.20982143, -0.46875, 0.0, 2.74553571, 7.734375, 10.98214286, 13.39285714, 14.89955357, 15.73660714, 16.50669643, 17.00892857, 17.31026786, 17.24330357, 16.77455357, 15.80357143, ] ) def number_squeezing_factor_to_db(var_CSS, var): """Calcululate the squeezing parameter from the observed variance.""" return 10 * np.log10(var / var_CSS) f, ax = plt.subplots() ax.set_title("Number Squeezing") ax.plot( np.rad2deg(np.pi - alphas), number_squeezing_factor_to_db(l / 2, variances_1), "r-", lw=5, label="simulated 15ms", alpha=0.5, ) ax.plot(strobel_15_dB, strobel_15_alpha, "ro", label="1experiment 5ms", markersize=4) ax.plot( np.rad2deg(np.pi - alphas), number_squeezing_factor_to_db(l / 2, variances_2), "b-", lw=5, label="simulated 25ms", alpha=0.5, ) ax.plot(strobel_25_dB, strobel_25_alpha, "bo", label="experiment 25ms", markersize=4) ax.axhline(y=0, color="g", linestyle="--") ax.set_ylabel(r"Number Squeezing in $dB$") ax.set_xlabel(r"tomography angle $\alpha$") ax.legend(); from qiskit_cold_atom.providers import ColdAtomProvider from pprint import pprint # save an account to disk #provider = ColdAtomProvider.save_account( # url=[ # "https://qlued.alqor.io/api/v2/singlequdit", # "https://qlued.alqor.io/api/v2/multiqudit", # "https://qlued.alqor.io/api/v2/fermions", # ], # username="name", # token="token", # overwrite=True #) # or enable an account in the current session #provider = ColdAtomProvider.enable_account( # url=[ # "https://qlued.alqor.io/api/v2/singlequdit", # "https://qlued.alqor.io/api/v2/multiqudit", # "https://qlued.alqor.io/api/v2/fermions", # ], # username="name", # token="token", # overwrite=True #) provider = ColdAtomProvider.load_account() spin_device_backend = provider.get_backend("alqor_singlequdit_simulator") pprint(spin_device_backend.configuration().supported_instructions) Nat = 200 l = Nat / 2 # spin length omegax = 2 * np.pi * 20 t1 = 15e-3 t2 = 25e-3 Lambda = 1.5 chi = Lambda * abs(omegax) / Nat Ntrott = 15 alphas = np.linspace(0, np.pi, 15) alpha = Parameter("α") beta = Parameter("β") gamma = Parameter("γ") qc_trott = QuantumCircuit(1, 1) qc_trott.load_spins(Nat, 0) qc_trott.rlx(np.pi / 2, 0) qc_trott.rlz(np.pi / 2, 0) for ii in range(Ntrott): qc_trott.rlx(beta, 0) qc_trott.rlz2(gamma, 0) qc_trott.rlx(alpha, 0) qc_trott.measure(0, 0) qc_trott.draw(output="mpl") circuit1_list = [ qc_trott.assign_parameters( {alpha: -a % (2 * np.pi), gamma: chi * t1 / Ntrott, beta: omegax * t1 / Ntrott}, inplace=False, ) for a in alphas ] job1 = spin_device_backend.run(circuit1_list, shots=500) job1.job_id() job_retrieved1 = spin_device_backend.retrieve_job(job_id=job1.job_id()) print("job status: ", job_retrieved1.status()) circuit2_list = [ qc_trott.assign_parameters( {alpha: -a % (2 * np.pi), gamma: chi * t2 / Ntrott, beta: omegax * t2 / Ntrott}, inplace=False, ) for a in alphas ] job2 = spin_device_backend.run(circuit2_list, shots=500) job2.job_id() job_retrieved2 = spin_device_backend.retrieve_job(job_id=job2.job_id()) print("job status: ", job_retrieved2.status()) result1 = job_retrieved1.result() result2 = job_retrieved2.result() outcomes1 = [result1.get_memory(i) for i in range(len(circuit1_list))] outcomes2 = [result2.get_memory(i) for i in range(len(circuit2_list))] variances_1 = [np.var(np.array(counts1, dtype=float)) for counts1 in outcomes1] variances_2 = [np.var(np.array(counts2, dtype=float)) for counts2 in outcomes2] variances_1 = np.array(variances_1) variances_2 = np.array(variances_2) f, ax = plt.subplots() ax.set_title("Number Squeezing") plt.plot( np.rad2deg(alphas), number_squeezing_factor_to_db(l / 2, variances_1), "r-", lw=5, label="simulated 15ms", alpha=0.5, ) plt.plot( np.rad2deg(alphas), number_squeezing_factor_to_db(l / 2, variances_2), "b-", lw=5, label="simulated 25ms", alpha=0.5, ) plt.plot(strobel_15_dB, strobel_15_alpha, "ro", label="15ms", markersize=4) plt.plot(strobel_25_dB, strobel_25_alpha, "bo", label="25ms", markersize=4) ax.axhline(y=0, color="g", linestyle="--") ax.set_ylabel(r"Number Squeezing in $dB$") ax.set_xlabel(r"tomography angle $\alpha$") ax.legend() import qiskit.tools.jupyter %qiskit_version_table
https://github.com/oierajenjo/q-Grover-Algorithm
oierajenjo
import qiskit qiskit.__qiskit_version__ import numpy as np import matplotlib.pyplot as plt %matplotlib inline # importing Qiskit from qiskit import BasicAer, IBMQ from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.compiler import transpile from qiskit.tools.visualization import plot_histogram q = QuantumRegister(6) qc = QuantumCircuit(q) qc.x(q[2]) qc.cx(q[1], q[5]) qc.cx(q[2], q[5]) qc.cx(q[3], q[5]) qc.ccx(q[1], q[2], q[4]) qc.ccx(q[3], q[4], q[5]) qc.ccx(q[1], q[2], q[4]) qc.x(q[2]) qc.draw(output='mpl') def black_box_u_f(circuit, f_in, f_out, aux, n, exactly_1_3_sat_formula): """Circuit that computes the black-box function from f_in to f_out. Create a circuit that verifies whether a given exactly-1 3-SAT formula is satisfied by the input. The exactly-1 version requires exactly one literal out of every clause to be satisfied. """ num_clauses = len(exactly_1_3_sat_formula) for (k, clause) in enumerate(exactly_1_3_sat_formula): # This loop ensures aux[k] is 1 if an odd number of literals # are true for literal in clause: if literal > 0: circuit.cx(f_in[literal-1], aux[k]) else: circuit.x(f_in[-literal-1]) circuit.cx(f_in[-literal-1], aux[k]) # Flip aux[k] if all literals are true, using auxiliary qubit # (ancilla) aux[num_clauses] circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) circuit.ccx(f_in[2], aux[num_clauses], aux[k]) # Flip back to reverse state of negative literals and ancilla circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) for literal in clause: if literal < 0: circuit.x(f_in[-literal-1]) # The formula is satisfied if and only if all auxiliary qubits # except aux[num_clauses] are 1 if (num_clauses == 1): circuit.cx(aux[0], f_out[0]) elif (num_clauses == 2): circuit.ccx(aux[0], aux[1], f_out[0]) elif (num_clauses == 3): circuit.ccx(aux[0], aux[1], aux[num_clauses]) circuit.ccx(aux[2], aux[num_clauses], f_out[0]) circuit.ccx(aux[0], aux[1], aux[num_clauses]) else: raise ValueError('We only allow at most 3 clauses') # Flip back any auxiliary qubits to make sure state is consistent # for future executions of this routine; same loop as above. for (k, clause) in enumerate(exactly_1_3_sat_formula): for literal in clause: if literal > 0: circuit.cx(f_in[literal-1], aux[k]) else: circuit.x(f_in[-literal-1]) circuit.cx(f_in[-literal-1], aux[k]) circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) circuit.ccx(f_in[2], aux[num_clauses], aux[k]) circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) for literal in clause: if literal < 0: circuit.x(f_in[-literal-1]) # -- end function def n_controlled_Z(circuit, controls, target): """Implement a Z gate with multiple controls""" if (len(controls) > 2): raise ValueError('The controlled Z with more than 2 ' + 'controls is not implemented') elif (len(controls) == 1): circuit.h(target) circuit.cx(controls[0], target) circuit.h(target) elif (len(controls) == 2): circuit.h(target) circuit.ccx(controls[0], controls[1], target) circuit.h(target) # -- end function def inversion_about_average(circuit, f_in, n): """Apply inversion about the average step of Grover's algorithm.""" # Hadamards everywhere for j in range(n): circuit.h(f_in[j]) # D matrix: flips the sign of the state |000> only for j in range(n): circuit.x(f_in[j]) n_controlled_Z(circuit, [f_in[j] for j in range(n-1)], f_in[n-1]) for j in range(n): circuit.x(f_in[j]) # Hadamards everywhere again for j in range(n): circuit.h(f_in[j]) # -- end function qr = QuantumRegister(3) qInvAvg = QuantumCircuit(qr) inversion_about_average(qInvAvg, qr, 3) qInvAvg.draw(output='mpl') """ Grover search implemented in Qiskit. This module contains the code necessary to run Grover search on 3 qubits, both with a simulator and with a real quantum computing device. This code is the companion for the paper "An introduction to quantum computing, without the physics", Giacomo Nannicini, https://arxiv.org/abs/1708.03684. """ def input_state(circuit, f_in, f_out, n): """(n+1)-qubit input state for Grover search.""" for j in range(n): circuit.h(f_in[j]) circuit.x(f_out) circuit.h(f_out) # -- end function # Make a quantum program for the n-bit Grover search. n = 3 # Exactly-1 3-SAT formula to be satisfied, in conjunctive # normal form. We represent literals with integers, positive or # negative, to indicate a Boolean variable or its negation. exactly_1_3_sat_formula = [[1, 2, -3], [-1, -2, -3], [-1, 2, 3]] # Define three quantum registers: 'f_in' is the search space (input # to the function f), 'f_out' is bit used for the output of function # f, aux are the auxiliary bits used by f to perform its # computation. f_in = QuantumRegister(n) f_out = QuantumRegister(1) aux = QuantumRegister(len(exactly_1_3_sat_formula) + 1) # Define classical register for algorithm result ans = ClassicalRegister(n) # Define quantum circuit with above registers grover = QuantumCircuit() grover.add_register(f_in) grover.add_register(f_out) grover.add_register(aux) grover.add_register(ans) input_state(grover, f_in, f_out, n) T = 2 for t in range(T): # Apply T full iterations black_box_u_f(grover, f_in, f_out, aux, n, exactly_1_3_sat_formula) inversion_about_average(grover, f_in, n) # Measure the output register in the computational basis for j in range(n): grover.measure(f_in[j], ans[j]) # Execute circuit backend = BasicAer.get_backend('qasm_simulator') job = execute([grover], backend=backend, shots=1000) result = job.result() # Get counts and plot histogram counts = result.get_counts(grover) plot_histogram(counts) IBMQ.load_account() # get ibmq_16_melbourne configuration and coupling map backend = IBMQ.get_backend('ibmq_16_melbourne') # compile the circuit for ibmq_16_rueschlikon grover_compiled = transpile(grover, backend=backend, seed_transpiler=1, optimization_level=3) print('gates = ', grover_compiled.count_ops()) print('depth = ', grover_compiled.depth()) grover.draw(output='mpl', scale=0.5)
https://github.com/bayesian-randomized-benchmarking/qiskit-advocates-bayes-RB
bayesian-randomized-benchmarking
import numpy as np import time import copy from qiskit_experiments.library import StandardRB, InterleavedRB from qiskit_experiments.framework import ParallelExperiment from qiskit_experiments.library.randomized_benchmarking import RBUtils import qiskit.circuit.library as circuits # for retrieving gate calibration from datetime import datetime import qiskit.providers.aer.noise.device as dv # import the bayesian packages import pymc3 as pm import arviz as az import qiskit_bayesian_fitter as bf simulation = True # make your choice here if simulation: from qiskit.providers.aer import AerSimulator from qiskit.test.mock import FakeParis backend = AerSimulator.from_backend(FakeParis()) else: from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = provider.get_backend('ibmq_bogota') # type here hardware backend # describe RB experiment qubits = [0] lengths = np.arange(1, 2500, 250) num_samples = 10 seed = 194606 exp1 = StandardRB(qubits, lengths, num_samples=num_samples, seed=seed) expdata1 = exp1.run(backend).block_for_results() results1 = expdata1.analysis_results() #prepare circuits exp1 = StandardRB(qubits, lengths, num_samples=num_samples, seed=seed) #run print("start experiments",time.strftime('%d/%m/%Y %H:%M:%S')) expdata1 = exp1.run(backend).block_for_results() print(" end experiments",time.strftime('%d/%m/%Y %H:%M:%S')) nQ = len(qubits) scale = (2 ** nQ - 1) / 2 ** nQ m_len = len(lengths) interleaved_gate = "" # for plot title experiment_type = expdata1._data[0]['metadata']['experiment_type'] physical_qubits = expdata1._data[0]['metadata']['physical_qubits'] shots = expdata1._data[0]['shots'] # to compare ultimately: EPC and sigma(EPC) by LSF epc_est_fm = expdata1.analysis_results()[2].value.value epc_est_fm_err = expdata1.analysis_results()[2].value.stderr # get count data and other values from expdata1 Y = bf.get_GSP_counts(expdata1._data, m_len, range(num_samples)) X = np.copy(lengths) y_mean = np.mean(Y, axis = 0)/shots sigma_y = np.std(Y, axis = 0)/shots model = "hierarchical model" # priors for unknown model parameters T_priors = expdata1.analysis_results()[0].value.value print(T_priors) testval_s = 0.001 upper_s = 0.004 lower_s = 0.0001 alpha_Gamma = 10 beta_Gamma = 10000 h_model = bf.create_model(T_priors, X, Y, shots, scale, testval_s = testval_s ,upper_s = upper_s, lower_s = lower_s, s_prior = "Gamma", alpha_Gamma = alpha_Gamma, beta_Gamma = beta_Gamma) # model graph pm.model_to_graphviz(h_model) # sample with h_model: trace_h = pm.sample(draws = 4000, tune= 1000, target_accept=.99, return_inferencedata=True) with h_model: az.plot_trace(trace_h); with h_model: az.plot_posterior(trace_h, var_names = ["Tying_Parameters","σ_Beta","EPC"], round_to = 4, figsize = [16, 8]); # look at the posterior values of the hyperparameters: with h_model: # (hdi_prob=.94 is default) azt_summary = az.summary(trace_h, round_to=12, var_names = ["Tying_Parameters", "σ_Beta","EPC"], kind="stats") azt_summary # for comparison # reference epc_calib = np.nan # bayesian epc_est_a = azt_summary['mean']['EPC'] epc_est_a_err = azt_summary['sd']['EPC'] # frequentist epc_est_fm = expdata1.analysis_results()[2].value.value epc_est_fm_err = expdata1.analysis_results()[2].value.stderr epc_title = experiment_type +', qubit(s):' + str(physical_qubits)\ +', backend: '+backend.name() + "\n Bayesian "+model bf.plot_epc(h_model, trace_h, epc_calib, epc_est_a, epc_est_a_err, epc_est_fm, epc_est_fm_err, epc_title) # backend's recorded EPG error_dic = RBUtils.get_error_dict_from_backend(backend, qubits) # get the EPG values EPG_dic = {} REF_dic = {} for i in range(3,6): EPG_key = expdata1.analysis_results()[i].name EPG_dic[EPG_key] = expdata1.analysis_results()[i].value.value for elem in (error_dic): if 'EPG_' + elem[1] == EPG_key: REF_dic[EPG_key] = error_dic[elem] # compare LSF and SMC print("Model: Frequentist Bayesian Reference") print("________________________________________________________") print("EPC {0:1.3e} {1:1.3e} {2:1.3e}" .format(epc_est_fm, epc_est_a, epc_calib )) print("± sd ± {0:1.3e} ± {1:1.3e} " .format(epc_est_fm_err, epc_est_a_err)) for i, (gate,EPG) in enumerate(EPG_dic.items()): print("{0:<12}{1:1.3e} {2:1.3e} {3:1.3e} " .format(gate, EPG, EPG*epc_est_a/epc_est_fm, REF_dic[gate])) # prepare box for GSP plot texto = "alpha = {0:7.4f} ± {1:1.4e}"\ .format(azt_summary['mean']['Tying_Parameters[1]'], azt_summary['sd']['Tying_Parameters[1]']) + "\n" texto += "EPC = {0:1.4e} ± {1:1.4e}"\ .format(azt_summary['mean']['EPC'], azt_summary['sd']['EPC']) + "\n" for i, (gate,EPG) in enumerate(EPG_dic.items()): texto += " {0:<8} = {1:1.4e} "\ .format(gate.ljust(6), EPG*epc_est_a/epc_est_fm) + "\n" texto += " Fit χ² = {0:7.4f} "\ .format(bf.reduced_chisquare(y_mean, sigma_y, trace_h)) bounds_rmk, y1, y1_min, y1_max = bf.prepare_data_GSP_plot(h_model, trace_h, HDI = False) title = experiment_type +', ' + interleaved_gate\ + str(physical_qubits)\ +', backend: '+backend.name()+\ "\n Bayesian "+model+" "+ bounds_rmk bf.gsp_plot(scale, lengths, num_samples, shots, texto, title, y1, y1_min, y1_max, y2=None, y2_min=None, y2_max=None, Y1=Y, Y2=None, first_curve = "Calculated values", second_curve = None) # View data for frequentist model display(expdata1.figure(0)) lengths = np.arange(1, 200, 30) num_samples = 10 seed = 194606 qubits = (1,4) # Run a 1-qubit RB expriment on qubits 1, 4 to determine the error-per-gate of 1-qubit gates expdata_1q = {} epg_1q = [] lengths_1_qubit = np.arange(1, 2500, 250) for qubit in qubits: exp = StandardRB([qubit], lengths_1_qubit, num_samples=num_samples, seed=seed) expdata = exp.run(backend).block_for_results() expdata_1q[qubit] = expdata epg_1q += expdata.analysis_results() # Run an RB experiment on qubits 1, 4 exp2 = StandardRB(qubits, lengths, num_samples=num_samples, seed=seed) # Use the EPG data of the 1-qubit runs to ensure correct 2-qubit EPG computation exp2.set_analysis_options(epg_1_qubit=epg_1q) # Run the 2-qubit experiment expdata2 = exp2.run(backend).block_for_results() # View result data results2 = expdata2.analysis_results() # Compare the computed EPG of the cx gate with the backend's recorded cx gate error: expected_epg = RBUtils.get_error_dict_from_backend(backend, qubits)[(qubits, 'cx')] exp2_epg = expdata2.analysis_results("EPG_cx").value print("Backend's reported EPG of the cx gate:", expected_epg) print("Experiment computed EPG of the cx gate:", exp2_epg) trace_1q = {} scale_1q = .5 for qubit in qubits: Y = bf.get_GSP_counts(expdata_1q[qubit]._data, len(lengths_1_qubit), range(num_samples)) X = np.copy(lengths_1_qubit) shots_1_qubit = expdata_1q[qubit]._data[0]['shots'] T_priors = expdata_1q[qubit].analysis_results()[0].value.value testval_s = 0.001 upper_s = 0.004 lower_s = 0.0001 alpha_Gamma = 10 beta_Gamma = 10000 h1_model = bf.create_model(T_priors, X, Y, shots_1_qubit, scale_1q, testval_s = testval_s ,upper_s = upper_s, lower_s = lower_s, s_prior = "Gamma", alpha_Gamma = alpha_Gamma, beta_Gamma = beta_Gamma) with h1_model: trace_h1 = pm.sample(draws = 4000, tune= 1000, target_accept=.99, return_inferencedata=True) trace_1q[qubit] = trace_h1 nQ = len(qubits) scale = (2 ** nQ - 1) / 2 ** nQ m_len = len(lengths) interleaved_gate = "" # for plot title experiment_type = expdata2._data[0]['metadata']['experiment_type'] physical_qubits = expdata2._data[0]['metadata']['physical_qubits'] shots = expdata2._data[0]['shots'] # get count data and other values from expdata2 Y = bf.get_GSP_counts(expdata2._data, m_len, range(num_samples)) X = np.copy(lengths) y_mean = np.mean(Y, axis = 0)/shots sigma_y = np.std(Y, axis = 0)/shots model = "hierarchical model" # priors for unknown model parameters T_priors = expdata2.analysis_results()[0].value.value print(T_priors) testval_s = 0.0025 upper_s = 0.005 lower_s = 0.0005 alpha_Gamma = 5 beta_Gamma = 2000 h2_model = bf.create_model(T_priors, X, Y, shots, scale, testval_s = testval_s ,upper_s = upper_s, lower_s = lower_s, s_prior = "Gamma", alpha_Gamma = alpha_Gamma, beta_Gamma = beta_Gamma) # model graph pm.model_to_graphviz(h2_model) # sample with h2_model: trace_h2 = pm.sample(draws = 4000, tune= 1000, target_accept=.99, return_inferencedata=True) with h2_model: az.plot_trace(trace_h2); with h2_model: az.plot_posterior(trace_h2, var_names = ["Tying_Parameters","σ_Beta","EPC"], round_to = 4, figsize = [16, 8]); # look at the posterior values of the hyperparameters: with h2_model: # (hdi_prob=.94 is default) azt2_summary = az.summary(trace_h2, round_to=12, var_names = ["Tying_Parameters", "σ_Beta","EPC"], kind="stats") azt2_summary # for comparison # reference epc_calib = np.nan # bayesian epc_est_a = azt2_summary['mean']['EPC'] epc_est_a_err = azt2_summary['sd']['EPC'] # frequentist epc_est_fm = expdata2.analysis_results()[2].value.value epc_est_fm_err = expdata2.analysis_results()[2].value.stderr epc_title = experiment_type +', qubit(s):' + str(physical_qubits)\ +', backend: '+backend.name() + "\n Bayesian "+model bf.plot_epc(h2_model, trace_h2, epc_calib, epc_est_a, epc_est_a_err, epc_est_fm, epc_est_fm_err, epc_title) # obtain posterior values of the hyperparameters: azts_1q = [] for i_qubit, qubit in enumerate(qubits): with h2_model: # (hdi_prob=.94 is default) azts_1q.append( az.summary(trace_1q[qubit], round_to=12, var_names = ["Tying_Parameters", "σ_Beta","EPC"], kind="stats") ) # retrieve gates per clifford from frequentist results alpha_1q = [epg_1q[1].value.value, epg_1q[7].value.value] epc_2_qubit = expdata2.analysis_results()[2].value.value alpha_c_1q = 1 / 5 * (alpha_1q[0] + alpha_1q[1] + 3 * alpha_1q[0] * alpha_1q[1]) alpha_c_2q = (1 - 4 / 3 * epc_2_qubit) / alpha_c_1q n_gate_2q = 3 / 4 * (1 - alpha_c_2q) / exp2_epg.value # calculate epg cx from the bayesian results alpha_1q_b = [azts_1q[0]['mean']['Tying_Parameters[1]'], azts_1q[1]['mean']['Tying_Parameters[1]']] epc_2_qubit_b = azt2_summary['mean']['EPC'] alpha_c_1q_b = 1 / 5 * (alpha_1q_b[0] + alpha_1q_b[1] + 3 * alpha_1q_b[0] * alpha_1q_b[1]) alpha_c_2q_b = (1 - 4 / 3 * epc_2_qubit_b) / alpha_c_1q_b epg_cx = 3 / 4 * (1 - alpha_c_2q_b) / n_gate_2q # compare LSF and SMC print("Model: Frequentist Bayesian Reference") print("________________________________________________________") print("EPC {0:1.3e} {1:1.3e} -----" .format(epc_est_fm, epc_est_a )) print("± sd ± {0:1.3e} ± {1:1.3e} " .format(epc_est_fm_err, epc_est_a_err)) print("EPG_cx {0:1.3e} {1:1.3e} {2:1.3e}" .format(exp2_epg.value, epg_cx, expected_epg)) # prepare box for GSP plot texto = " alpha = {0:7.4f} ± {1:1.4e}"\ .format(azt2_summary['mean']['Tying_Parameters[1]'], azt2_summary['sd']['Tying_Parameters[1]']) + "\n" texto += " EPC = {0:1.4e} ± {1:1.4e}"\ .format(azt2_summary['mean']['EPC'], azt2_summary['sd']['EPC']) + "\n" texto += " EPG_cx = {0:7.4f}"\ .format(epg_cx) + "\n" texto += " Fit χ² = {0:7.4f} "\ .format(bf.reduced_chisquare(y_mean, sigma_y, trace_h2)) bounds_rmk, y1, y1_min, y1_max = bf.prepare_data_GSP_plot(h2_model, trace_h2) title = experiment_type +', ' + interleaved_gate\ + str(physical_qubits)\ +', backend: '+backend.name()+\ "\n Bayesian "+model+" "+ bounds_rmk bf.gsp_plot(scale, lengths, num_samples, shots, texto, title, y1, y1_min, y1_max, y2=None, y2_min=None, y2_max=None, Y1=Y, Y2=None, first_curve = "Calculated values", second_curve = None) # View result for frequentist model display(expdata2.figure(0))
https://github.com/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience
PacktPublishing
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created Nov 2020 @author: hassi """ from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.tools.monitor import job_monitor from qiskit.visualization import plot_histogram,plot_error_map from qiskit.compiler import transpile from IPython.core.display import display print("Ch 8: Comparing qubits on a chip") print("--------------------------------") print("Getting provider...") if not IBMQ.active_account(): IBMQ.load_account() provider = IBMQ.get_provider() def select_backend(): # Get all available and operational backends. available_backends = provider.backends(filters=lambda b: not b.configuration().simulator and b.configuration().n_qubits > 1 and b.status().operational) # Fish out criteria to compare print("{0:20} {1:<10} {2:<10}".format("Name","#Qubits","Pending jobs")) print("{0:20} {1:<10} {2:<10}".format("----","-------","------------")) for n in range(0, len(available_backends)): backend = provider.get_backend(str(available_backends[n])) print("{0:20} {1:<10}".format(backend.name(),backend.configuration().n_qubits),backend.status().pending_jobs) select_backend=input("Select a backend ('LB' for least busy): ") if select_backend not in ["LB","lb"]: backend = provider.get_backend(str(select_backend)) else: from qiskit.providers.ibmq import least_busy backend = least_busy(provider.backends(filters=lambda b: not b.configuration().simulator and b.configuration().n_qubits > 1 and b.status().operational)) print("Selected backend:",backend.status().backend_name) return(backend) def get_gate_info(backend): # Pull out the gates information. gates=backend.properties().gates #Cycle through the CX gate couplings to find the best and worst cx_best_worst = [[[0,0],1],[[0,0],0]] for n in range (0, len(gates)): if gates[n].gate == "cx": print(gates[n].name, ":", gates[n].parameters[0].name,"=", gates[n].parameters[0].value) if cx_best_worst[0][1]>gates[n].parameters[0].value: cx_best_worst[0][1]=gates[n].parameters[0].value cx_best_worst[0][0]=gates[n].qubits if cx_best_worst[1][1]<gates[n].parameters[0].value: cx_best_worst[1][1]=gates[n].parameters[0].value cx_best_worst[1][0]=gates[n].qubits print("Best cx gate:", cx_best_worst[0][0], ",", round(cx_best_worst[0][1]*100,3),"%") print("Worst cx gate:", cx_best_worst[1][0], ",", round(cx_best_worst[1][1]*100,3),"%") display(plot_error_map(backend, show_title=True)) return(cx_best_worst) def create_circuits(backend, cx_best_worst): print("Building circuits...") q1 = QuantumRegister(backend.configuration().n_qubits) c1 = ClassicalRegister(backend.configuration().n_qubits) qc_best = QuantumCircuit(q1, c1) qc_worst = QuantumCircuit(q1, c1) #Best circuit qc_best.h(q1[cx_best_worst[0][0][0]]) qc_best.cx(q1[cx_best_worst[0][0][0]], q1[cx_best_worst[0][0][1]]) qc_best.measure(q1[cx_best_worst[0][0][0]], c1[0]) qc_best.measure(q1[cx_best_worst[0][0][1]], c1[1]) print("Best CX:") display(qc_best.draw('mpl')) trans_qc_best = transpile(qc_best, backend) print("Transpiled qc_best circuit:") display(trans_qc_best.draw()) #Worst circuit qc_worst.h(q1[cx_best_worst[1][0][0]]) qc_worst.cx(q1[cx_best_worst[1][0][0]], q1[cx_best_worst[1][0][1]]) qc_worst.measure(q1[cx_best_worst[1][0][0]], c1[0]) qc_worst.measure(q1[cx_best_worst[1][0][1]], c1[1]) print("Worst CX:") display(qc_worst.draw('mpl')) return(qc_best,qc_worst) def compare_cx(backend,qc_best,qc_worst): print("Comparing CX pairs...") job_best = execute(qc_best, backend, shots=8192) job_monitor(job_best) job_worst = execute(qc_worst, backend, shots=8192) job_monitor(job_worst) q = QuantumRegister(backend.configuration().n_qubits) c = ClassicalRegister(backend.configuration().n_qubits) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[1]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) best_result = job_best.result() counts_best = best_result.get_counts(qc_best) print("Best qubit pair:") print(counts_best) worst_result = job_worst.result() counts_worst = worst_result.get_counts(qc_worst) print("Worst qubit pair:") print(counts_worst) sim_result = job_sim.result() counts_sim = sim_result.get_counts(qc) print("Simulated baseline:") print(counts_sim) display(plot_histogram([counts_best, counts_worst, counts_sim], title = "Best and worst qubit pair for: " + backend.name(), legend = ["Best qubit pair","Worst qubit pair","Simulated baseline"], sort = 'desc', figsize = (15,12), color = ['green', 'red','blue'], bar_labels = True)) def main(): backend=select_backend() cx_best_worst=get_gate_info(backend) qc_best, qc_worst=create_circuits(backend, cx_best_worst) compare_cx(backend,qc_best,qc_worst) if __name__ == '__main__': main()
https://github.com/grossiM/Qiskit_workshop1019
grossiM
import numpy as np from qiskit import * %matplotlib inline # Create a Quantum Circuit acting on a quantum register of three qubits circ = QuantumCircuit(3) # Add a H gate on qubit 0, putting this qubit in superposition. circ.h(0) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting # the qubits in a Bell state. circ.cx(0, 1) # Add a CX (CNOT) gate on control qubit 0 and target qubit 2, putting # the qubits in a GHZ state. circ.cx(0, 2) #circ.draw() circ.draw(output='mpl') # Import Aer from qiskit import Aer # Run the quantum circuit on a statevector simulator backend backend = Aer.get_backend('statevector_simulator') # Create a Quantum Program for execution job = execute(circ, backend) result = job.result() outputstate = result.get_statevector(circ, decimals=3) print(outputstate) from qiskit.visualization import plot_state_city plot_state_city(outputstate) # Run the quantum circuit on a unitary simulator backend backend = Aer.get_backend('unitary_simulator') job = execute(circ, backend) result = job.result() # Show the results print(result.get_unitary(circ, decimals=3)) # Create a Quantum Circuit meas = QuantumCircuit(3, 3) meas.barrier(range(3)) # map the quantum measurement to the classical bits meas.measure(range(3),range(3)) # The Qiskit circuit object supports composition using # the addition operator. qc = circ+meas #drawing the circuit qc.draw() # Use Aer's qasm_simulator backend_sim = Aer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator. # We've set the number of repeats of the circuit # to be 1024, which is the default. job_sim = execute(qc, backend_sim, shots=1024) # Grab the results from the job. result_sim = job_sim.result() counts = result_sim.get_counts(qc) print(counts) from qiskit.visualization import plot_histogram plot_histogram(counts) from qiskit import IBMQ #IBMQ.save_account('APIKEY') IBMQ.load_account() IBMQ.providers() provider = IBMQ.get_provider(group='open') provider.backends() simulator_backend = provider.get_backend('ibmq_qasm_simulator') job_cloud = execute(qc, backend=simulator_backend) result_cloud = job_cloud.result() counts_cloud = result_cloud.get_counts(qc) plot_histogram(counts_cloud) #example of backend filtering, you can modify the filters or ask just for the least_busy device from qiskit.providers.ibmq import least_busy backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) #here we ask for the backend properties backend.configuration() from qiskit.tools.monitor import job_monitor job_exp = execute(qc, backend=backend) job_monitor(job_exp) result_exp = job_exp.result() counts_exp = result_exp.get_counts(qc) plot_histogram([counts_exp,counts], legend=['Device', 'Simulator']) #uncomment the line below in case you are not able to specify 'latex' in the draw method #!pip install pylatexenc #!pip install pillow from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import BasicAer qr0 = QuantumRegister(1,name='qb') # qb for "qubit", but the name is optional cr0 = ClassicalRegister(1,name='b') # b for "bit", but the name is optional qc0 = QuantumCircuit(qr0,cr0) qc0.draw(output='latex') from qiskit.tools.visualization import plot_bloch_vector import math theta = math.pi/2 # You can try to change the parameters theta and phi phi = math.pi/4 # to see how the vector moves on the sphere plot_bloch_vector([math.cos(phi)*math.sin(theta),math.sin(phi)*math.sin(theta),math.cos(theta)]) # Entries of the # input vector are # coordinates [x,y,z] qc0.measure(qr0,cr0) #Select the output method to use for drawing the circuit. Valid choices are text, latex, latex_source, or mpl. By default the ‘text’ drawer is used unless a user config file has an alternative backend set as the default. #If the output kwarg is set, that backend will always be used over the default in a user config file. qc0.draw('latex') #backend_sim = Aer.get_backend('qasm_simulator') already defined above job = execute(qc0, backend_sim, shots=1024) result = job.result() counts = result.get_counts() print(counts) qc1 = QuantumCircuit(qr0,cr0) qc1.x(0) # A X gate targeting the first (and only) qubit in register qr0 qc1.measure(qr0,cr0) qc1.draw(output='mpl') job1 = execute(qc1, backend_sim, shots=1024) result1 = job1.result() counts1 = result1.get_counts() print(counts1) from qiskit.tools.visualization import plot_bloch_multivector vec_backend = Aer.get_backend('statevector_simulator') result_vec0 = execute(qc0, vec_backend).result() result_vec1 = execute(qc1, vec_backend).result() psi0 = result_vec0.get_statevector() psi1 = result_vec1.get_statevector() plot_bloch_multivector(psi0) plot_bloch_multivector(psi1) qc2 = QuantumCircuit(qr0,cr0) qc2.h(0) qc2.measure(qr0,cr0) qc2.draw(output='mpl') job2 = execute(qc2, backend_sim, shots=1024) result2 = job2.result() counts2 = result2.get_counts() print(counts2) result_vec2 = execute(qc2, vec_backend).result() psi2 = result_vec2.get_statevector() plot_bloch_multivector(psi2) qc3 = QuantumCircuit(qr0,cr0) qc3.h(0) qc3.s(0) # Use sdg instead of s for the adjoint qc3.measure(qr0,cr0) qc3.draw(output='mpl') job3 = execute(qc3, backend_sim, shots=1024) result3 = job3.result() counts3 = result3.get_counts() print(counts3) result_vec3 = execute(qc3, vec_backend).result() psi3 = result_vec3.get_statevector() plot_bloch_multivector(psi3) qc4 = QuantumCircuit(qr0,cr0) qc4.h(0) qc4.t(0) # Use tdg instead of t for the adjoint qc4.measure(qr0,cr0) qc4.draw(output='mpl') job4 = execute(qc4, backend_sim, shots=1024) result4 = job4.result() counts4 = result4.get_counts() print(counts4) result_vec4 = execute(qc4, vec_backend).result() psi4 = result_vec4.get_statevector() plot_bloch_multivector(psi4) qc4b = QuantumCircuit(qr0) qc4b.tdg(0) qc4b.draw('mpl') backend_unit = BasicAer.get_backend('unitary_simulator') job = execute(qc4b, backend_unit) job.result().get_unitary(qc4b, decimals=3) lmbd = 1.2 # Change this value to rotate the output vector on the equator of the Bloch sphere qc5 = QuantumCircuit(qr0,cr0) qc5.h(0) qc5.u1(lmbd,0) qc5.measure(qr0,cr0) qc5.draw(output='mpl') result_vec5 = execute(qc5, vec_backend).result() psi5 = result_vec5.get_statevector() plot_bloch_multivector(psi5) qc6 = QuantumCircuit(qr0,cr0) qc6.u2(0,math.pi, 0) qc6.measure(qr0,cr0) result_vec6 = execute(qc6, vec_backend).result() psi6 = result_vec6.get_statevector() plot_bloch_multivector(psi6) theta = math.pi phi = math.pi lmb = math.pi qc7 = QuantumCircuit(qr0,cr0) qc7.u3(theta,phi, lmb, 0) qc7.measure(qr0,cr0) result_vec7 = execute(qc7, vec_backend).result() psi7 = result_vec7.get_statevector() plot_bloch_multivector(psi7) qr = QuantumRegister(2,name='qr') # we need a 2-qubit register now cr = ClassicalRegister(2,name='cr') cnot_example = QuantumCircuit(qr,cr) cnot_example.x(0) cnot_example.cx(0,1) # First entry is control, the second is the target cnot_example.measure(qr,cr) cnot_example.draw(output='mpl') job_cnot = execute(cnot_example, backend_sim, shots=1024) result_cnot = job_cnot.result() counts_cnot = result_cnot.get_counts() print(counts_cnot) cnot_reversed = QuantumCircuit(qr,cr) cnot_reversed.x(0) # This part uses cx(qr[1],qr[0]) but is equivalent to cx(qr[0],qr[1]) cnot_reversed.h(0) cnot_reversed.h(1) cnot_reversed.cx(1,0) cnot_reversed.h(0) cnot_reversed.h(1) # cnot_reversed.measure(qr,cr) cnot_reversed.draw(output='mpl') job_cnot_rev = execute(cnot_reversed, backend_sim, shots=1024) result_cnot_rev = job_cnot_rev.result() counts_cnot_rev = result_cnot_rev.get_counts() print(counts_cnot_rev) bell_phi_p = QuantumCircuit(qr,cr) bell_phi_p.h(0) bell_phi_p.cx(0,1) bell_phi_p.measure(qr,cr) bell_phi_p.draw(output='mpl') job_bell_phi_p = execute(bell_phi_p, backend_sim, shots=1024) result_bell_phi_p = job_bell_phi_p.result() counts_bell_phi_p = result_bell_phi_p.get_counts() print(counts_bell_phi_p) cz_example = QuantumCircuit(qr) cz_example.cz(0,1) cz_example.draw(output='mpl') job_cz = execute(cz_example, backend_unit) job_cz.result().get_unitary(cz_example, decimals=3) cz_from_cnot = QuantumCircuit(qr) #notice here a more verbose way of writing gates and assign them to qubits cz_from_cnot.h(qr[1]) cz_from_cnot.cx(qr[0],qr[1]) cz_from_cnot.h(qr[1]) cz_from_cnot.draw(output='mpl') swap_test = QuantumCircuit(qr) swap_test.swap(qr[0],qr[1]) swap_test.draw(output='mpl') swap_from_cnot = QuantumCircuit(qr) swap_from_cnot.cx(qr[0],qr[1]) swap_from_cnot.cx(qr[1],qr[0]) swap_from_cnot.cx(qr[0],qr[1]) swap_from_cnot.draw(output='mpl') qr_many = QuantumRegister(5) control_example = QuantumCircuit(qr_many) control_example.cy(qr_many[0],qr_many[1]) control_example.ch(qr_many[1],qr_many[2]) control_example.crz(0.2,qr_many[2],qr_many[3]) control_example.cu3(0.5, 0, 0, qr_many[3],qr_many[4]) control_example.draw(output='mpl') qrthree = QuantumRegister(3) toffoli_example = QuantumCircuit(qrthree) toffoli_example.ccx(0,1,2) toffoli_example.draw(output='mpl') toffoli_from_cnot = QuantumCircuit(qrthree) toffoli_from_cnot.h(qrthree[2]) toffoli_from_cnot.cx(qrthree[1],qrthree[2]) toffoli_from_cnot.tdg(qrthree[2]) toffoli_from_cnot.cx(qrthree[0],qrthree[2]) toffoli_from_cnot.t(qrthree[2]) toffoli_from_cnot.cx(qrthree[1],qrthree[2]) toffoli_from_cnot.tdg(qrthree[2]) toffoli_from_cnot.cx(qrthree[0],qrthree[2]) toffoli_from_cnot.tdg(qrthree[1]) toffoli_from_cnot.t(qrthree[2]) toffoli_from_cnot.h(qrthree[2]) toffoli_from_cnot.cx(qrthree[0],qrthree[1]) toffoli_from_cnot.tdg(qrthree[1]) toffoli_from_cnot.cx(qrthree[0],qrthree[1]) toffoli_from_cnot.s(qrthree[1]) toffoli_from_cnot.t(qrthree[0]) toffoli_from_cnot.draw(output='mpl') # Initializing a three-qubit quantum state import math desired_vector = [ 1 / math.sqrt(16) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(16) * complex(1, 1), 0, 0, 1 / math.sqrt(8) * complex(1, 2), 1 / math.sqrt(16) * complex(1, 0), 0] q = QuantumRegister(3) qc = QuantumCircuit(q) qc.initialize(desired_vector, [q[0],q[1],q[2]]) qc.draw(output='latex') backend = BasicAer.get_backend('statevector_simulator') job = execute(qc, backend) qc_state = job.result().get_statevector(qc) qc_state state_fidelity(desired_vector,qc_state)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, QuantumRegister from qiskit.circuit.library.standard_gates import HGate qr = QuantumRegister(3) qc = QuantumCircuit(qr) c3h_gate = HGate().control(2) qc.append(c3h_gate, qr) qc.draw('mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit_nature.second_q.hamiltonians import QuadraticHamiltonian # create Hamiltonian hermitian_part = np.array( [ [1.0, 2.0, 0.0, 0.0], [2.0, 1.0, 2.0, 0.0], [0.0, 2.0, 1.0, 2.0], [0.0, 0.0, 2.0, 1.0], ] ) antisymmetric_part = np.array( [ [0.0, 3.0, 0.0, 0.0], [-3.0, 0.0, 3.0, 0.0], [0.0, -3.0, 0.0, 3.0], [0.0, 0.0, -3.0, 0.0], ] ) constant = 4.0 hamiltonian = QuadraticHamiltonian( hermitian_part=hermitian_part, antisymmetric_part=antisymmetric_part, constant=constant, ) # convert it to a FermionicOp and print it hamiltonian_ferm = hamiltonian.second_q_op() print(hamiltonian_ferm) # get the transformation matrix W and orbital energies {epsilon_j} ( transformation_matrix, orbital_energies, transformed_constant, ) = hamiltonian.diagonalizing_bogoliubov_transform() print(f"Shape of matrix W: {transformation_matrix.shape}") print(f"Orbital energies: {orbital_energies}") print(f"Transformed constant: {transformed_constant}") from qiskit_nature.second_q.circuit.library import FermionicGaussianState occupied_orbitals = (0, 2) eig = np.sum(orbital_energies[list(occupied_orbitals)]) + transformed_constant print(f"Eigenvalue: {eig}") circuit = FermionicGaussianState(transformation_matrix, occupied_orbitals=occupied_orbitals) circuit.draw("mpl") from qiskit.quantum_info import Statevector from qiskit_nature.second_q.mappers import JordanWignerMapper # simulate the circuit to get the final state state = np.array(Statevector(circuit)) # convert the Hamiltonian to a matrix hamiltonian_jw = JordanWignerMapper().map(hamiltonian_ferm).to_matrix() # check that the state is an eigenvector with the expected eigenvalue np.testing.assert_allclose(hamiltonian_jw @ state, eig * state, atol=1e-8) # create Hamiltonian hermitian_part = np.array( [ [1.0, 2.0, 0.0, 0.0], [2.0, 1.0, 2.0, 0.0], [0.0, 2.0, 1.0, 2.0], [0.0, 0.0, 2.0, 1.0], ] ) constant = 4.0 hamiltonian = QuadraticHamiltonian( hermitian_part=hermitian_part, constant=constant, ) print(f"Hamiltonian conserves particle number: {hamiltonian.conserves_particle_number()}") # get the transformation matrix W and orbital energies {epsilon_j} ( transformation_matrix, orbital_energies, transformed_constant, ) = hamiltonian.diagonalizing_bogoliubov_transform() print(f"Shape of matrix W: {transformation_matrix.shape}") print(f"Orbital energies: {orbital_energies}") print(f"Transformed constant: {transformed_constant}") from qiskit_nature.second_q.circuit.library import SlaterDeterminant occupied_orbitals = (0, 2) eig = np.sum(orbital_energies[list(occupied_orbitals)]) + transformed_constant print(f"Eigenvalue: {eig}") circuit = SlaterDeterminant(transformation_matrix[list(occupied_orbitals)]) circuit.draw("mpl") from qiskit_nature.second_q.circuit.library import BogoliubovTransform from qiskit import QuantumCircuit, QuantumRegister from qiskit.quantum_info import random_hermitian, random_statevector, state_fidelity from scipy.linalg import expm # create Hamiltonian n_modes = 5 hermitian_part = np.array(random_hermitian(n_modes)) hamiltonian = QuadraticHamiltonian(hermitian_part=hermitian_part) # diagonalize Hamiltonian ( transformation_matrix, orbital_energies, _, ) = hamiltonian.diagonalizing_bogoliubov_transform() # set simulation time and construct time evolution circuit time = 1.0 register = QuantumRegister(n_modes) circuit = QuantumCircuit(register) bog_circuit = BogoliubovTransform(transformation_matrix) # change to the diagonal basis of the Hamiltonian circuit.append(bog_circuit.inverse(), register) # perform time evolution by applying z rotations for q, energy in zip(register, orbital_energies): circuit.rz(-energy * time, q) # change back to the original basis circuit.append(bog_circuit, register) # simulate the circuit initial_state = random_statevector(2**n_modes) final_state = initial_state.evolve(circuit) # compute the correct state by direct exponentiation hamiltonian_jw = JordanWignerMapper().map(hamiltonian.second_q_op()).to_matrix() exact_evolution_op = expm(-1j * time * hamiltonian_jw) expected_state = exact_evolution_op @ np.array(initial_state) # check that the simulated state is correct fidelity = state_fidelity(final_state, expected_state) np.testing.assert_allclose(fidelity, 1.0, atol=1e-8) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/andrewwack/Qiskit-primtives-bell-state
andrewwack
from qiskit import QuantumCircuit from qiskit.primitives import Sampler, BackendSampler from qiskit.circuit.library import * from qiskit.circuit.random import random_circuit from qiskit.visualization import plot_histogram, array_to_latex, plot_bloch_multivector from qiskit.quantum_info import Statevector from qiskit_ibm_runtime import Sampler, QiskitRuntimeService, Options, Session from qiskit.providers.fake_provider import FakeManila from qiskit_aer.noise import NoiseModel import numpy as np print('X (1q gate)') xgate = XGate() array_to_latex(xgate.to_matrix()) qc_x = QuantumCircuit(1) qc_x.x(0) qc_x.draw('mpl', scale=1.5) state = Statevector(qc_x) plot_bloch_multivector(state) qc_x = QuantumCircuit(1,1) qc_x.x(0) qc_x.measure([0],[0]) qc_x.draw('mpl', scale=1.5) # load the service and set the backend to the simulator service = QiskitRuntimeService(channel="ibm_quantum") backend = "ibmq_qasm_simulator" # Make a noise model fake_backend = FakeManila() noise_model = NoiseModel.from_backend(fake_backend) # Set options to include the noise model options = Options() options.simulator = { "noise_model": noise_model, "basis_gates": fake_backend.configuration().basis_gates, "coupling_map": fake_backend.configuration().coupling_map, "seed_simulator": 42 } # Set number of shots, optimization_level and resilience_level options.execution.shots = 1000 options.optimization_level = 0 options.resilience_level = 0 with Session(service=service, backend=backend): sampler = Sampler(options=options) job = sampler.run(qc_x) result_prob = job.result().quasi_dists[0].binary_probabilities() plot_histogram(result_prob) print('H (1q gate)') hgate = HGate() array_to_latex(hgate.to_matrix()) qc_h = QuantumCircuit(1,1) qc_h.h(0) qc_h.draw('mpl', scale=1.5) state = Statevector(qc_h) plot_bloch_multivector(state) qc_h.measure([0],[0]) with Session(service=service, backend=backend): sampler = Sampler(options=options) job = sampler.run(qc_h) result_prob = job.result().quasi_dists[0].binary_probabilities() plot_histogram(result_prob) options.resilience_level = 1 # add in M3 measurement mitigation with Session(service=service, backend=backend): sampler = Sampler(options=options) job = sampler.run(qc_h) result_prob = job.result().quasi_dists[0].binary_probabilities() plot_histogram(result_prob) qc_cx = QuantumCircuit(2) qc_cx.cx(0,1) qc_cx.draw('mpl') print('CX (2q gate)') cxgate = CXGate() array_to_latex(cxgate.to_matrix()) qc2 = QuantumCircuit(2, 2) qc2.h(0) qc2.h(1) qc2.draw('mpl', scale=1.5) state = Statevector(qc2) plot_bloch_multivector(state) qc2.measure([0,1],[0,1]) options.resilience_level = 0 # no error mitigation with Session(service=service, backend=backend): sampler = Sampler(options=options) job = sampler.run(qc2) result_prob = job.result().quasi_dists[0].binary_probabilities() plot_histogram(result_prob) options.resilience_level = 1 # add in M3 measurement mitigation with Session(service=service, backend=backend): sampler = Sampler(options=options) job = sampler.run(qc2) result_prob = job.result().quasi_dists[0].binary_probabilities() plot_histogram(result_prob) qc_bell = QuantumCircuit(2, 2) qc_bell.h(0) qc_bell.cx(0,1) qc_bell.draw('mpl') state = Statevector(qc_bell) plot_bloch_multivector(state) qc_bell.measure([0,1],[0,1]) # add the measurement options.resilience_level = 0 # no mitigation with Session(service=service, backend=backend): sampler = Sampler(options=options) job = sampler.run(qc_bell) result_prob = job.result().quasi_dists[0].binary_probabilities() plot_histogram(result_prob) options.resilience_level = 1 # add in M3 measurement mitigation with Session(service=service, backend=backend): sampler = Sampler(options=options) job = sampler.run(qc_bell) result_prob = job.result().quasi_dists[0].binary_probabilities() plot_histogram(result_prob) print(result_prob) least_busy_device = service.least_busy(filters=lambda b: b.configuration().simulator==False) least_busy_device hw_result = None with Session(service, backend=least_busy_device) as session: options = Options(resilience_level=0) sampler0 = Sampler(options=options) options = Options(resilience_level=1) sampler1 = Sampler(options=options) job0 = sampler0.run(circuits=[qc_bell], shots=8000) job1 = sampler1.run(circuits=[qc_bell], shots=8000) # You can see that the results are quasi probabilities, not counts hw_results = [job0.result().quasi_dists[0].binary_probabilities(), job1.result().quasi_dists[0].binary_probabilities()] print('Results resilience level 0 ', hw_results[0]) print('Results resilience level 1 ', hw_results[1]) plot_histogram(hw_results, legend=['resilience 0', 'resilience 1'])
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) # with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) # with open(filename, "wb") as f: # pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) # with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump(backend.properties(), f) retrieved_jobs = jobs retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/WhenTheyCry96/qiskitHackathon2022
WhenTheyCry96
import os import warnings warnings.filterwarnings('ignore') ws_path = os.getcwd() import numpy as np from scipy.constants import c, h, pi, hbar, e from qiskit_metal.analyses.em.cpw_calculations import guided_wavelength # constants: phi0 = h/(2*e) varphi0 = phi0/(2*pi) # project target parameters f_qList = np.around(np.linspace(5.25, 5.75, 4),2) # GHz f_rList = f_qList + 1.8 # GHz L_JJList = np.around(varphi0**2/((f_qList*1e9+300e6)**2/(8*300e6))/h*1e9, 2) # nH # initial CPW readout lengths def find_resonator_length(frequency, line_width, line_gap, N): #frequency in GHz #line_width/line_gap in um #N -> 2 for lambda/2, 4 for lambda/4 [lambdaG, etfSqrt, q] = guided_wavelength(frequency*10**9, line_width*10**-6, line_gap*10**-6, 750*10**-6, 200*10**-9) return str(lambdaG/N*10**3)+" mm" find_resonator_length(f_rList, 10, 6, 2) find_resonator_length(np.around(np.linspace(8, 8.5, 4),2), 10, 6, 2) from qiskit_metal import designs, MetalGUI design = designs.DesignPlanar() design.overwrite_enabled = True design.chips.main.size_x = '12mm' design.chips.main.size_y = '10mm' gui = MetalGUI(design) from qiskit_metal.qlibrary.qubits.transmon_pocket_cl import TransmonPocketCL design.delete_all_components() design_span_x = 5 design_span_y = 3 half_chip_width = design_span_x / 2 half_chip_height = design_span_y / 2 connection_pads_options = dict( B1 = dict(loc_W=1, loc_H=-1), R= dict(loc_W=1, loc_H=1), B2 = dict(loc_W=-1, loc_H=-1) ) transmons = [] transmons.append(TransmonPocketCL(design, 'Q1', options=dict(pos_x=f'0mm', pos_y=f'{half_chip_height}mm', orientation=0, connection_pads=dict(**connection_pads_options)))) gui.rebuild() gui.autoscale() transmons.append(TransmonPocketCL(design, 'Q2', options=dict(pos_x=f'{half_chip_width}mm', pos_y=f'0mm', orientation=-90, connection_pads=dict(**connection_pads_options)))) gui.rebuild() gui.autoscale() transmons.append(TransmonPocketCL(design, 'Q3', options=dict(pos_x=f'{-half_chip_width}mm', pos_y=f'0mm', orientation=90, connection_pads=dict(**connection_pads_options)))) gui.rebuild() gui.autoscale() transmons.append(TransmonPocketCL(design, 'Q4', options=dict(pos_x=f'0mm', pos_y=f'{-half_chip_height}mm', orientation=180, connection_pads=dict(**connection_pads_options)))) gui.rebuild() gui.autoscale() from qiskit_metal.qlibrary.tlines.meandered import RouteMeander from qiskit_metal import Dict fillet='99.99um' options = Dict( meander=Dict( lead_start='0.1mm', lead_end='0.1mm', asymmetry='0 um') ) def connect(component_name: str, component1: str, pin1: str, component2: str, pin2: str, length: str, asymmetry='0 um', start_strght='0 um', end_strght='0 um', flip=False): """Connect two pins with a CPW.""" myoptions = Dict( pin_inputs=Dict( start_pin=Dict( component=component1, pin=pin1), end_pin=Dict( component=component2, pin=pin2)), lead=Dict( start_straight=start_strght, end_straight=end_strght ), total_length=length, fillet = '99.9um') myoptions.update(options) myoptions.meander.asymmetry = asymmetry myoptions.meander.lead_direction_inverted = 'true' if flip else 'false' return RouteMeander(design, component_name, myoptions) cpw = [] asym_h = 200 cpw.append(connect('cpw1', 'Q1', 'B1', 'Q2', 'B2', '7.60 mm', f'-{asym_h}um', '0.1mm', '0.1mm')) asym_h = 200 cpw.append(connect('cpw2', 'Q4', 'B2', 'Q2', 'B1', '7.45 mm', f'{asym_h}um', '0.1mm', '0.1mm')) asym_h = 200 cpw.append(connect('cpw3', 'Q1', 'B2', 'Q3', 'B1', '7.30 mm', f'{asym_h}um', '0.1mm', '0.1mm')) asym_h = 200 cpw.append(connect('cpw4', 'Q4', 'B1', 'Q3', 'B2', '7.15 mm', f'-{asym_h}um', '0.1mm', '0.1mm')) gui.rebuild() gui.autoscale() from qiskit_metal.qlibrary.terminations.launchpad_wb_coupled import LaunchpadWirebondCoupled readouts_lwc = [] control_lwc = [] #Readouts readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R1', options = dict( pos_x=f'3mm', pos_y=f'{half_chip_height+3}mm', orientation = 180, lead_length = '30um'))) readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R2', options = dict( pos_x=f'{half_chip_width+3}mm', pos_y=f'-3mm', orientation = 90, lead_length = '30um'))) readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R3', options = dict( pos_x=f'{-half_chip_width-3}mm', pos_y=f'3mm', orientation = 0, lead_length = '30um'))) readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R4', options = dict( pos_x = f'-3mm', pos_y = f'{-half_chip_height-3}mm', orientation = 0, lead_length = '30um'))) gui.rebuild() gui.autoscale() from qiskit_metal.qlibrary.tlines.pathfinder import RoutePathfinder from qiskit_metal.qlibrary.lumped.cap_3_interdigital import Cap3Interdigital cap_Q1 = Cap3Interdigital(design, 'cap_Q1', options= dict( pos_x='2mm', pos_y=f'{half_chip_height+2}mm', orientation='180', finger_length = '40um')) readout_lines = [] options = Dict( lead=Dict( start_straight='400um', end_straight='400um'), fillet='99.99um') asym = 800 readout_lines.append(connect('ol1_c', 'Q1', 'R', 'cap_Q1', 'a', '8.63 mm', f'-{asym}um')) TL_Q1 = RoutePathfinder(design, 'TL_Q1', options = dict( fillet='99um', lead=dict(end_straight='150um'), pin_inputs=Dict( start_pin=Dict( component='R1', pin='tie'), end_pin=Dict( component='cap_Q1', pin='b') ))) cap_Q2 = Cap3Interdigital(design, 'cap_Q2', options= dict( pos_x=f'{half_chip_width+2}mm', pos_y=f'-2mm', orientation='90', finger_length = '40um')) readout_lines.append(connect('ol2', 'Q2', 'R', 'cap_Q2', 'a', '8.42 mm', f'-{asym}um')) TL_Q2 = RoutePathfinder(design, 'TL_Q2', options = dict( fillet='99um', lead=dict(end_straight='150um'), pin_inputs=Dict( start_pin=Dict( component='R2', pin='tie'), end_pin=Dict( component='cap_Q2', pin='b') ))) cap_Q3 = Cap3Interdigital(design, 'cap_Q3', options= dict( pos_x=f'{-half_chip_width-2}mm', pos_y=f'2mm', orientation='270', finger_length = '40um')) readout_lines.append(connect('ol3', 'Q3', 'R', 'cap_Q3', 'a', '8.25 mm', f'-{asym}um')) TL_Q3 = RoutePathfinder(design, 'TL_Q3', options = dict( fillet='99um', lead=dict(end_straight='150um'), pin_inputs=Dict( start_pin=Dict( component='R3', pin='tie'), end_pin=Dict( component='cap_Q3', pin='b') ))) options = Dict( lead=Dict( start_straight='400um', end_straight='400um'), fillet='99.99um') cap_Q4 = Cap3Interdigital(design, 'cap_Q4', options= dict( pos_x=f'-2mm', pos_y=f'{-half_chip_height-2}mm', orientation='0', finger_length = '40um')) readout_lines.append(connect('ol4', 'Q4', 'R', 'cap_Q4', 'a', '8.05 mm', f'-{asym}um')) TL_Q4 = RoutePathfinder(design, 'TL_Q4', options = dict( fillet='99um', lead=dict(end_straight='150um'), pin_inputs=Dict( start_pin=Dict( component='R4', pin='tie'), end_pin=Dict( component='cap_Q4', pin='b') ))) gui.rebuild() gui.autoscale() #Controls control_lwc.append(LaunchpadWirebondCoupled(design, 'CL1', options = dict( pos_x = f'-3mm', pos_y = f'3mm', orientation=0, lead_length = '30um'))) control_lwc.append(LaunchpadWirebondCoupled(design, 'CL2', options = dict( pos_x = f'3mm', pos_y = f'3mm', orientation = -90, lead_length = '30um'))) control_lwc.append(LaunchpadWirebondCoupled(design, 'CL3', options = dict( pos_x = f'-3mm', pos_y = f'-3mm', orientation = 90, lead_length = '30um'))) control_lwc.append(LaunchpadWirebondCoupled(design, 'CL4', options = dict( pos_x = f'2mm', pos_y = f'-3mm', orientation = 90, lead_length = '30um'))) gui.rebuild() gui.autoscale() from qiskit_metal.qlibrary.tlines.anchored_path import RouteAnchors from collections import OrderedDict import numpy as np control_lines = [] def connectRouteAnchor(name: str, component1: str, pin1: str, component2: str, pin2: str, anchor_points: OrderedDict) -> RouteAnchors: options_line_cl = dict( pin_inputs = dict(start_pin = dict(component = component1, pin = pin1), end_pin = dict(component = component2, pin = pin2)), anchors = anchor_points, lead = dict(start_straight = '200um', end_straight = '225um'), fillet = fillet ) return RouteAnchors(design, name, options_line_cl) anchors1c = OrderedDict() anchors1c[0] = np.array([-4, -1.42]) anchors1c[1] = np.array([-4, 2]) control_lines.append(connectRouteAnchor('line_cl1', 'Q1', 'Charge_Line', 'CL1', 'tie', anchors1c)) anchors2c = OrderedDict() anchors2c[0] = np.array([0.08, 3.25]) anchors2c[1] = np.array([4, 3.25]) control_lines.append(connectRouteAnchor('line_cl2', 'Q2', 'Charge_Line', 'CL2', 'tie', anchors2c)) anchors3c = OrderedDict() anchors3c[0] = np.array([-0.08, -3.25]) anchors3c[1] = np.array([-4, -3.25]) control_lines.append(connectRouteAnchor('line_cl3', 'Q3', 'Charge_Line', 'CL3', 'tie', anchors3c)) anchors4c = OrderedDict() anchors4c[0] = np.array([4, 1.42]) anchors4c[1] = np.array([4, -2]) control_lines.append(connectRouteAnchor('line_cl4', 'Q4', 'Charge_Line', 'CL4', 'tie', anchors4c)) gui.rebuild() gui.autoscale() from qiskit_metal.analyses.quantization import EPRanalysis eig_res1 = EPRanalysis(design, "hfss") hfss1 = eig_res1.sim.renderer hfss1.start() transmons[0].options.pad_gap = '40um' transmons[0].options.pad_width = '405um' transmons[0].options.pad_height = '90um' gui.rebuild() hfss1.activate_ansys_design("Tune_Q1", 'eigenmode') hfss1.render_design(['Q1'], [('Q1', 'c'), ('Q1', 'a'),('Q1', 'b'),('Q1', 'Charge_Line')]) # Analysis properties setup1 = hfss1.pinfo.setup setup1.passes = 10 setup1.n_modes = 3 print(f""" Number of eigenmodes to find = {setup1.n_modes} Number of simulation passes = {setup1.passes} Convergence freq max delta percent diff = {setup1.delta_f} """) # Next 2 lines are counterinuitive, since there is no junction in this resonator. # However, these are necessary to make pyEPR work correctly. Please do note delete hfss1.pinfo.design.set_variable('Lj', '12 nH') hfss1.pinfo.design.set_variable('Cj', '1 fF') setup1.analyze() eig_res1.sim.convergence_t, eig_res1.sim.convergence_f, _ = hfss1.get_convergences() eig_res1.sim.plot_convergences()
https://github.com/sintefmath/QuantumPoker
sintefmath
%matplotlib inline from os.path import dirname, abspath import sys sys.path.append(dirname(abspath(''))) from PokerGame import PokerGame import matplotlib.pyplot as plt from numpy import array nPlayers = 3 deckOfGates = {"H": nPlayers, "X": nPlayers, "ZH": nPlayers, "CX": nPlayers} money = array([100 for i in range(nPlayers)]) names = ["James", "Lilly", "Harry"] pokerGame = PokerGame(deckOfGates, nPlayers, money, names = names, smallBlind=5, smallBlindPlayer=0, seed=4, enableEntanglement=True) fig = pokerGame.interactive.fig pokerGame.interactiveButtons.showHand(None, updateBoard=False) fig pokerGame.fold() pokerGame.interactiveButtons.showHand(None, updateBoard=False) fig pokerGame.check() pokerGame.check() fig pokerGame.bet(10) fig pokerGame.check() pokerGame.check() pokerGame.check() pokerGame.interactiveButtons.checkBellStates2(None) pokerGame.mouseClick(1) pokerGame.mouseClick(4) fig pokerGame.check() pokerGame.check() fig pokerGame.interactiveButtons.CX(None) pokerGame.mouseClick(1) pokerGame.mouseClick(4) fig pokerGame.interactiveButtons.X(None) pokerGame.mouseClick(2) pokerGame.interactiveButtons.ZH(None) pokerGame.mouseClick(4) fig pokerGame.endGateTurn(None) fig pokerGame.interactiveButtons.X(None) pokerGame.mouseClick(2) pokerGame.interactiveButtons.H(None) pokerGame.mouseClick(3) fig pokerGame.endGateTurn(None) fig
https://github.com/ctuning/ck-qiskit
ctuning
#!/usr/bin/env python3 """ Example used in the readme. In this example a Bell state is made and then measured. ## Running this script using the "lightweight" CK infrastructure to import QISKit library... # 1) on local simulator: ck virtual env --tags=lib,qiskit --shell_cmd=quantum_coin_flip.py # 2) on remote simulator (need the API Token from IBM QuantumExperience) : CK_IBM_BACKEND=ibmq_qasm_simulator ck virtual `ck search env:* --tags=qiskit,lib` `ck search env:* --tags=ibmqx,login` --shell_cmd=quantum_coin_flip.py # 3) on remote quantum hardware (need the API Token from IBM QuantumExperience) : CK_IBM_BACKEND=ibmqx4 ck virtual `ck search env:* --tags=qiskit,lib` `ck search env:* --tags=ibmqx,login` --shell_cmd=quantum_coin_flip.py """ import sys import os # We don't know from where the user is running the example, # so we need a relative position from this file path. # TODO: Relative imports for intra-package imports are highly discouraged. # http://stackoverflow.com/a/7506006 sys.path.append(os.path.join(os.path.dirname(__file__), '../..')) from qiskit import QuantumProgram, QISKitError, available_backends, register try: import Qconfig register(Qconfig.APItoken, Qconfig.config["url"], verify=False, hub=Qconfig.config["hub"], group=Qconfig.config["group"], project=Qconfig.config["project"]) except: print(""" WARNING: There's no connection with IBMQuantumExperience servers. cannot test I/O intesive tasks, will only test CPU intensive tasks running the jobs in the local simulator """) available_backends = available_backends() print("The backends available for use are: {}\n".format(available_backends)) backend = os.environ.get('CK_IBM_BACKEND', 'local_qasm_simulator') email = os.environ.get('CK_IBM_API_EMAIL', 'N/A') print("User email: {}\n".format(email)) timeout = int( os.environ.get('CK_IBM_TIMEOUT', 120) ) shots = int( os.environ.get('CK_IBM_REPETITION', 10) ) # Create a QuantumProgram object instance. Q_program = QuantumProgram() try: # Create a Quantum Register called "qr" with 2 qubits. qr = Q_program.create_quantum_register("qr", 2) # Create a Classical Register called "cr" with 2 bits. cr = Q_program.create_classical_register("cr", 2) # Create a Quantum Circuit called "qc" with the Quantum Register "qr" # and the Classical Register "cr". qc = Q_program.create_circuit("bell", [qr], [cr]) # Add an H gate to qubit 0, putting this qubit in superposition. qc.h(qr[0]) # Add a CX gate to control qubit 0 and target qubit 1, putting # the qubits in a Bell state. qc.cx(qr[0], qr[1]) # Add a Measure gate to observe the state. qc.measure(qr, cr) # Compile and execute the Quantum Program using the given backend. result = Q_program.execute(["bell"], backend=backend, shots=shots, seed=1, timeout=timeout) # Show the results. print(result) # 'COMPLETED' q_execution_time = result.get_data().get('time') if q_execution_time: print("Quantum execution time: {} sec".format(q_execution_time) ) print(result.get_data("bell")) except QISKitError as ex: print('Error in the circuit! {}'.format(ex)) ########################### Save output to CK format. ############################## import json import numpy as np # See https://stackoverflow.com/questions/26646362/numpy-array-is-not-json-serializable # class NumpyEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, np.ndarray): return obj.tolist() elif isinstance(obj, np.bool_): return bool(obj) elif isinstance(obj, np.complex): return obj.real # if you care about the imaginary part, try (obj.real, obj.imag) return json.JSONEncoder.default(self, obj) output_dict = { 'backends': available_backends, 'email': email, 'result': result.get_data("bell"), } formatted_json = json.dumps(output_dict, cls=NumpyEncoder, sort_keys = True, indent = 4) #print(formatted_json) with open('tmp-ck-timer.json', 'w') as json_file: json_file.write( formatted_json )
https://github.com/daimurat/qiskit-implementation
daimurat
pip install qiskit-aer import numpy as np from qiskit import QuantumCircuit from qiskit import Aer, transpile from qiskit.tools.visualization import plot_histogram, plot_state_city import qiskit.quantum_info as pi Aer.backends() simulator = Aer.get_backend('aer_simulator') circ = QuantumCircuit(2) circ.h(0) circ.cx(0,1) circ.measure_all() simulator = Aer.get_backend('aer_simulator') circ =transpile(circ, simulator) result =simulator.run(circ).result() counts =result.get_counts(circ) plot_histogram(counts, title= "Bell-State counts") result =simulator.run(circ,shots=10, memory=True).result() memory =result.get_memory(circ) print(memory) shots = 10000 sim_stabilizer = Aer.get_backend('aer_simulator_stabilizer') job_stabilizer = sim_stabilizer.run(circ, shots=shots) counts_stabilizer = job_stabilizer.result().get_counts(0) sim_statevector = Aer.get_backend('aer_simulator_statevector') job_statevector =sim_statevector.run(circ, shots=shots) counts_statevector = job_statevector.result().get_counts(0) sim_density = Aer.get_backend('aer_simulator_density_matrix') job_density = sim_density.run(circ, shots=shots) counts_density = job_density.result().get_counts(0) sim_mps = Aer.get_backend('aer_simulator_matrix_product_state') job_mps = sim_mps.run(circ, shots=shots) counts_mps =job_mps.result().get_counts(0) plot_histogram([counts_stabilizer, counts_statevector, counts_density, counts_mps], title='Counts for different simulation methods', legend=['stabilizer', 'statevector', 'density_matrix', 'matrix_product_state']) from qiskit_aer import AerError try: simulator_gpu = Aer.get_backend('aer_simulator') simulator_gpu.set_options(device='GPU') except AerError as e: print(e) simulator = Aer.get_backend('aer_simulator_statevector') simulator.set_options(precision='single') result =simulator.run(circ).result() counts =result.get_counts(circ) print(counts) circ = QuantumCircuit(2) circ.h(0) circ.cx(0, 1) circ.save_statevector() simulator = Aer.get_backend('aer_simulator') circ =transpile(circ, simulator) result =simulator.run(circ).result() statevector= result.get_statevector(circ) plot_state_city(statevector,title='Bell state') steps = 5 circ = QuantumCircuit(1) for i in range(steps): circ.save_statevector(label=f'psi_{i}') circ.rx(i * np.pi / steps, 0) circ.save_statevector(label=f'psi_{steps}') simulator = Aer.get_backend('aer_simulator') circ =transpile(circ, simulator) result =simulator.run(circ).result() data =result.data(0) data # Generate a random statevector num_qubits = 2 psi = random_statevector(2 ** num_qubits, seed=100) # Set initial state to generated statevector circ = QuantumCircuit(num_qubits) circ.set_statevector(psi) circ.save_state() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get saved data result = simulator.run(circ).result() result.data(0) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for DensityMatrix quantum state class.""" import logging import unittest import numpy as np from ddt import data, ddt from numpy.testing import assert_allclose from qiskit import QiskitError, QuantumCircuit, QuantumRegister from qiskit.circuit.library import QFT, HGate from qiskit.quantum_info.operators.operator import Operator from qiskit.quantum_info.operators.symplectic import Pauli, SparsePauliOp from qiskit.quantum_info.random import random_density_matrix, random_pauli, random_unitary from qiskit.quantum_info.states import DensityMatrix, Statevector from qiskit.test import QiskitTestCase from qiskit.utils import optionals logger = logging.getLogger(__name__) @ddt class TestDensityMatrix(QiskitTestCase): """Tests for DensityMatrix class.""" @classmethod def rand_vec(cls, n, normalize=False): """Return complex vector or statevector""" seed = np.random.randint(0, np.iinfo(np.int32).max) logger.debug("rand_vec default_rng seeded with seed=%s", seed) rng = np.random.default_rng(seed) vec = rng.random(n) + 1j * rng.random(n) if normalize: vec /= np.sqrt(np.dot(vec, np.conj(vec))) return vec @classmethod def rand_rho(cls, n): """Return random pure state density matrix""" rho = cls.rand_vec(n, normalize=True) return np.outer(rho, np.conjugate(rho)) def test_init_array_qubit(self): """Test subsystem initialization from N-qubit array.""" # Test automatic inference of qubit subsystems rho = self.rand_rho(8) for dims in [None, 8]: state = DensityMatrix(rho, dims=dims) assert_allclose(state.data, rho) self.assertEqual(state.dim, 8) self.assertEqual(state.dims(), (2, 2, 2)) self.assertEqual(state.num_qubits, 3) def test_init_array(self): """Test initialization from array.""" rho = self.rand_rho(3) state = DensityMatrix(rho) assert_allclose(state.data, rho) self.assertEqual(state.dim, 3) self.assertEqual(state.dims(), (3,)) self.assertIsNone(state.num_qubits) rho = self.rand_rho(2 * 3 * 4) state = DensityMatrix(rho, dims=[2, 3, 4]) assert_allclose(state.data, rho) self.assertEqual(state.dim, 2 * 3 * 4) self.assertEqual(state.dims(), (2, 3, 4)) self.assertIsNone(state.num_qubits) def test_init_array_except(self): """Test initialization exception from array.""" rho = self.rand_rho(4) self.assertRaises(QiskitError, DensityMatrix, rho, dims=[4, 2]) self.assertRaises(QiskitError, DensityMatrix, rho, dims=[2, 4]) self.assertRaises(QiskitError, DensityMatrix, rho, dims=5) def test_init_densitymatrix(self): """Test initialization from DensityMatrix.""" rho1 = DensityMatrix(self.rand_rho(4)) rho2 = DensityMatrix(rho1) self.assertEqual(rho1, rho2) def test_init_statevector(self): """Test initialization from DensityMatrix.""" vec = self.rand_vec(4) target = DensityMatrix(np.outer(vec, np.conjugate(vec))) rho = DensityMatrix(Statevector(vec)) self.assertEqual(rho, target) def test_init_circuit(self): """Test initialization from a circuit.""" # random unitaries u0 = random_unitary(2).data u1 = random_unitary(2).data # add to circuit qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.unitary(u0, [qr[0]]) circ.unitary(u1, [qr[1]]) target_vec = Statevector(np.kron(u1, u0).dot([1, 0, 0, 0])) target = DensityMatrix(target_vec) rho = DensityMatrix(circ) self.assertEqual(rho, target) # Test tensor product of 1-qubit gates circuit = QuantumCircuit(3) circuit.h(0) circuit.x(1) circuit.ry(np.pi / 2, 2) target = DensityMatrix.from_label("000").evolve(Operator(circuit)) rho = DensityMatrix(circuit) self.assertEqual(rho, target) # Test decomposition of Controlled-Phase gate lam = np.pi / 4 circuit = QuantumCircuit(2) circuit.h(0) circuit.h(1) circuit.cp(lam, 0, 1) target = DensityMatrix.from_label("00").evolve(Operator(circuit)) rho = DensityMatrix(circuit) self.assertEqual(rho, target) def test_from_circuit(self): """Test initialization from a circuit.""" # random unitaries u0 = random_unitary(2).data u1 = random_unitary(2).data # add to circuit qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.unitary(u0, [qr[0]]) circ.unitary(u1, [qr[1]]) # Test decomposition of controlled-H gate circuit = QuantumCircuit(2) circ.x(0) circuit.ch(0, 1) target = DensityMatrix.from_label("00").evolve(Operator(circuit)) rho = DensityMatrix.from_instruction(circuit) self.assertEqual(rho, target) # Test initialize instruction init = Statevector([1, 0, 0, 1j]) / np.sqrt(2) target = DensityMatrix(init) circuit = QuantumCircuit(2) circuit.initialize(init.data, [0, 1]) rho = DensityMatrix.from_instruction(circuit) self.assertEqual(rho, target) # Test reset instruction target = DensityMatrix([1, 0]) circuit = QuantumCircuit(1) circuit.h(0) circuit.reset(0) rho = DensityMatrix.from_instruction(circuit) self.assertEqual(rho, target) def test_from_instruction(self): """Test initialization from an instruction.""" target_vec = Statevector(np.dot(HGate().to_matrix(), [1, 0])) target = DensityMatrix(target_vec) rho = DensityMatrix.from_instruction(HGate()) self.assertEqual(rho, target) def test_from_label(self): """Test initialization from a label""" x_p = DensityMatrix(np.array([[0.5, 0.5], [0.5, 0.5]])) x_m = DensityMatrix(np.array([[0.5, -0.5], [-0.5, 0.5]])) y_p = DensityMatrix(np.array([[0.5, -0.5j], [0.5j, 0.5]])) y_m = DensityMatrix(np.array([[0.5, 0.5j], [-0.5j, 0.5]])) z_p = DensityMatrix(np.diag([1, 0])) z_m = DensityMatrix(np.diag([0, 1])) label = "0+r" target = z_p.tensor(x_p).tensor(y_p) self.assertEqual(target, DensityMatrix.from_label(label)) label = "-l1" target = x_m.tensor(y_m).tensor(z_m) self.assertEqual(target, DensityMatrix.from_label(label)) def test_equal(self): """Test __eq__ method""" for _ in range(10): rho = self.rand_rho(4) self.assertEqual(DensityMatrix(rho), DensityMatrix(rho.tolist())) def test_copy(self): """Test DensityMatrix copy method""" for _ in range(5): rho = self.rand_rho(4) orig = DensityMatrix(rho) cpy = orig.copy() cpy._data[0] += 1.0 self.assertFalse(cpy == orig) def test_is_valid(self): """Test is_valid method.""" state = DensityMatrix(np.eye(2)) self.assertFalse(state.is_valid()) for _ in range(10): state = DensityMatrix(self.rand_rho(4)) self.assertTrue(state.is_valid()) def test_to_operator(self): """Test to_operator method for returning projector.""" for _ in range(10): rho = self.rand_rho(4) target = Operator(rho) op = DensityMatrix(rho).to_operator() self.assertEqual(op, target) def test_evolve(self): """Test evolve method for operators.""" for _ in range(10): op = random_unitary(4) rho = self.rand_rho(4) target = DensityMatrix(np.dot(op.data, rho).dot(op.adjoint().data)) evolved = DensityMatrix(rho).evolve(op) self.assertEqual(target, evolved) def test_evolve_subsystem(self): """Test subsystem evolve method for operators.""" # Test evolving single-qubit of 3-qubit system for _ in range(5): rho = self.rand_rho(8) state = DensityMatrix(rho) op0 = random_unitary(2) op1 = random_unitary(2) op2 = random_unitary(2) # Test evolve on 1-qubit op = op0 op_full = Operator(np.eye(4)).tensor(op) target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data)) self.assertEqual(state.evolve(op, qargs=[0]), target) # Evolve on qubit 1 op_full = Operator(np.eye(2)).tensor(op).tensor(np.eye(2)) target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data)) self.assertEqual(state.evolve(op, qargs=[1]), target) # Evolve on qubit 2 op_full = op.tensor(np.eye(4)) target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data)) self.assertEqual(state.evolve(op, qargs=[2]), target) # Test evolve on 2-qubits op = op1.tensor(op0) # Evolve on qubits [0, 2] op_full = op1.tensor(np.eye(2)).tensor(op0) target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data)) self.assertEqual(state.evolve(op, qargs=[0, 2]), target) # Evolve on qubits [2, 0] op_full = op0.tensor(np.eye(2)).tensor(op1) target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data)) self.assertEqual(state.evolve(op, qargs=[2, 0]), target) # Test evolve on 3-qubits op = op2.tensor(op1).tensor(op0) # Evolve on qubits [0, 1, 2] op_full = op target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data)) self.assertEqual(state.evolve(op, qargs=[0, 1, 2]), target) # Evolve on qubits [2, 1, 0] op_full = op0.tensor(op1).tensor(op2) target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data)) self.assertEqual(state.evolve(op, qargs=[2, 1, 0]), target) def test_evolve_qudit_subsystems(self): """Test nested evolve calls on qudit subsystems.""" dims = (3, 4, 5) init = self.rand_rho(np.prod(dims)) ops = [random_unitary((dim,)) for dim in dims] state = DensityMatrix(init, dims) for i, op in enumerate(ops): state = state.evolve(op, [i]) target_op = np.eye(1) for op in ops: target_op = np.kron(op.data, target_op) target = DensityMatrix(np.dot(target_op, init).dot(target_op.conj().T), dims) self.assertEqual(state, target) def test_conjugate(self): """Test conjugate method.""" for _ in range(10): rho = self.rand_rho(4) target = DensityMatrix(np.conj(rho)) state = DensityMatrix(rho).conjugate() self.assertEqual(state, target) def test_expand(self): """Test expand method.""" for _ in range(10): rho0 = self.rand_rho(2) rho1 = self.rand_rho(3) target = np.kron(rho1, rho0) state = DensityMatrix(rho0).expand(DensityMatrix(rho1)) self.assertEqual(state.dim, 6) self.assertEqual(state.dims(), (2, 3)) assert_allclose(state.data, target) def test_tensor(self): """Test tensor method.""" for _ in range(10): rho0 = self.rand_rho(2) rho1 = self.rand_rho(3) target = np.kron(rho0, rho1) state = DensityMatrix(rho0).tensor(DensityMatrix(rho1)) self.assertEqual(state.dim, 6) self.assertEqual(state.dims(), (3, 2)) assert_allclose(state.data, target) def test_add(self): """Test add method.""" for _ in range(10): rho0 = self.rand_rho(4) rho1 = self.rand_rho(4) state0 = DensityMatrix(rho0) state1 = DensityMatrix(rho1) self.assertEqual(state0 + state1, DensityMatrix(rho0 + rho1)) def test_add_except(self): """Test add method raises exceptions.""" state1 = DensityMatrix(self.rand_rho(2)) state2 = DensityMatrix(self.rand_rho(3)) self.assertRaises(QiskitError, state1.__add__, state2) def test_subtract(self): """Test subtract method.""" for _ in range(10): rho0 = self.rand_rho(4) rho1 = self.rand_rho(4) state0 = DensityMatrix(rho0) state1 = DensityMatrix(rho1) self.assertEqual(state0 - state1, DensityMatrix(rho0 - rho1)) def test_multiply(self): """Test multiply method.""" for _ in range(10): rho = self.rand_rho(4) state = DensityMatrix(rho) val = np.random.rand() + 1j * np.random.rand() self.assertEqual(val * state, DensityMatrix(val * state)) def test_negate(self): """Test negate method""" for _ in range(10): rho = self.rand_rho(4) state = DensityMatrix(rho) self.assertEqual(-state, DensityMatrix(-1 * rho)) def test_to_dict(self): """Test to_dict method""" with self.subTest(msg="dims = (2, 2)"): rho = DensityMatrix(np.arange(1, 17).reshape(4, 4)) target = { "00|00": 1, "01|00": 2, "10|00": 3, "11|00": 4, "00|01": 5, "01|01": 6, "10|01": 7, "11|01": 8, "00|10": 9, "01|10": 10, "10|10": 11, "11|10": 12, "00|11": 13, "01|11": 14, "10|11": 15, "11|11": 16, } self.assertDictAlmostEqual(target, rho.to_dict()) with self.subTest(msg="dims = (2, 3)"): rho = DensityMatrix(np.diag(np.arange(1, 7)), dims=(2, 3)) target = {} for i in range(2): for j in range(3): key = "{1}{0}|{1}{0}".format(i, j) target[key] = 2 * j + i + 1 self.assertDictAlmostEqual(target, rho.to_dict()) with self.subTest(msg="dims = (2, 11)"): vec = DensityMatrix(np.diag(np.arange(1, 23)), dims=(2, 11)) target = {} for i in range(2): for j in range(11): key = "{1},{0}|{1},{0}".format(i, j) target[key] = 2 * j + i + 1 self.assertDictAlmostEqual(target, vec.to_dict()) def test_densitymatrix_to_statevector_pure(self): """Test converting a pure density matrix to statevector.""" state = 1 / np.sqrt(2) * (np.array([1, 0, 0, 0, 0, 0, 0, 1])) psi = Statevector(state) rho = DensityMatrix(psi) phi = rho.to_statevector() self.assertTrue(psi.equiv(phi)) def test_densitymatrix_to_statevector_mixed(self): """Test converting a pure density matrix to statevector.""" state_1 = 1 / np.sqrt(2) * (np.array([1, 0, 0, 0, 0, 0, 0, 1])) state_2 = 1 / np.sqrt(2) * (np.array([0, 0, 0, 0, 0, 0, 1, 1])) psi = 0.5 * (Statevector(state_1) + Statevector(state_2)) rho = DensityMatrix(psi) self.assertRaises(QiskitError, rho.to_statevector) def test_probabilities_product(self): """Test probabilities method for product state""" state = DensityMatrix.from_label("+0") # 2-qubit qargs with self.subTest(msg="P(None)"): probs = state.probabilities() target = np.array([0.5, 0, 0.5, 0]) self.assertTrue(np.allclose(probs, target)) with self.subTest(msg="P([0, 1])"): probs = state.probabilities([0, 1]) target = np.array([0.5, 0, 0.5, 0]) self.assertTrue(np.allclose(probs, target)) with self.subTest(msg="P([1, 0]"): probs = state.probabilities([1, 0]) target = np.array([0.5, 0.5, 0, 0]) self.assertTrue(np.allclose(probs, target)) # 1-qubit qargs with self.subTest(msg="P([0])"): probs = state.probabilities([0]) target = np.array([1, 0]) self.assertTrue(np.allclose(probs, target)) with self.subTest(msg="P([1])"): probs = state.probabilities([1]) target = np.array([0.5, 0.5]) self.assertTrue(np.allclose(probs, target)) def test_probabilities_ghz(self): """Test probabilities method for GHZ state""" psi = (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2) state = DensityMatrix(psi) # 3-qubit qargs target = np.array([0.5, 0, 0, 0, 0, 0, 0, 0.5]) for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) # 2-qubit qargs target = np.array([0.5, 0, 0, 0.5]) for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) # 1-qubit qargs target = np.array([0.5, 0.5]) for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) def test_probabilities_w(self): """Test probabilities method with W state""" psi = ( Statevector.from_label("001") + Statevector.from_label("010") + Statevector.from_label("100") ) / np.sqrt(3) state = DensityMatrix(psi) # 3-qubit qargs target = np.array([0, 1 / 3, 1 / 3, 0, 1 / 3, 0, 0, 0]) for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) # 2-qubit qargs target = np.array([1 / 3, 1 / 3, 1 / 3, 0]) for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) # 1-qubit qargs target = np.array([2 / 3, 1 / 3]) for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) def test_probabilities_dict_product(self): """Test probabilities_dict method for product state""" state = DensityMatrix.from_label("+0") # 2-qubit qargs with self.subTest(msg="P(None)"): probs = state.probabilities_dict() target = {"00": 0.5, "10": 0.5} self.assertDictAlmostEqual(probs, target) with self.subTest(msg="P([0, 1])"): probs = state.probabilities_dict([0, 1]) target = {"00": 0.5, "10": 0.5} self.assertDictAlmostEqual(probs, target) with self.subTest(msg="P([1, 0]"): probs = state.probabilities_dict([1, 0]) target = {"00": 0.5, "01": 0.5} self.assertDictAlmostEqual(probs, target) # 1-qubit qargs with self.subTest(msg="P([0])"): probs = state.probabilities_dict([0]) target = {"0": 1} self.assertDictAlmostEqual(probs, target) with self.subTest(msg="P([1])"): probs = state.probabilities_dict([1]) target = {"0": 0.5, "1": 0.5} self.assertDictAlmostEqual(probs, target) def test_probabilities_dict_ghz(self): """Test probabilities_dict method for GHZ state""" psi = (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2) state = DensityMatrix(psi) # 3-qubit qargs target = {"000": 0.5, "111": 0.5} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) # 2-qubit qargs target = {"00": 0.5, "11": 0.5} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) # 1-qubit qargs target = {"0": 0.5, "1": 0.5} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) def test_probabilities_dict_w(self): """Test probabilities_dict method with W state""" psi = ( Statevector.from_label("001") + Statevector.from_label("010") + Statevector.from_label("100") ) / np.sqrt(3) state = DensityMatrix(psi) # 3-qubit qargs target = np.array([0, 1 / 3, 1 / 3, 0, 1 / 3, 0, 0, 0]) target = {"001": 1 / 3, "010": 1 / 3, "100": 1 / 3} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) # 2-qubit qargs target = {"00": 1 / 3, "01": 1 / 3, "10": 1 / 3} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) # 1-qubit qargs target = {"0": 2 / 3, "1": 1 / 3} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) def test_sample_counts_ghz(self): """Test sample_counts method for GHZ state""" shots = 2000 threshold = 0.02 * shots state = DensityMatrix( (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2) ) state.seed(100) # 3-qubit qargs target = {"000": shots / 2, "111": shots / 2} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"counts (qargs={qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) # 2-qubit qargs target = {"00": shots / 2, "11": shots / 2} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"counts (qargs={qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) # 1-qubit qargs target = {"0": shots / 2, "1": shots / 2} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"counts (qargs={qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) def test_sample_counts_w(self): """Test sample_counts method for W state""" shots = 3000 threshold = 0.02 * shots state = DensityMatrix( ( Statevector.from_label("001") + Statevector.from_label("010") + Statevector.from_label("100") ) / np.sqrt(3) ) state.seed(100) target = {"001": shots / 3, "010": shots / 3, "100": shots / 3} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) # 2-qubit qargs target = {"00": shots / 3, "01": shots / 3, "10": shots / 3} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"P({qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) # 1-qubit qargs target = {"0": 2 * shots / 3, "1": shots / 3} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) def test_probabilities_dict_unequal_dims(self): """Test probabilities_dict for a state with unequal subsystem dimensions.""" vec = np.zeros(60, dtype=float) vec[15:20] = np.ones(5) vec[40:46] = np.ones(6) state = DensityMatrix(vec / np.sqrt(11.0), dims=[3, 4, 5]) p = 1.0 / 11.0 self.assertDictEqual( state.probabilities_dict(), { s: p for s in [ "110", "111", "112", "120", "121", "311", "312", "320", "321", "322", "330", ] }, ) # differences due to rounding self.assertDictAlmostEqual( state.probabilities_dict(qargs=[0]), {"0": 4 * p, "1": 4 * p, "2": 3 * p}, delta=1e-10 ) self.assertDictAlmostEqual( state.probabilities_dict(qargs=[1]), {"1": 5 * p, "2": 5 * p, "3": p}, delta=1e-10 ) self.assertDictAlmostEqual( state.probabilities_dict(qargs=[2]), {"1": 5 * p, "3": 6 * p}, delta=1e-10 ) self.assertDictAlmostEqual( state.probabilities_dict(qargs=[0, 1]), {"10": p, "11": 2 * p, "12": 2 * p, "20": 2 * p, "21": 2 * p, "22": p, "30": p}, delta=1e-10, ) self.assertDictAlmostEqual( state.probabilities_dict(qargs=[1, 0]), {"01": p, "11": 2 * p, "21": 2 * p, "02": 2 * p, "12": 2 * p, "22": p, "03": p}, delta=1e-10, ) self.assertDictAlmostEqual( state.probabilities_dict(qargs=[0, 2]), {"10": 2 * p, "11": 2 * p, "12": p, "31": 2 * p, "32": 2 * p, "30": 2 * p}, delta=1e-10, ) def test_sample_counts_qutrit(self): """Test sample_counts method for qutrit state""" p = 0.3 shots = 1000 threshold = 0.03 * shots state = DensityMatrix(np.diag([p, 0, 1 - p])) state.seed(100) with self.subTest(msg="counts"): target = {"0": shots * p, "2": shots * (1 - p)} counts = state.sample_counts(shots=shots) self.assertDictAlmostEqual(counts, target, threshold) def test_sample_memory_ghz(self): """Test sample_memory method for GHZ state""" shots = 2000 state = DensityMatrix( (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2) ) state.seed(100) # 3-qubit qargs target = {"000": shots / 2, "111": shots / 2} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) # 2-qubit qargs target = {"00": shots / 2, "11": shots / 2} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) # 1-qubit qargs target = {"0": shots / 2, "1": shots / 2} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) def test_sample_memory_w(self): """Test sample_memory method for W state""" shots = 3000 state = DensityMatrix( ( Statevector.from_label("001") + Statevector.from_label("010") + Statevector.from_label("100") ) / np.sqrt(3) ) state.seed(100) target = {"001": shots / 3, "010": shots / 3, "100": shots / 3} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) # 2-qubit qargs target = {"00": shots / 3, "01": shots / 3, "10": shots / 3} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) # 1-qubit qargs target = {"0": 2 * shots / 3, "1": shots / 3} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) def test_sample_memory_qutrit(self): """Test sample_memory method for qutrit state""" p = 0.3 shots = 1000 state = DensityMatrix(np.diag([p, 0, 1 - p])) state.seed(100) with self.subTest(msg="memory"): memory = state.sample_memory(shots) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), {"0", "2"}) def test_reset_2qubit(self): """Test reset method for 2-qubit state""" state = DensityMatrix(np.diag([0.5, 0, 0, 0.5])) with self.subTest(msg="reset"): rho = state.copy() value = rho.reset() target = DensityMatrix(np.diag([1, 0, 0, 0])) self.assertEqual(value, target) with self.subTest(msg="reset"): rho = state.copy() value = rho.reset([0, 1]) target = DensityMatrix(np.diag([1, 0, 0, 0])) self.assertEqual(value, target) with self.subTest(msg="reset [0]"): rho = state.copy() value = rho.reset([0]) target = DensityMatrix(np.diag([0.5, 0, 0.5, 0])) self.assertEqual(value, target) with self.subTest(msg="reset [0]"): rho = state.copy() value = rho.reset([1]) target = DensityMatrix(np.diag([0.5, 0.5, 0, 0])) self.assertEqual(value, target) def test_reset_qutrit(self): """Test reset method for qutrit""" state = DensityMatrix(np.diag([1, 1, 1]) / 3) state.seed(200) value = state.reset() target = DensityMatrix(np.diag([1, 0, 0])) self.assertEqual(value, target) def test_measure_2qubit(self): """Test measure method for 2-qubit state""" state = DensityMatrix.from_label("+0") seed = 200 shots = 100 with self.subTest(msg="measure"): for i in range(shots): rho = state.copy() rho.seed(seed + i) outcome, value = rho.measure() self.assertIn(outcome, ["00", "10"]) if outcome == "00": target = DensityMatrix.from_label("00") self.assertEqual(value, target) else: target = DensityMatrix.from_label("10") self.assertEqual(value, target) with self.subTest(msg="measure [0, 1]"): for i in range(shots): rho = state.copy() outcome, value = rho.measure([0, 1]) self.assertIn(outcome, ["00", "10"]) if outcome == "00": target = DensityMatrix.from_label("00") self.assertEqual(value, target) else: target = DensityMatrix.from_label("10") self.assertEqual(value, target) with self.subTest(msg="measure [1, 0]"): for i in range(shots): rho = state.copy() outcome, value = rho.measure([1, 0]) self.assertIn(outcome, ["00", "01"]) if outcome == "00": target = DensityMatrix.from_label("00") self.assertEqual(value, target) else: target = DensityMatrix.from_label("10") self.assertEqual(value, target) with self.subTest(msg="measure [0]"): for i in range(shots): rho = state.copy() outcome, value = rho.measure([0]) self.assertEqual(outcome, "0") target = DensityMatrix.from_label("+0") self.assertEqual(value, target) with self.subTest(msg="measure [1]"): for i in range(shots): rho = state.copy() outcome, value = rho.measure([1]) self.assertIn(outcome, ["0", "1"]) if outcome == "0": target = DensityMatrix.from_label("00") self.assertEqual(value, target) else: target = DensityMatrix.from_label("10") self.assertEqual(value, target) def test_measure_qutrit(self): """Test measure method for qutrit""" state = DensityMatrix(np.diag([1, 1, 1]) / 3) seed = 200 shots = 100 for i in range(shots): rho = state.copy() rho.seed(seed + i) outcome, value = rho.measure() self.assertIn(outcome, ["0", "1", "2"]) if outcome == "0": target = DensityMatrix(np.diag([1, 0, 0])) self.assertEqual(value, target) elif outcome == "1": target = DensityMatrix(np.diag([0, 1, 0])) self.assertEqual(value, target) else: target = DensityMatrix(np.diag([0, 0, 1])) self.assertEqual(value, target) def test_from_int(self): """Test from_int method""" with self.subTest(msg="from_int(0, 4)"): target = DensityMatrix([1, 0, 0, 0]) value = DensityMatrix.from_int(0, 4) self.assertEqual(target, value) with self.subTest(msg="from_int(3, 4)"): target = DensityMatrix([0, 0, 0, 1]) value = DensityMatrix.from_int(3, 4) self.assertEqual(target, value) with self.subTest(msg="from_int(8, (3, 3))"): target = DensityMatrix([0, 0, 0, 0, 0, 0, 0, 0, 1], dims=(3, 3)) value = DensityMatrix.from_int(8, (3, 3)) self.assertEqual(target, value) def test_expval(self): """Test expectation_value method""" psi = Statevector([1, 0, 0, 1]) / np.sqrt(2) rho = DensityMatrix(psi) for label, target in [ ("II", 1), ("XX", 1), ("YY", -1), ("ZZ", 1), ("IX", 0), ("YZ", 0), ("ZX", 0), ("YI", 0), ]: with self.subTest(msg=f"<{label}>"): op = Pauli(label) expval = rho.expectation_value(op) self.assertAlmostEqual(expval, target) psi = Statevector([np.sqrt(2), 0, 0, 0, 0, 0, 0, 1 + 1j]) / 2 rho = DensityMatrix(psi) for label, target in [ ("XXX", np.sqrt(2) / 2), ("YYY", -np.sqrt(2) / 2), ("ZZZ", 0), ("XYZ", 0), ("YIY", 0), ]: with self.subTest(msg=f"<{label}>"): op = Pauli(label) expval = rho.expectation_value(op) self.assertAlmostEqual(expval, target) labels = ["XXX", "IXI", "YYY", "III"] coeffs = [3.0, 5.5, -1j, 23] spp_op = SparsePauliOp.from_list(list(zip(labels, coeffs))) expval = rho.expectation_value(spp_op) target = 25.121320343559642 + 0.7071067811865476j self.assertAlmostEqual(expval, target) @data( "II", "IX", "IY", "IZ", "XI", "XX", "XY", "XZ", "YI", "YX", "YY", "YZ", "ZI", "ZX", "ZY", "ZZ", "-II", "-IX", "-IY", "-IZ", "-XI", "-XX", "-XY", "-XZ", "-YI", "-YX", "-YY", "-YZ", "-ZI", "-ZX", "-ZY", "-ZZ", "iII", "iIX", "iIY", "iIZ", "iXI", "iXX", "iXY", "iXZ", "iYI", "iYX", "iYY", "iYZ", "iZI", "iZX", "iZY", "iZZ", "-iII", "-iIX", "-iIY", "-iIZ", "-iXI", "-iXX", "-iXY", "-iXZ", "-iYI", "-iYX", "-iYY", "-iYZ", "-iZI", "-iZX", "-iZY", "-iZZ", ) def test_expval_pauli_f_contiguous(self, pauli): """Test expectation_value method for Pauli op""" seed = 1020 op = Pauli(pauli) rho = random_density_matrix(2**op.num_qubits, seed=seed) rho._data = np.reshape(rho.data.flatten(order="F"), rho.data.shape, order="F") target = rho.expectation_value(op.to_matrix()) expval = rho.expectation_value(op) self.assertAlmostEqual(expval, target) @data( "II", "IX", "IY", "IZ", "XI", "XX", "XY", "XZ", "YI", "YX", "YY", "YZ", "ZI", "ZX", "ZY", "ZZ", "-II", "-IX", "-IY", "-IZ", "-XI", "-XX", "-XY", "-XZ", "-YI", "-YX", "-YY", "-YZ", "-ZI", "-ZX", "-ZY", "-ZZ", "iII", "iIX", "iIY", "iIZ", "iXI", "iXX", "iXY", "iXZ", "iYI", "iYX", "iYY", "iYZ", "iZI", "iZX", "iZY", "iZZ", "-iII", "-iIX", "-iIY", "-iIZ", "-iXI", "-iXX", "-iXY", "-iXZ", "-iYI", "-iYX", "-iYY", "-iYZ", "-iZI", "-iZX", "-iZY", "-iZZ", ) def test_expval_pauli_c_contiguous(self, pauli): """Test expectation_value method for Pauli op""" seed = 1020 op = Pauli(pauli) rho = random_density_matrix(2**op.num_qubits, seed=seed) rho._data = np.reshape(rho.data.flatten(order="C"), rho.data.shape, order="C") target = rho.expectation_value(op.to_matrix()) expval = rho.expectation_value(op) self.assertAlmostEqual(expval, target) @data([0, 1], [0, 2], [1, 0], [1, 2], [2, 0], [2, 1]) def test_expval_pauli_qargs(self, qubits): """Test expectation_value method for Pauli op""" seed = 1020 op = random_pauli(2, seed=seed) state = random_density_matrix(2**3, seed=seed) target = state.expectation_value(op.to_matrix(), qubits) expval = state.expectation_value(op, qubits) self.assertAlmostEqual(expval, target) def test_reverse_qargs(self): """Test reverse_qargs method""" circ1 = QFT(5) circ2 = circ1.reverse_bits() state1 = DensityMatrix.from_instruction(circ1) state2 = DensityMatrix.from_instruction(circ2) self.assertEqual(state1.reverse_qargs(), state2) @unittest.skipUnless(optionals.HAS_MATPLOTLIB, "requires matplotlib") @unittest.skipUnless(optionals.HAS_PYLATEX, "requires pylatexenc") def test_drawings(self): """Test draw method""" qc1 = QFT(5) dm = DensityMatrix.from_instruction(qc1) with self.subTest(msg="str(density_matrix)"): str(dm) for drawtype in ["repr", "text", "latex", "latex_source", "qsphere", "hinton", "bloch"]: with self.subTest(msg=f"draw('{drawtype}')"): dm.draw(drawtype) def test_density_matrix_partial_transpose(self): """Test partial_transpose function on density matrices""" with self.subTest(msg="separable"): rho = DensityMatrix.from_label("10+") rho1 = np.zeros((8, 8), complex) rho1[4, 4] = 0.5 rho1[4, 5] = 0.5 rho1[5, 4] = 0.5 rho1[5, 5] = 0.5 self.assertEqual(rho.partial_transpose([0, 1]), DensityMatrix(rho1)) self.assertEqual(rho.partial_transpose([0, 2]), DensityMatrix(rho1)) with self.subTest(msg="entangled"): rho = DensityMatrix([[0, 0, 0, 0], [0, 0.5, -0.5, 0], [0, -0.5, 0.5, 0], [0, 0, 0, 0]]) rho1 = DensityMatrix([[0, 0, 0, -0.5], [0, 0.5, 0, 0], [0, 0, 0.5, 0], [-0.5, 0, 0, 0]]) self.assertEqual(rho.partial_transpose([0]), DensityMatrix(rho1)) self.assertEqual(rho.partial_transpose([1]), DensityMatrix(rho1)) with self.subTest(msg="dims(3,3)"): mat = np.zeros((9, 9)) mat1 = np.zeros((9, 9)) mat[8, 0] = 1 mat1[0, 8] = 1 rho = DensityMatrix(mat, dims=(3, 3)) rho1 = DensityMatrix(mat1, dims=(3, 3)) self.assertEqual(rho.partial_transpose([0, 1]), rho1) def test_clip_probabilities(self): """Test probabilities are clipped to [0, 1].""" dm = DensityMatrix([[1.1, 0], [0, 0]]) self.assertEqual(list(dm.probabilities()), [1.0, 0.0]) # The "1" key should be exactly zero and therefore omitted. self.assertEqual(dm.probabilities_dict(), {"0": 1.0}) def test_round_probabilities(self): """Test probabilities are correctly rounded. This is good to test to ensure clipping, renormalizing and rounding work together. """ p = np.sqrt(1 / 3) amplitudes = [p, p, p, 0] dm = DensityMatrix(np.outer(amplitudes, amplitudes)) expected = [0.33, 0.33, 0.33, 0] # Exact floating-point check because fixing the rounding should ensure this is exact. self.assertEqual(list(dm.probabilities(decimals=2)), expected) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit ghz = QuantumCircuit(5) ghz.h(0) ghz.cx(0,range(1,5)) ghz.draw(output='mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
https://github.com/urwin419/QiskitChecker
urwin419
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) ### added x gate ### qc.x(qubit) return qc def decode_message(qc): qc.cx(1, 0) ### added z gate ### qc.z(1) qc.h(1) return qc
https://github.com/papaaannn/Circuit
papaaannn
import numpy as np from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import circuit_drawer from qiskit.tools.visualization import plot_histogram # Total number of inputs n = 8 # Random n numbers a = np.random.randint(0, 2**n, size=n) # Check if n is a power of 2 if not (n and (not (n & (n - 1)))) or len(a) != n: raise ValueError("n must be a power of 2 and len(a) must be n") # Initialize the circuit and the registers circuit = QuantumCircuit(2*n, name="bitonic_sort") a_reg = [i for i in range(n)] c_reg = [i + n for i in range(n)] # Apply Hadamard gates to all input qubits circuit.h(a_reg) # Apply the bitonic sort operations recursively for k in range(1, n): for j in range(k, 0, -1): circuit.cswap(j + k - 1, j - 1, c_reg[k]) for i in range(j - 1): circuit.cswap(j + k - 1, i, c_reg[k]) # Measure the qubits and run the circuit circuit.measure_all() circuit_drawer(circuit, output='mpl') backend = Aer.get_backend('qasm_simulator') shots = 1024 job = execute(circuit, backend=backend, shots=shots) result = job.result() counts = result.get_counts() plot_histogram(counts, figsize=(100,30)) # Extract the sorted output from the measurement results output = [int(key[::-1], 2) for key in sorted(counts.keys())] print(f"Input array: {a}") print(f"Sorted array: {output}")
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() # our backend is the Pulse Simulator from resources import helper from qiskit.providers.aer import PulseSimulator backend_sim = PulseSimulator() # sample duration for pulse instructions dt = 1e-9 # create the model duffing_model = helper.get_transmon(dt) # get qubit frequency from Duffing model qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift() import numpy as np # visualization tools import matplotlib.pyplot as plt plt.style.use('dark_background') # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz kHz = 1.0e3 # kilohertz us = 1.0e-6 # microseconds ns = 1.0e-9 # nanoseconds from qiskit import pulse from qiskit.pulse import Play, Acquire from qiskit.pulse.pulse_lib import GaussianSquare # qubit to be used throughout the notebook qubit = 0 ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) # Construct a measurement schedule and add it to an InstructionScheduleMap meas_samples = 1200 meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150) measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit)) inst_map = pulse.InstructionScheduleMap() inst_map.add('measure', [qubit], measure_sched) # save the measurement/acquire pulse for later measure = inst_map.get('measure', qubits=[qubit]) from qiskit.pulse import pulse_lib # the same spect pulse used in every schedule drive_amp = 0.9 drive_sigma = 16 drive_duration = 128 spec_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp, sigma=drive_sigma, name=f"Spec drive amplitude = {drive_amp}") # Construct an np array of the frequencies for our experiment spec_freqs_GHz = np.arange(5.0, 5.2, 0.005) # Create the base schedule # Start with drive pulse acting on the drive channel spec_schedules = [] for freq in spec_freqs_GHz: sb_spec_pulse = helper.apply_sideband(spec_pulse, qubit_lo_freq[0]-freq*GHz, dt) spec_schedule = pulse.Schedule(name='SB Frequency = {}'.format(freq)) spec_schedule += Play(sb_spec_pulse, drive_chan) # The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration spec_schedule += measure << spec_schedule.duration spec_schedules.append(spec_schedule) spec_schedules[0].draw() from qiskit import assemble # assemble the schedules into a Qobj spec01_qobj = assemble(**helper.get_params('spec01', globals())) # run the simulation spec01_result = backend_sim.run(spec01_qobj, duffing_model).result() # retrieve the data from the experiment spec01_values = helper.get_values_from_result(spec01_result, qubit) fit_params, y_fit = helper.fit_lorentzian(spec_freqs_GHz, spec01_values, [5, 5, 1, 0]) f01 = fit_params[1] plt.scatter(spec_freqs_GHz, np.real(spec01_values), color='white') # plot real part of sweep values plt.plot(spec_freqs_GHz, y_fit, color='red') plt.xlim([min(spec_freqs_GHz), max(spec_freqs_GHz)]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured Signal [a.u.]") plt.show() print("01 Spectroscopy yields %f GHz"%f01) x180_amp = 0.629070 #from lab 6 Rabi experiment x_pulse = pulse_lib.gaussian(duration=drive_duration, amp=x180_amp, sigma=drive_sigma, name='x_pulse') anharmonicity_guess_GHz = -0.3 def build_spec12_pulse_schedule(freq): sb12_spec_pulse = helper.apply_sideband(spec_pulse, (freq + anharmonicity_guess_GHz)*GHz, dt) ### create a 12 spectroscopy pulse schedule spec12_schedule (already done) ### play an x pulse on the drive channel ### play sidebanded spec pulse on the drive channel ### add measurement pulse to schedule spec12_schedule = pulse.Schedule() ### WRITE YOUR CODE BETWEEN THESE LINES - START spec12_schedule += Play(x_pulse, drive_chan) spec12_schedule += Play(sb12_spec_pulse, drive_chan) spec12_schedule += measure << spec12_schedule.duration ### WRITE YOUR CODE BETWEEN THESE LINES - STOP return spec12_schedule sb_freqs_GHz = np.arange(-.1, .1, 0.005) # sweep +/- 100 MHz around guess # now vary the sideband frequency for each spec pulse spec_schedules = [] for freq in sb_freqs_GHz: spec_schedules.append(build_spec12_pulse_schedule(freq)) spec_schedules[0].draw() # assemble the schedules into a Qobj spec12_qobj = assemble(**helper.get_params('spec12', globals())) answer1 = spec12_qobj # run the simulation spec12_result = backend_sim.run(spec12_qobj, duffing_model).result() # retrieve the data from the experiment spec12_values = helper.get_values_from_result(spec12_result, qubit) anharm_offset = qubit_lo_freq[0]/GHz + anharmonicity_guess_GHz fit_params, y_fit = helper.fit_lorentzian(anharm_offset + sb_freqs_GHz, spec12_values, [5, 4.5, .1, 3]) f12 = fit_params[1] plt.scatter(anharm_offset + sb_freqs_GHz, np.real(spec12_values), color='white') # plot real part of sweep values plt.plot(anharm_offset + sb_freqs_GHz, y_fit, color='red') plt.xlim([anharm_offset + min(sb_freqs_GHz), anharm_offset + max(sb_freqs_GHz)]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured Signal [a.u.]") plt.show() print("12 Spectroscopy yields %f GHz"%f12) print("Measured transmon anharmonicity is %f MHz"%((f12-f01)*GHz/MHz)) from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();')); from grading_tools import send_code;send_code('ex1.ipynb')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit # Create a circuit with a register of three qubits circ = QuantumCircuit(3) # H gate on qubit 0, putting this qubit in a superposition of |0> + |1>. circ.h(0) # A CX (CNOT) gate on control qubit 0 and target qubit 1 generating a Bell state. circ.cx(0, 1) # CX (CNOT) gate on control qubit 0 and target qubit 2 resulting in a GHZ state. circ.cx(0, 2) # Draw the circuit circ.draw('mpl')
https://github.com/LeanderThiessen/antisymmetrization-circuit
LeanderThiessen
#General Imports import numpy as np import matplotlib.pyplot as plt import time from itertools import product,permutations from string import ascii_lowercase as asc import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) #Qiskit Imports from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile from qiskit.circuit.library.standard_gates import MCXGate, CXGate, XGate, CSwapGate from qiskit.circuit.library import Diagonal from qiskit.quantum_info import partial_trace,purity #############FUNCTIONS########################################################################################################### #wrapper for measuring time taken by function 'func' def timeis(func): def wrap(*args,**kwargs): start = time.time() result = func(*args,**kwargs) end = time.time() if measure_time: print("{} took {:.2f}s".format(func.__name__,end-start)) return result return wrap #check if inputs are valid def check_inputs(n,m): if n == 1: print("Case n=1 currently not supported") correct = 1 if m>2**n: correct == 0 if correct == 1: print("Inputs valid") return 0 #initialize quantum circuit with electron register, swap_ancillas, record_ancillas, collision_ancillas def initialize_circuit(n,m,L): circuit = QuantumCircuit() #add main electron register (seed/target) for e in range(m): r_q = QuantumRegister(n,'{}'.format(asc[e]))#asc[i]=ith letter of the alphabe c = QuantumCircuit(r_q) circuit = circuit.combine(c) #add ancillas for comparator_swaps for k in range(int(np.ceil(m/2))): anc_q = QuantumRegister(n-1,'anc_{}'.format(k)) c = QuantumCircuit(anc_q) circuit = circuit.combine(c) #add 'record' register for storing outcomes of comparators for l in range(L): anc_q = QuantumRegister(1,'record_{}'.format(l)) c = QuantumCircuit(anc_q) circuit = circuit.combine(c) #add ancillas to store the occurence of collisions between pairs of electrons for c in range(m-1): anc_q = QuantumRegister(1,'coll_record_{}'.format(c)) c = QuantumCircuit(anc_q) circuit = circuit.combine(c) #add one ancilla to store if all other collision ancillas are '1' anc_q = QuantumRegister(1,'collision_test') c = QuantumCircuit(anc_q) circuit = circuit.combine(c) return circuit #returns x in binary format as string of length n, incl leading zeros def binary_n(x,n): return bin(x)[2:].zfill(n) #initializes j-th electron register with number x def binary_init(circuit,n,m,input): for k,e in enumerate(input): e_bin = binary_n(e,n) for i in range(n): if e_bin[i]=='1': circuit.append(XGate(),[i+k*n]) return circuit #Apply a Hadamard gate to each qubit in the electron register def Hadamard(circuit,n,m): for q in range(n*m): circuit.h(q) return circuit #Compare bits at positions x and y, only output=(x<y) to position anc def bit_compare(circuit,cbits,control,debug=True): x = cbits[0] y = cbits[1] anc = cbits[2] if debug: circuit.barrier() #control='01' for initial sorting and '10' for collision detection circuit.append(MCXGate(2,ctrl_state=control),[x,y,anc]) if debug: circuit.barrier() return circuit #split the array 'index' into array of pairs of adjacent indices; first entry is (e.g.) [0] if number of entries of index is odd def get_subsets(index): #index = [0,1,2,3] -> result = [[0,1],[2,3]] #index = [0,1,2,3,4] -> result = [[0],[1,2],[3,4]] M = len(index) result = [] if M % 2 != 0: result.append(np.array([0])) n_split = int((M-1)/2) for s in np.split(index[1:M],n_split): result.append(s) else: result = np.split(index,M/2) return result #get position of first qubit in swap_control ancilla register def get_first_swap_ctrl(n,m): #n_comp_parallel is the number of comparators that are applied in each layer #n*m = main register for storing electron registers; #(n_comp_parallel)*(n-1) = fixed ancilla register needed for compare_n n_comp_parallel = int(np.ceil(m/2)) ctrl_0 = n*m + (n-1)*n_comp_parallel return ctrl_0 #get position of first qubit in collision_control ancilla register def get_first_coll_ctrl(n,m,L): coll_0 = get_first_swap_ctrl(n,m) + L return coll_0 #return pairs of electron indices that need to be compared in collision-detection step def get_coll_sets(m): ind = np.arange(m) if m == 2: sets_a = [np.array([0,1])] sets_b = [] return sets_a,sets_b if m % 2 == 0: sets_a = np.split(ind,m/2) sets_b = np.split(ind[1:-1],(m-2)/2) else: sets_a = np.split(ind[:-1],(m-1)/2) sets_b = np.split(ind[1:],(m-1)/2) #all gates in sets_a can be applied in parallel #all gates in sets_b can be applied in parallel return sets_a,sets_b #returns the first qubit position of the ancilla register used for swap of i and j (only really tested for m<6) def get_anc(n,m,i,j): if abs(j-i) == 1: anc_reg = int( np.min([i,j])/2 ) elif abs(j-i) == 2: anc_reg = int( np.ceil( np.min([i,j])/2 )) else: anc_reg = int( np.min([i,j]) ) anc = n*m + anc_reg*(n-1) return anc #Implement 'Compare2' function (Fig 3); input: two 2bit numbers, output: two 1bit numbers with same ordering def compare_2(circuit,x_0,x_1,y_0,y_1,anc): #Notation: x = 2^1*x_0 + x_1 (reverse from paper!!) #compares numbers x,y and outputs two bits x',y' (at positions x_1 and y_1) with the same ordering circuit.append(XGate(),[anc]) circuit.append(CXGate(),[y_0,x_0]) circuit.append(CXGate(),[y_1,x_1]) circuit.append(CSwapGate(),[x_0,x_1,anc]) circuit.append(CSwapGate(),[x_0,y_0,y_1]) circuit.append(CXGate(),[y_1,x_1]) return circuit #Generalisation of 'compare2' two nbit numbers, output: two 1bit numbers with same ordering at positions x1,y1 def compare_n(circuit,n,m,i,j,l,L,debug): index = np.arange(n) subsets = get_subsets(index) M = len(subsets) anc = get_anc(n,m,i,j) for s in subsets: if len(s)==2: if debug: circuit.barrier() x_0 = s[0] + i*n x_1 = s[1] + i*n y_0 = s[0] + j*n y_1 = s[1] + j*n circuit = compare_2(circuit,x_0,x_1,y_0,y_1,anc) anc += 1 while (len(subsets)>1): index = np.array([subsets[k][-1] for k in range(M)]) subsets = get_subsets(index) M = len(subsets) for s in subsets: if len(s)==2: if debug: circuit.barrier() x_0 = s[0] + i*n x_1 = s[1] + i*n y_0 = s[0] + j*n y_1 = s[1] + j*n circuit = compare_2(circuit,x_0,x_1,y_0,y_1,anc) anc += 1 ######################################################################################################################################## #at this point the bits x_1 and y_1 have the same ordering as numbers stored in registers i and j #e(i)<e(j) -> x_1=0 and y_1=1 #e(i)>e(j) -> x_1=1 and y_1=0 #e(i)=e(j) -> x_1=0 y_1=0 if e(i) even or x_1=1 y_1=1 if e(i) odd #prepare output for bit_compare function; anc iterates through the second ancilla register (+1 for each comparator) #l = current swap; each new swap gets a new ancilla for storing the outcome anc = get_first_swap_ctrl(n,m) + l cbits = x_1,y_1,anc return circuit,cbits #apply diagonal phase shift to qubit i, conditioned on qubit 'ctrl' def cphase_shift(circuit,ctrl,i): target = i*n CDiag = Diagonal([-1,-1]).control(1) CDiag = CDiag.to_gate() CDiag.label = "D" #doesn't work currently circuit.append(CDiag,[ctrl,target]) return circuit #performs swap of registers i and j conditioned on ancilla qubit 'ctrl' def swap_registers(circuit,n,i,j,ctrl,debug): for g in range(n): circuit.append(CSwapGate(),[ctrl,i*n+g,j*n+g]) if debug: circuit.barrier() return circuit #compare electron registers i and j; swap registers iff e(i)<(j); l=current swap (0 to L) def comparator_swap(n,m,i,j,l,L,phase,debug): #Perform comparison to generate output qubits "cbits" circuit_compute = initialize_circuit(n,m,L) circuit_compute,cbits = compare_n(circuit_compute,n,m,i,j,l,L,debug) #Add bit_compare between the two output qubits and store in ancilla circuit_bit_compare = initialize_circuit(n,m,L) circuit_bit_compare = bit_compare(circuit_bit_compare,cbits,'10',debug) #add uncomputing step only of the comparison circuit circuit_uncompute = circuit_compute.inverse() #Swap registers based on control ancilla circuit_swap = initialize_circuit(n,m,L) #apply a conditioned phase shift to the first qubit of the register pair; is only called when sn is applied backwards, that's why it's (phase,swap) and not (swap,phase) if phase: circuit_swap = cphase_shift(circuit_swap,cbits[2],i) circuit_swap = swap_registers(circuit_swap,n,i,j,cbits[2],debug) #Combine circuits circuit_comparator = circuit_compute + circuit_bit_compare + circuit_uncompute + circuit_swap return circuit_comparator #Apply the sorting network sn, where each comparator stores the outcome in ctrl_register def apply_sorting_network(circuit,n,m,sn,L,phase,debug): for l,swap in enumerate(sn): #swap = [i, j, direction]; dir = 0 : descending (from the top); dir = 1 : ascending (from the top) if swap[2]==0: i = swap[0] j = swap[1] if swap[2]==1: i = swap[1] j = swap[0] circuit_comparator = comparator_swap(n,m,i,j,l,L,phase,debug) circuit = circuit + circuit_comparator return circuit #Apply the reverse of the sorting networkl sn for antisymmetrizing the input state def apply_reverse_sorting_network(circuit,n,m,sn,L,phase,debug): circuit_sn = initialize_circuit(n,m,L) circuit_sn = apply_sorting_network(circuit_sn,n,m,sn,L,phase,debug) #reverse all gates in the circuit circuit_reverse_sn = circuit_sn.inverse() circuit = circuit + circuit_reverse_sn return circuit #reset first register to [|0>,|0>,|0>,...] (all zeros) def reset_electrons(circuit,n,m): circuit.barrier() for g in range(m): g_indices = np.arange(g*n,(g+1)*n) #classical register positions for electron g for g_i in g_indices: circuit.reset(g_i) return circuit #reset all registers except for the main electron register def reset_ancillas(circuit,n,m,L): circuit.barrier() start = n*m end = get_first_coll_ctrl(n,m,L) + m for q in range(start,end): circuit.reset(q) return circuit #Perform comparisons between all adjacent electron registers, with ctrl ancilla in the coll_register def collision_compare(circuit,n,m,L,debug): #all sets in sets_a can be applied simultaneously (same for sets_b); both for loops are otherwise identical and could be combined sets_a,sets_b = get_coll_sets(m) c = 0 for s in sets_a: circuit_coll_test = initialize_circuit(n,m,L) i = s[0] j = s[1] circuit_coll_test,cbits = compare_n(circuit_coll_test,n,m,i,j,0,L,debug) x_1 = cbits[0] y_1 = cbits[1] coll_anc = get_first_coll_ctrl(n,m,L) + c cbits = [x_1,y_1,coll_anc] circuit_coll_test_reverse = circuit_coll_test.inverse() circuit = circuit + circuit_coll_test circuit = bit_compare(circuit,cbits,'01',debug) circuit = circuit + circuit_coll_test_reverse c+=1 for s in sets_b: circuit_coll_test = initialize_circuit(n,m,L) i = s[0] j = s[1] circuit_coll_test,cbits = compare_n(circuit_coll_test,n,m,i,j,0,L,debug) x_1 = cbits[0] y_1 = cbits[1] coll_anc = get_first_coll_ctrl(n,m,L) + c cbits = [x_1,y_1,coll_anc] circuit_coll_test_reverse = circuit_coll_test.inverse() circuit = circuit + circuit_coll_test circuit = bit_compare(circuit,cbits,'01',debug) circuit = circuit + circuit_coll_test_reverse c+=1 return circuit #apply X gate on last qubit, conditioned on all other coll_ancillas being 1 (which means that all elctron registers are different) def collision_test(circuit,n,m,L,debug): coll_ctrl_0 = get_first_coll_ctrl(n,m,L) control = '' qubits = [] for i in range(m-1): control = control + '1' qubits.append(coll_ctrl_0+i) qubits.append(coll_ctrl_0+m-1) circuit.append(MCXGate(m-1,ctrl_state=control),qubits) return circuit #not necessary #returns True if output contains only unique elements; returns False otherwise (if two or more elements are the same) def collision_check_old(output): if len(output) == len(set(output)): return True else: return False #Perform measurement on last qubit in coll_register def measure_collisions(circuit,n,m,L): #add classical register to store measurement result c_q = QuantumRegister(0) c_reg = ClassicalRegister(1,'collision_check') c = QuantumCircuit(c_q,c_reg) circuit = circuit.combine(c) #perform measurements on each electron register and store in separate memorey circuit.measure(get_first_coll_ctrl(n,m,L) + m - 1, 0) return circuit #Add classical registers and apply measurements on the main electron register def measure_electrons(circuit,n,m): circuit.barrier() for g in range(m): #Add classicla register to store measurement outcomes c_q = QuantumRegister(0) c_reg = ClassicalRegister(n,'mem_{}'.format(asc[g])) c = QuantumCircuit(c_q,c_reg) circuit = circuit.combine(c) #perform measurements on each electron register and store in separate memorey circuit.measure(np.arange(g*n,(g+1)*n),np.arange(g*n + 1,(g+1)*n + 1)) return circuit #Build the circuit with all gates and measurements @timeis def build_circuit(n,m,input,sn,L,debug=True): #Initialize the circuit with the right number of qubits and ancillas circuit = initialize_circuit(n,m,L) #Apply Hadamard gates to each qubit in the first register circuit = Hadamard(circuit,n,m) #Apply the sorting network sn phase = False circuit = apply_sorting_network(circuit,n,m,sn,L,phase,debug) #apply comparisons between all adjacent electron registers and store outcome in coll_register circuit = collision_compare(circuit,n,m,L,debug) #check if outcome of all comparisons is "not_equal"; flip last qubit in coll_register if this is the case circuit = collision_test(circuit,n,m,L,debug) #measure last qubit in coll_register, which stores (no collisions = 1) or (collisions = 0); result is kept until the end of the simulation and result accepted if (no collisions == True) circuit = measure_collisions(circuit,n,m,L) #Measurements: classical register 0 stores the random sorted array that can still include collisions #circuit = measure_electrons(circuit,n,m) #Reset main electron register circuit = reset_electrons(circuit,n,m) #Initialize main electron register in given input product state circuit = binary_init(circuit,n,m,input) #Apply the reverse of 'apply_sorting_network' and add a conditioned phase shift after each swap (this antisymmetrizes the input state) phase = True circuit = apply_reverse_sorting_network(circuit,n,m,sn,L,phase,debug) #Reset all ancilla qubits and only keep the main electron register (disable for testing final state for antisymmetry) #circuit = reset_ancillas(circuit,n,m,L) #Measure electron register (for testing) #circuit = measure_electrons(circuit,n,m) return circuit #Simulate circuit using specified backend and return simulation result @timeis def simulate(circuit,backend,shots): simulator = Aer.get_backend(backend) #transpile the circuit into the supported set of gates circuit = transpile(circuit,backend=simulator) result = simulator.run(circuit,shots=shots).result() return result #turns simulation result 'counts' into list of decimal numbers corresponding to the electron registers; only use if shots=1 or all outcomes are the same def convert_output_to_decimal(counts,n,m): output_list = list(counts.keys())[0][::-1] coll_test = output_list[0] output_list = output_list[2:] output = [] offset = 0 for g in range(m): start = g*n + offset end = (g+1)*n + offset g_out = int(output_list[start:end],2) output.append(g_out) offset += 1 output_0 = output[0:m] return coll_test,output_0 #draw the circuit using size,name as input if plot==True @timeis def draw_circuit(circuit,plot_scale,fname): circuit.draw(output='mpl',fold=-1,scale=plot_scale,plot_barriers=True) plt.savefig(fname,dpi=700) return 0 def plot_circuit(circuit,plot_scale,fname,plot=True): if plot: draw_circuit(circuit,plot_scale,fname) plt.show() return 0 print("Plot disabled") return 0 #plot sorting network by itself, using cnot as directed comparator (only for visualizationo) def plot_sorting_network(sn,m): circuit_sn = QuantumCircuit(m) for s in sn: if s[2] == 0: i,j = s[0],s[1] else: i,j = s[1],s[0] circuit_sn.cz(i,j) circuit_sn.draw(output='mpl') plt.show() return 0 #Generate a bitonic sorting network for m electrons; dir=0 (descending), dir=1 (ascending) def sorting_network_bitonic(m,dir): sn = [] def compAndSwap(i,j,dir): sn.append([i,j,dir]) def bitonic_sort(low, cnt, dir): if cnt>1: k = cnt//2 dir_n = (dir + 1) % 2 bitonic_sort(low, k, dir_n)#n_dir bitonic_sort(low + k, cnt-k, dir)#dir bitonic_merge(low, cnt, dir) def bitonic_merge(low, cnt, dir): if cnt>1: k = greatestPowerOfTwoLessThan(cnt) i = low while i < low+cnt-k: compAndSwap(i, i+k, dir) i+=1 bitonic_merge(low,k,dir) bitonic_merge(low+k,cnt-k,dir) def greatestPowerOfTwoLessThan(cnt): i=1 while (2**i)<cnt: i+=1 return 2**(i-1) bitonic_sort(0,m,dir) L = len(sn) return sn,L #Test if sorting network correctly sorts all possible inputs def test_sn(sn,n,m): all_inputs = list(product(range(2**n),repeat=m)) fail = 0 count = 0 for input in all_inputs: input = np.array(input) temp = np.copy(input) for s in sn: if s[2]==0: i = s[0] j = s[1] if s[2]==1: i = s[1] j = s[0] if input[i]<input[j]: input[i],input[j] = input[j],input[i] should_be = np.sort(temp)[::-1] if (input == should_be).all(): fail += 0 else: fail += 1 print(f"Testing sorting network {count}/{len(all_inputs)}",end="\r") count+=1 print(" ", end = "\r") if fail == 0: print("Sorting network correct\n") return 1 else: print("Error in sorting network\n") return 0 #Returns all steps of sorting network with corresponding ancilla registers (for testing) def test_sn_anc(sn,n,m): for s in sn: i = s[0] j = s[1] anc = get_anc(n,m,i,j) anc_reg = int((anc-n*m)/(n-1)) print(f"[{i},{j}] anc_reg={anc_reg}") return 0 #Output density matrix of electron register (target) and compute purity, doesnt actually test antisymmetry yet! def test_antisymmetry(result,n,m,L): sv = result.get_statevector() trace_out = list(np.arange(n*m,get_first_coll_ctrl(n,m,L)+m)) #print(f"Tracing out qubits: {trace_out}") rho_e = partial_trace(sv,trace_out) if rho_e.is_valid(): print("Target state is valid density matrix\n") else: print("Target state is not valid density matrix") #print(rho_e) p = purity(rho_e) print(f"Purity of target state = {p}\n") return p ###################MAINPART############################################################################################################ #Parameters #n: number of qubits per electron; N = 2^n orbitals n=3 #m: number of electrons m=4 #input: list of orbitals the electrons are initialized in; needs to be in descending order, without repetitions input = [5,4,3,2] #dir: ordering descending (dir=0) or ascending (dir=1) dir = 0 #plot and save the circuit plot = True #include barriers between comparators in the circuit for visualization debug = False #measure time of functions: {build_circuit, simulate, draw_circuit} measure_time = True #size of the plot plot_scale = 0.2 #simulation method backend = 'statevector_simulator'#'aer_simulator' #number of circuit repetitions in 'simulate' shots = 1 #check valid inputs check_inputs(n,m) #Generate sorting network sn,L = sorting_network_bitonic(m,dir) #Test sorting network test_sn(sn,n,m) #Plot sorting network plot_sorting_network(sn,m) #Build circuit circuit = build_circuit(n,m,input,sn,L,debug) #Simulate result = simulate(circuit,backend,shots) counts = result.get_counts(circuit) print(f"Counts: {counts}\n") #Test if final state is antisymmetric test_antisymmetry(result,n,m,L) output_list = list(counts.keys())[0][::-1] coll_test = output_list[0] if coll_test == '1': print("No collisions detected - continue\n") else: print("Collisions detected - repeat\n") #plot circuit plot_circuit(circuit,plot_scale,f"Plots/Circuit_m{m}_n{n}_debug{debug}",plot)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, QuantumRegister from qiskit.circuit.library.standard_gates import HGate qr = QuantumRegister(3) qc = QuantumCircuit(qr) c3h_gate = HGate().control(2) qc.append(c3h_gate, qr) qc.draw('mpl')
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for qiskit/tools/parallel""" import os import time from unittest.mock import patch from qiskit.tools.parallel import get_platform_parallel_default, parallel_map from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.pulse import Schedule from qiskit.test import QiskitTestCase def _parfunc(x): """Function for testing parallel_map""" time.sleep(1) return x def _build_simple_circuit(_): qreg = QuantumRegister(2) creg = ClassicalRegister(2) qc = QuantumCircuit(qreg, creg) return qc def _build_simple_schedule(_): return Schedule() class TestGetPlatformParallelDefault(QiskitTestCase): """Tests get_parallel_default_for_platform.""" def test_windows_parallel_default(self): """Verifies the parallel default for Windows.""" with patch("sys.platform", "win32"): parallel_default = get_platform_parallel_default() self.assertEqual(parallel_default, False) def test_mac_os_unsupported_version_parallel_default(self): """Verifies the parallel default for macOS.""" with patch("sys.platform", "darwin"): with patch("sys.version_info", (3, 8, 0, "final", 0)): parallel_default = get_platform_parallel_default() self.assertEqual(parallel_default, False) def test_other_os_parallel_default(self): """Verifies the parallel default for Linux and other OSes.""" with patch("sys.platform", "linux"): parallel_default = get_platform_parallel_default() self.assertEqual(parallel_default, True) class TestParallel(QiskitTestCase): """A class for testing parallel_map functionality.""" def test_parallel_env_flag(self): """Verify parallel env flag is set""" self.assertEqual(os.getenv("QISKIT_IN_PARALLEL", None), "FALSE") def test_parallel(self): """Test parallel_map""" ans = parallel_map(_parfunc, list(range(10))) self.assertEqual(ans, list(range(10))) def test_parallel_circuit_names(self): """Verify unique circuit names in parallel""" out_circs = parallel_map(_build_simple_circuit, list(range(10))) names = [circ.name for circ in out_circs] self.assertEqual(len(names), len(set(names))) def test_parallel_schedule_names(self): """Verify unique schedule names in parallel""" out_schedules = parallel_map(_build_simple_schedule, list(range(10))) names = [schedule.name for schedule in out_schedules] self.assertEqual(len(names), len(set(names)))
https://github.com/YPadawan/qiskit-hackathon
YPadawan
import numpy as np import matplotlib.pyplot as plt import torch from torchvision import datasets, transforms n_samples = 100 #transforms.compose receive all the types of transformation that can be done on an image #in our case the only transformation that we do is to transform the image into a tensor, it is #why between hook [] we just have transforms.ToTensor() X_train = datasets.MNIST(root='./data' , train=True, download=True, transform=transforms.Compose([transforms.ToTensor()])) # Leaving only 8 and 9 #We select two numbers to make the classification #I try to take characters that are alike to put the model a little in difficulty idx = np.append(np.where(X_train.targets == 8)[0][:n_samples], np.where(X_train.targets == 9)[0][:n_samples]) X_train.data = X_train.data = X_train.data[idx] X_train.targets = X_train.targets[idx] train_loader = torch.utils.data.DataLoader(X_train, batch_size=1, shuffle=True) n_samples_show = 5 data_iter = iter(train_loader) fig, axes = plt.subplots(nrows = 1, ncols=n_samples_show, figsize=(10, 3)) while n_samples_show > 0: images, targets = data_iter.__next__() axes[n_samples_show - 1].imshow(images[0].numpy().squeeze(), cmap='gray') axes[n_samples_show - 1].set_xticks([]) axes[n_samples_show - 1].set_yticks([]) axes[n_samples_show - 1].set_title("Labeled: {}".format(targets.item())) n_samples_show -= 1 #Half of the data is used for validation n_samples = 50 X_test = datasets.MNIST(root='./data', train=False, download=True, transform=transforms.Compose([transforms.ToTensor()])) idx = np.append(np.where(X_test.targets == 5)[0][:n_samples], np.where(X_test.targets == 6)[0][:n_samples]) X_test.data = X_test.data[idx] X_test.targets = X_test.targets[idx] test_loader = torch.utils.data.DataLoader(X_test, batch_size=1, shuffle=True)
https://github.com/bayesian-randomized-benchmarking/qiskit-advocates-bayes-RB
bayesian-randomized-benchmarking
#Import general libraries (needed for functions) import numpy as np import matplotlib.pyplot as plt #from IPython import display #Import Qiskit classes import qiskit from qiskit.tools.monitor import job_monitor from qiskit import Aer from qiskit.providers.aer.noise import NoiseModel from qiskit import QuantumRegister, QuantumCircuit #Import the RB Functions import qiskit.ignis.verification.randomized_benchmarking as rb # import the bayesian packages import pymc3 as pm import arviz as az from scipy.optimize import curve_fit import bayesian_fitter as bf # initialize the Bayesian extension %config InlineBackend.figure_format = 'retina' # Initialize random number generator RANDOM_SEED = 8927 np.random.seed(RANDOM_SEED) az.style.use("arviz-darkgrid") RB_process = "2_Q RB" if RB_process in ["3_Q RB","2-3_Q RB"] : #Number of qubits nQ = 3 #There are 3 qubits: Q0,Q1,Q2. #2Q RB on Q0,Q2 and 1Q RB on Q1 rb_pattern = [[1,2],[3]] # because 3 qubits #Do three times as many 1Q Cliffords length_multiplier = [1,3] #Interleaved Clifford gates (2-qubits and 1-qubit) interleaved_gates = [['cx 0 1'],['x 2']] else: #Number of qubits nQ = 2 #There are 2 qubits: Q0,Q1. #2Q RB Q0,Q1 rb_pattern = [[0,1]] length_multiplier = 1 interleaved_gates = [['cx 0,1']] #Number of Cliffords in the sequence (start, stop, steps) nCliffs = [1, 20, 40, 60, 100, 150, 200, 300, 400, 500] #Number of seeds (random sequences) nseeds=8 scale = (2 ** len(rb_pattern[0]) - 1) / (2 ** len(rb_pattern[0])) qregs_02 = QuantumRegister(2) circ_02 = QuantumCircuit(qregs_02, name='circ_02') #circ_02.h(qregs_02[0]) # booptrap! WIP! circ_02.cx(qregs_02[0], qregs_02[1]) circ_02.draw() qregs_1 = QuantumRegister(1) circ_1 = QuantumCircuit(qregs_1, name='circ_1') circ_1.x(qregs_1[0]) # booptrap! WIP! circ_1.draw() rb_opts = {} rb_opts['rand_seed'] = 61946 rb_opts['length_vector'] = nCliffs rb_opts['nseeds'] = nseeds rb_opts['rb_pattern'] = rb_pattern rb_opts['length_multiplier'] = length_multiplier #rb_opts['align_cliffs'] = True if RB_process in ["3_Q RB","2-3_Q RB"]: rb_opts['interleaved_elem'] = [circ_02, circ_1] if RB_process == "2_Q RB": rb_opts['interleaved_elem'] = [circ_02] rb_original_circs, xdata, rb_interleaved_circs = rb.randomized_benchmarking_seq(**rb_opts) #Original RB circuits print (rb_original_circs[0][0]) #Interleaved RB circuits print (rb_interleaved_circs[0][0]) from qiskit import IBMQ from qiskit import Aer IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') device = provider.get_backend('ibmq_lima') # type here hardware backend properties = device.properties() coupling_map = device.configuration().coupling_map # use a noise model corresponding to the chosen real device backend basis_gates = ['id', 'rz', 'sx', 'x', 'cx', 'reset'] hardware = device.name() backend = Aer.get_backend('qasm_simulator') shots = 2**9 noise_model = NoiseModel.from_backend(properties) retrieve_list = [] original_result_list, original_transpile_list = bf.get_and_run_seeds(rb_circs=rb_original_circs, shots=shots, backend = backend, coupling_map = coupling_map, basis_gates = basis_gates, noise_model = noise_model, retrieve_list=retrieve_list) retrieve_list = [] interleaved_result_list, interleaved_transpile_list = bf.get_and_run_seeds(rb_circs=rb_interleaved_circs, shots=shots, backend = backend, coupling_map = coupling_map, basis_gates = basis_gates, noise_model = noise_model, retrieve_list=retrieve_list) Y1 = bf.get_count_data(original_result_list, nCliffs=nCliffs ) Y2 = bf.get_count_data(interleaved_result_list, nCliffs=nCliffs) # function to optimize def lsf(x, a, alpha, b): return a * alpha ** x + b # curve fit popt_s,pcov_s = curve_fit(lsf, np.array(nseeds*list(nCliffs)), np.ravel(Y1)/shots, bounds = ([.65,.9,0.15],[.85,.999,0.35])) perr_s= np.sqrt(np.diag(pcov_s)) # get EPC and EPC sigma for LSF accelerated alpha_f = popt_s[1] alpha_f_err = perr_s[1] popt_s,perr_s # curve fit popt_i,pcov_i = curve_fit(lsf, np.array(nseeds*list(nCliffs)), np.ravel(Y2)/shots, bounds = ([.65,.9,0.15],[.85,.999,0.35])) perr_i= np.sqrt(np.diag(pcov_i)) # get EPC and EPC sigma for LSF accelerated alphC_f = popt_i[1] alphC_f_err = perr_i[1] popt_i,perr_i epc_est_f = scale*(1 - alphC_f/alpha_f) epc_est_f_err = scale*(alphC_f/alpha_f)*(np.sqrt(alpha_f_err**2 + alphC_f_err**2)) # function to optimize def lsmf(x, a, alpha, p_tilde_m, b): return x[1]*(a * alpha ** x[0] + b) + x[2]*(a * (alpha*p_tilde_m) ** x[0] + b) # obtain the data m_len = len(nCliffs)*nseeds x0_lsmf = np.array(nseeds*2*list(nCliffs)) x1_lsmf = np.hstack((np.ones(m_len),np.zeros(m_len))) x2_lsmf = np.hstack((np.zeros(m_len),np.ones(m_len))) x_lsmf = np.vstack((x0_lsmf,x1_lsmf,x2_lsmf)) y_lsmf=np.hstack((np.ravel(Y1),np.ravel(Y2)))/shots # curve fit popt_m,pcov_m = curve_fit(lsmf, x_lsmf, y_lsmf, bounds = ([.65,.9,.9,0.15], [.85,.999,.999,0.35])) perr_m = np.sqrt(np.diag(pcov_m)) # get EPC and EPC sigma for LSF accelerated alpha_fm = popt_m[1] p_tilde_m = popt_m[2] alpha_fm_err = perr_m[1] p_tilde_m_err = perr_m[2] popt_m,perr_m epc_est_fm = scale*(1 - p_tilde_m) epc_est_fm_err = scale*p_tilde_m_err original_model = bf.get_bayesian_model(model_type="pooled",Y=Y1,shots=shots,m_gates=nCliffs, mu_AB=[popt_s[0],popt_s[2]],cov_AB=[perr_s[0],perr_s[2]], alpha_ref=alpha_f) pm.model_to_graphviz(original_model) trace_o = bf.get_trace(original_model) azo_summary = bf.get_summary(original_model, trace_o) azo_summary alpha_original_p = azo_summary['mean']['alpha'] alpha_original_p_err = azo_summary['sd']['alpha'] interleaved_model = bf.get_bayesian_model(model_type="pooled",Y=Y2,shots=shots,m_gates=nCliffs, mu_AB=[popt_i[0],popt_i[2]],cov_AB=[perr_i[0],perr_i[2]], alpha_ref=alphC_f) pm.model_to_graphviz(interleaved_model) trace_i = bf.get_trace(interleaved_model) azi_summary = bf.get_summary(interleaved_model, trace_i) azi_summary alpha_c_p = azi_summary['mean']['alpha'] alpha_c_p_err = azi_summary['sd']['alpha'] epc_est_p = scale*(1 - alpha_c_p/alpha_original_p) epc_est_p_err = scale*(alpha_c_p/alpha_original_p)*(np.sqrt(alpha_original_p_err**2 + alpha_c_p_err**2)) Y = np.vstack((Y1,Y2)) RvsI = np.vstack((np.ones_like(Y1),np.zeros_like(Y2))) IvsR = np.vstack((np.zeros_like(Y1),np.ones_like(Y2))) tilde =bf.get_bayesian_model("tilde",Y=Y,shots=shots, m_gates=nCliffs, alpha_ref=alpha_fm, p_testval= p_tilde_m, mu_AB=[popt_m[0],popt_m[3]],cov_AB=[perr_m[0],perr_m[3]], RvsI=RvsI,IvsR=IvsR) pm.model_to_graphviz(tilde) trace_t = bf.get_trace(tilde) azt_summary = bf.get_summary(tilde, trace_t) azt_summary epc_est_a = scale*(1 - azt_summary['mean']['p_tilde']) epc_est_a_err = scale* (azt_summary['sd']['p_tilde']) epc_calib = 0.0 # not for simulation # compare LSF and SMC print("Model: Frequentist Bayesian ") print(" two-run accelerated two-run accelerated ") print("EPC {0:.5f} {1:.5f} {2:.5f} {3:.5f} " .format(epc_est_f, epc_est_fm, epc_est_p, epc_est_a)) print("± sigma ± {0:.5f} ± {1:.5f} ± {2:.5f} ± {3:.5f} " .format(epc_est_f_err, epc_est_fm_err, epc_est_p_err, epc_est_a_err)) # obtain EPC from alpha (used by plot_posterior) def alpha_to_EPC(alpha): return scale*(1-alpha) # for refering the interleaved gate in the title of the graphs intl_g=str(interleaved_gates[0][0][0:2])+str(rb_pattern[0][0:2]) if RB_process in ["3_Q RB","2-3_Q RB"] : intl_g=intl_g+"<"+str(interleaved_gates[1][0][0:1]+str(rb_pattern[1][0:2])) import matplotlib.pyplot as plt # seems we need to reimport for replot WIP with tilde: ax = az.plot_posterior(trace_t, var_names=['p_tilde'], round_to=4, point_estimate=None, transform = alpha_to_EPC) ax.set_xlim(0.003, 0.007) plt.axvline(x=epc_est_fm,color='red',ls="-") plt.axvline(x=epc_est_p,color='orange',ls="-") plt.axvline(x=epc_est_f,color='cyan',ls="-") if epc_calib > 0.0: plt.axvline(x=epc_calib,color='green',ls=":") plt.axvline(x=epc_est_a,color='blue',ls=":") plt.title(RB_process +' $accelerated$, gate: ' + intl_g\ +", "+hardware+', backend: '+backend.name(), fontsize=12) Bayes_legend = "EPC Accelerated SMC: {0:1.3e} ({1:1.3e})".format(epc_est_a, epc_est_a_err) Bayes2_legend = "EPC SMC 2-runs: {0:1.3e} ({1:1.3e})".format(epc_est_p, epc_est_p_err) Fitter_legend = "EPC LSF 2-runs: {0:1.3e} ({1:1.3e})".format(epc_est_f, epc_est_f_err) LSM_legend = "EPC Accelerated LSF: {0:1.3e} ({1:1.3e})".format(epc_est_fm, epc_est_fm_err) Cal_legend = "EPC Calibration: {0:1.3e}".format(epc_calib) if epc_calib > 0.0: plt.legend((Bayes_legend, "$Higher\; density\; interval$ HDI", LSM_legend,Bayes2_legend, Fitter_legend,Cal_legend), fontsize=10 ) else: plt.legend((Bayes_legend, "$Higher\; density\; interval$ HDI", LSM_legend, Bayes2_legend, Fitter_legend), fontsize=10 ) import matplotlib.pyplot as plt # seems we need to reimport for replot WIP fig, plt = plt.subplots(1, 1) plt.set_ylabel("Ground State Population") plt.set_xlabel("Number of Cliffords") for i_seed in range(nseeds): plt.scatter(nCliffs, Y1[i_seed,:]/shots, label = "data", marker="x",color="b") plt.scatter(nCliffs, Y2[i_seed,:]/shots, label = "data", marker="+",color="r") plt.plot(nCliffs,azt_summary['mean']['AB[0]']*azt_summary['mean']['alpha']**nCliffs+\ azt_summary['mean']['AB[1]'],'--',color="b") plt.plot(nCliffs,azt_summary['mean']['AB[0]']*(azt_summary['mean']['alpha']*azt_summary['mean']['p_tilde'])**\ nCliffs+azt_summary['mean']['AB[1]'],'--',color="r") plt.legend(("Standard", "Interleaved")) plt.set_title(RB_process +' SMC $accelerated$, gate: ' + intl_g\ +", "+hardware+', backend: '+backend.name(), fontsize=14); import qiskit.tools.jupyter %qiskit_version_table
https://github.com/LauraGentini/QRL
LauraGentini
__author__ = 'QRL_team' from qiskit import * from qiskit.circuit.library import GroverOperator from qiskit.quantum_info import Statevector import numpy as np from math import ceil from qttt import QTicTacToeEnv class GroverQuantumBoardLearner: """ Inits a quantum QLearner object. Chosen environment must be discrete! """ def __init__(self, env): self.env = env # in this approach we do not know in advance how many possible states are there, # they will be added during training self.obs_dim = 1 # number of possible actions extracted from env self.acts_dim = self.env.action_space.n # evaluate number of needed qubits to encode actions self.acts_reg_dim = ceil(np.log2(self.acts_dim)) # evaluate maximum number of grover steps self.max_grover_steps = int(round(np.pi/(4*np.arcsin(1./np.sqrt(2**self.acts_reg_dim))) - 0.5)) # state variable self.state = self.env.reset() # action variable self.action = 0 # init dictionary of quality values, str(state) is used for better comparison self.state_vals = {str(self.state): 0.} # init dict of grover steps for each state-action pair self.grover_steps = {str(self.state): np.zeros(self.acts_dim, dtype=int)} # init dict of flags to stop grover amplification, needed when acts_dim = 4 self.grover_steps_flag = {str(self.state): np.zeros(self.acts_dim, dtype=bool)} # learner hyperparameters self.hyperparams = {'k': -1, 'alpha': 0.05, 'gamma': 0.99} # grover oracles self.grover_ops = self._init_grover_ops() # state-action circuits self.acts_circs = self._init_acts_circs() self.SIM = Aer.get_backend('qasm_simulator') def set_hyperparams(self, hyperdict): """ Set new values for learner's hyperparameters :param hyperdict: :return: nthg """ self.hyperparams = hyperdict def _new_state_check(self, newstate): """ Checks if newstate was already observed :param newstate: :return: nthg """ if str(newstate) in self.state_vals.keys(): return else: self.state_vals[str(newstate)] = 0. self.grover_steps[str(newstate)] = np.zeros(self.acts_dim, dtype=int) self.grover_steps_flag[str(newstate)] = np.zeros(self.acts_dim, dtype=bool) self._append_new_circ(newstate) def _init_acts_circs(self): """ Creates the state-action circuits and inits them in full superposition :return: dict of said circuits, keys are strings of state vectors """ circs = {str(self.state): QuantumCircuit(self.acts_reg_dim)} for _, c in circs.items(): c.h(list(range(self.acts_reg_dim))) return circs def _append_new_circ(self, state): """ Inits a new state-action circuit :param state: :return: """ self.acts_circs[str(state)] = QuantumCircuit(self.acts_reg_dim) self.acts_circs[str(state)].h(list(range(self.acts_reg_dim))) def _update_statevals(self, reward, new_state): """ Bellman equation to update state values :param reward: the instantaneous reward received by the agent :param new_state: the new state visited by the agent :return: """ self.state_vals[str(self.state)] += self.hyperparams['alpha']\ * (reward + self.hyperparams['gamma']*self.state_vals[str(new_state)] - self.state_vals[str(self.state)]) def _eval_grover_steps(self, reward, new_state): """ Choose how many grover step to take based on instantaneous reward and value of new state :param reward: the instantaneous reward received by the agent :param new_state: the new state visited by the agent :return: number of grover steps to be taken, if it exceeds the theoretical optimal number the latter is returned instead """ steps_num = int(self.hyperparams['k']*(reward + self.state_vals[str(new_state)])) return min(steps_num, self.max_grover_steps) def _init_grover_ops(self): """ Inits grover oracles for the actions set :return: a list of qiskit instructions ready to be appended to circuit """ states_binars = [format(i, '0{}b'.format(self.acts_reg_dim)) for i in range(self.acts_dim)] targ_states = [Statevector.from_label(s) for s in states_binars] grops = [GroverOperator(oracle=ts) for ts in targ_states] return [g.to_instruction() for g in grops] def _run_grover(self): """ Deploy grover ops on acts_circs :return: """ gsteps = self.grover_steps[str(self.state)][self.action] circ = self.acts_circs[str(self.state)] op = self.grover_ops[self.action] for _ in range(gsteps): circ.append(op, list(range(self.acts_reg_dim))) self.acts_circs[str(self.state)] = circ def _run_grover_bool(self): """ Update state-action circuits based on evaluated steps :return: """ flag = self.grover_steps_flag[str(self.state)] gsteps = self.grover_steps[str(self.state)][self.action] circ = self.acts_circs[str(self.state)] op = self.grover_ops[self.action] if not flag.any(): for _ in range(gsteps): circ.append(op, list(range(self.acts_reg_dim))) if gsteps >= self.max_grover_steps and not flag.any(): self.grover_steps_flag[str(self.state)][self.action] = True self.acts_circs[str(self.state)] = circ def _take_action(self): """ Measures state-action circuit and chooses which action to take :return: int, chosen action """ action = self.acts_dim + 1 while action >= self.acts_dim: circ = self.acts_circs[str(self.state)] circ_tomeasure = circ.copy() circ_tomeasure.measure_all() # circ_tomeasure = transpile(circ_tomeasure) # print(circ.draw()) job = execute(circ_tomeasure, backend=self.SIM, shots=1) result = job.result() counts = result.get_counts() action = int((list(counts.keys()))[0], 2) return action # test if __name__ == "__main__": def train(env, pl1, pl2, hyperparams): traj_dict = {} stats = {"Pl1 wins": [], "Pl2 wins": [], "Draws": []} # set initial max_steps gamelen = hyperparams['game_length'] for epoch in range(hyperparams['max_epochs']): if epoch % 10 == 0: print("Processing epoch {} ...".format(epoch)) # reset env state = env.reset() # init list for traj traj = [state] if hyperparams['graphics']: env.render() for step in range(gamelen): print('\rTurn {0}/{1}'.format(step, gamelen)) # pl1 goes first, then pl2 for player in (pl1, pl2): player._new_state_check(state) player.state = state # Select action action = player._take_action() #self._run_grover_bool() player.action = action # take action new_state, reward, done = env.step(action) player._new_state_check(new_state) player.state = state # print('REWARD: ', reward) # update statevals and grover steps player._update_statevals(reward, new_state) player.grover_steps[str(state)][action] = player._eval_grover_steps(reward, new_state) # amplify amplitudes with zio grover # player._run_grover() player._run_grover_bool() # render if curious if hyperparams['graphics']: env.render() # save transition traj.append(new_state) state = new_state # measure and observe outcome final = env.collapse_board() print("Observed board state: ", final) winner = env.check_end(final) if winner == 1: stats["Pl1 wins"].append(epoch) pl1._new_state_check(state) pl1._update_statevals(100, state) pl2._new_state_check(state) pl2._update_statevals(-10, state) elif winner == 2: stats["Pl2 wins"].append(epoch) pl2._new_state_check(state) pl2._update_statevals(100, state) pl1._new_state_check(state) pl1._update_statevals(-10, state) else: stats["Draws"].append(epoch) pl1._new_state_check(state) pl1._update_statevals(-5, state) pl2._new_state_check(state) pl2._update_statevals(-5, state) traj_dict['epoch_{}'.format(epoch)] = traj # return trajectories return traj_dict, stats board_dim = 2 # game_length = 5 env = QTicTacToeEnv(board_dim) player_1 = GroverQuantumBoardLearner(env) player_2 = GroverQuantumBoardLearner(env) game_hyperparms = {'max_epochs': 100, 'game_length': 4, 'graphics': False} player_hyperparms = {'k': 0.1, 'alpha': 0.05, 'gamma': 0.99} player_1.set_hyperparams(player_hyperparms) player_2.set_hyperparams(player_hyperparms) game_trajectories, game_stats = train(env, player_1, player_2, game_hyperparms) # print(game_trajectories) print(game_stats) print(player_1.state_vals) print(player_1.grover_steps)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools import pickle plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.providers.aer import QasmSimulator from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity # Suppress warnings import warnings warnings.filterwarnings('ignore') def trotter_gate(dt, to_instruction = True): qc = QuantumCircuit(2) qc.rx(2*dt,0) qc.rz(2*dt,1) qc.h(1) qc.cx(1,0) qc.rz(-2*dt, 0) qc.rx(-2*dt, 1) qc.rz(2*dt, 1) qc.cx(1,0) qc.h(1) qc.rz(2*dt, 0) return qc.to_instruction() if to_instruction else qc trotter_gate(np.pi / 6, to_instruction=False).draw("mpl") # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate Trot_gate = trotter_gate(dt) # Number of trotter steps trotter_steps = 100 ### CAN BE >= 4 # Initialize quantum circuit for 3 qubits qr = QuantumRegister(7) qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) qc.x([5]) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) # Simulate time evolution under H_heis3 Hamiltonian for _ in range(trotter_steps): qc.append(Trot_gate, [qr[3], qr[5]]) qc.cx(qr[3], qr[1]) qc.cx(qr[5], qr[3]) # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time/trotter_steps}) t3_qc = transpile(qc, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_qc = transpile(t3_qc, optimization_level=3, basis_gates=["sx", "cx", "rz"]) # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(t3_qc, [qr[1], qr[3], qr[5]]) # Display circuit for confirmation # st_qcs[-1].decompose().draw() # view decomposition of trotter gates st_qcs[-1].draw("mpl") # only view trotter gates from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") shots = 8192 reps = 8 jobs = [] for _ in range(reps): # execute job = execute(st_qcs, backend, shots=shots) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3) print('Job ID', cal_job.job_id()) with open("jakarta_100step.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open("jakarta_100step.pkl", "rb") as f: job_list = pickle.load(f) jobs = job_list["jobs"] cal_job = job_list["cal_job"] cal_results = cal_job.result() print("retrieved cal_results") qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') results = [] mit_results = [] for i, job in enumerate(jobs): results.append(job.result()) mit_results.append( meas_fitter.filter.apply(job.result()) ) print("retrieved", i, "th results") # Compute the state tomography based on the st_qcs quantum circuits and the results from those ciricuits def state_tomo(result, st_qcs): # The expected final state; necessary to determine state tomography fidelity target_state = (One^One^Zero).to_matrix() # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) # Fit state tomography results tomo_fitter = StateTomographyFitter(result, st_qcs) rho_fit = tomo_fitter.fit(method='lstsq') # Compute fidelity fid = state_fidelity(rho_fit, target_state) return fid # Compute tomography fidelities for each repetition fids = [] for result in results: fid = state_tomo(result, st_qcs) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids))) mit_fids = [] for mit_result in mit_results: mit_fid = state_tomo(mit_result, st_qcs) mit_fids.append(mit_fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(mit_fids), np.std(mit_fids)))
https://github.com/veenaiyuri/qiskit-education
veenaiyuri
# coding: utf-8 # Copyright © 2018 IBM Research # Adapted from and/or inspired by # * initialization tool by Mirko Amico # https://github.com/Qiskit/qiskit-tutorials/blob/awards/community/awards/teach_me_quantum_2018/intro2qc/initialize.py # * qreative by James R. Wootton # https://github.com/quantumjim/qreative/blob/master/qreative/qreative.py from qiskit import * from qiskit.tools.visualization import plot_histogram as plothistogram def get_backend(device): """Returns backend object for device specified by input string.""" try: try: backend = Aer.get_backend(device) except: backend = BasicAer.get_backend(device) except: backend = IBMQ.get_backend(device) return backend def get_noise(noisy): """Returns a noise model when input is not False or None. A string will be interpreted as the name of a backend, and the noise model of this will be extracted. A float will be interpreted as an error probability for a depolarizing+measurement error model. Anything else (such as True) will give the depolarizing+measurement error model with default error probabilities.""" if noisy: if type(noisy) is str: device = get_backend(noisy) noise_model = noise.device.basic_device_noise_model( device.properties() ) else: if type(noisy) is float: p_meas = noisy p_gate1 = noisy else: p_meas = 0.08 p_gate1 = 0.04 error_meas = pauli_error([('X',p_meas), ('I', 1 - p_meas)]) error_gate1 = depolarizing_error(p_gate1, 1) error_gate2 = error_gate1.kron(error_gate1) noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(error_meas, "measure") noise_model.add_all_qubit_quantum_error(error_gate1, ["u1", "u2", "u3"]) noise_model.add_all_qubit_quantum_error(error_gate2, ["cx"]) else: noise_model = None return noise_model class QuantumAlgorithm: """""" def __init__ (self, qregs, cregs): qubit = {} if type(qregs)!=list: qregs = [(qregs,'q')] if type(cregs)!=list: cregs = [(cregs,'c')] self.qc = QuantumCircuit() for qreg in qregs: exec( 'self.'+qreg[1]+'=QuantumRegister('+str(qreg[0])+',"'+str(qreg[1])+'")' ) exec( 'self.qc.add_register( self.'+qreg[1]+')' ) for creg in cregs: exec( 'self.'+creg[1]+'=ClassicalRegister('+str(creg[0])+',"'+str(creg[1])+'")' ) exec( 'self.qc.add_register( self.'+creg[1]+')' ) # methods to implement the methods of qc, in exactly the same manner as terra 0.7 def x(self,qubit): self.qc.x(qubit) def y(self,qubit): self.qc.y(qubit) def z(self,qubit): self.qc.z(qubit) def h(self,qubit): self.qc.h(qubit) def s(self,qubit): self.qc.s(qubit) def sdg(self,qubit): self.qc.sdg(qubit) def t(self,qubit): self.qc.t(qubit) def tdg(self,qubit): self.qc.tdg(qubit) def cx(self,control,target): self.qc.cx(control,target) def cz(self,control,target): self.qc.cz(control,target) def ccx(self,control1,control2,target): self.qc.cx(control1,control2,target) def measure(self,qubit,bit): self.qc.measure(qubit,bit) def execute(self,device='qasm_simulator',noisy=False,shots=1024,histogram=True): backend = get_backend(device) try: job = execute(self.qc,backend,shots=shots,noise_model=get_noise(noisy),memory=True) data = {'counts':job.result().get_counts(),'memory':job.result().get_memory()} except: try: job = execute(self.qc,backend,shots=shots,memory=True) data = {'counts':job.result().get_counts(),'memory':job.result().get_memory()} except: job = execute(self.qc,backend,shots=shots) data = {'counts':job.result().get_counts()} if histogram: self.plot_histogram(data['counts']) return data def plot_histogram(self,counts): return plothistogram(counts)
https://github.com/bayesian-randomized-benchmarking/qiskit-advocates-bayes-RB
bayesian-randomized-benchmarking
#Import general libraries (needed for functions) import numpy as np import matplotlib.pyplot as plt from IPython import display #Import Qiskit classes import qiskit from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors.standard_errors import depolarizing_error, thermal_relaxation_error #Import the RB Functions import qiskit.ignis.verification.randomized_benchmarking as rb import copy # import the bayesian packages import pymc3 as pm import arviz as az from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() from qiskit.tools.monitor import job_monitor device = provider.get_backend('ibmq_lima') # initialize the Bayesian extension %config InlineBackend.figure_format = 'retina' # Initialize random number generator RANDOM_SEED = 8927 np.random.seed(RANDOM_SEED) az.style.use("arviz-darkgrid") def obtain_priors_and_data_from_fitter(printout = True): m_gates = copy.deepcopy(nCliffs) # We choose the count matrix corresponding to 2 Qubit RB Y = (np.array(rbfit._raw_data[0])*shots).astype(int) # alpha prior and bounds alpha_ref = rbfit._fit[0]['params'][1] alpha_lower = alpha_ref - 2*rbfit._fit[0]['params_err'][1] # modified for real alpha_upper = alpha_ref + 2*rbfit._fit[0]['params_err'][1] # modified for real # priors for A anbd B mu_AB = np.delete(rbfit._fit[0]['params'],1) cov_AB=np.delete(rbfit._fit[0]['params_err'],1)**2 # prior for sigmatheta: sigma_theta = 0.004 if printout: print("priors:\nalpha_ref",alpha_ref) print("alpha_lower", alpha_lower, "alpha_upper", alpha_upper) print("A,B", mu_AB, "\ncov A,B", cov_AB) print("sigma_theta", sigma_theta) return m_gates, Y, alpha_ref, alpha_lower, alpha_upper, mu_AB, cov_AB, sigma_theta def get_bayesian_model(model_type): # Bayesian model # from https://iopscience.iop.org/article/10.1088/1367-2630/17/1/013042/pdf # see https://docs.pymc.io/api/model.html RB_model = pm.Model() with RB_model: #Priors for unknown model parameters alpha = pm.Uniform("alpha",lower=alpha_lower, upper=alpha_upper, testval = alpha_ref) BoundedMvNormal = pm.Bound(pm.MvNormal, lower=0.0) AB = BoundedMvNormal("AB", mu=mu_AB,testval = mu_AB, cov= np.diag(cov_AB), shape = (2)) # Expected value of outcome GSP = AB[0]*alpha**m_gates + AB[1] if model_type == "pooled": total_shots = np.full(Y.shape, shots) theta = GSP elif model_type == "hierarchical": total_shots = np.full(Y.shape, shots) theta = pm.Beta("GSP", mu=GSP, sigma = sigma_theta, shape = Y.shape[1]) # Likelihood (sampling distribution) of observations p = pm.Binomial("Counts", p=theta, observed=Y, n = total_shots) return RB_model def get_trace(RB_model): # Gradient-based sampling methods # see also: https://docs.pymc.io/notebooks/sampler-stats.html # and https://docs.pymc.io/notebooks/api_quickstart.html with RB_model: trace= pm.sample(draws = 2000, tune= 10000, target_accept=0.9, return_inferencedata=True) with RB_model: az.plot_trace(trace); return trace def get_summary(RB_model, trace, hdi_prob=.94, kind='all'): with RB_model: # (hdi_prob=.94 is default) az_summary = az.summary(trace, round_to=4, hdi_prob=hdi_prob, kind=kind ) return az_summary # obtain EPC from alpha (used by plot_posterior) def alpha_to_EPC(alpha): return 3*(1-alpha)/4 def get_EPC_and_legends(azs): EPC_Bayes = alpha_to_EPC(azs['mean']['alpha']) EPC_Bayes_err = EPC_Bayes - alpha_to_EPC(azs['mean']['alpha']+azs['sd']['alpha']) Bayes_legend ="EPC Bayes {0:.5f} ({1:.5f})".format(EPC_Bayes, EPC_Bayes_err) Fitter_legend ="EPC Fitter {0:.5f} ({1:.5f})".format(rbfit.fit[0]['epc']\ ,rbfit._fit[0]['epc_err']) pred_epc_legend = "EPC predicted {0:.5f}".format(pred_epc) return EPC_Bayes, EPC_Bayes_err, Bayes_legend,Fitter_legend, pred_epc_legend def EPC_compare_fitter_to_bayes(RB_model, azs, trace): EPC_Bayes, EPC_Bayes_err, Bayes_legend,Fitter_legend, pred_epc_legend = get_EPC_and_legends(azs) with RB_model: az.plot_posterior(trace, var_names=['alpha'], round_to=4, transform = alpha_to_EPC, point_estimate=None) plt.title("Error per Clifford") plt.axvline(x=alpha_to_EPC(alpha_ref),color='red') #plt.axvline(x=pred_epc,color='green') # WIP #plt.legend((Bayes_legend, "Higher density interval",Fitter_legend, pred_epc_legend), fontsize=10 )# WIP plt.legend((Bayes_legend, "Higher density interval",Fitter_legend), fontsize=10 ) plt.show() def GSP_compare_fitter_to_bayes(RB_model, azs): EPC_Bayes, EPC_Bayes_err, Bayes_legend,Fitter_legend,_ = get_EPC_and_legends(azs) # plot ground state population ~ Clifford length fig, axes = plt.subplots(1, 1, sharex=True, figsize=(10, 6)) axes.set_ylabel("Ground State Population") axes.set_xlabel("Clifford Length") axes.plot(m_gates, np.mean(Y/shots,axis=0), 'r.') axes.plot(m_gates,azs['mean']['AB[0]']*azs['mean']['alpha']**m_gates+azs['mean']['AB[1]'],'--') #axes.plot(m_gates,azs['mean']['GSP'],'--') # WIP #axes.errorbar(m_gates, azs['mean']['GSP'], azs['sd']['GSP'], linestyle='None', marker='^') # WIP axes.plot(m_gates,mu_AB[0]*np.power(alpha_ref,m_gates)+mu_AB[1],':') for i_seed in range(nseeds): plt.scatter(m_gates-0.25, Y[i_seed,:]/shots, label = "data", marker="x") axes.legend(["Mean Observed Frequencies", "Bayesian Model\n"+Bayes_legend, "Fitter Model\n"+Fitter_legend],fontsize=12) #axes.set_title('2 Qubit RB with T1/T2 Noise', fontsize=18) # WIP def get_predicted_EPC(error_source): #Count the number of single and 2Q gates in the 2Q Cliffords gates_per_cliff = rb.rb_utils.gates_per_clifford(transpile_list,xdata[0],basis_gates,rb_opts['rb_pattern'][0]) for basis_gate in basis_gates: print("Number of %s gates per Clifford: %f "%(basis_gate , np.mean([gates_per_cliff[rb_pattern[0][0]][basis_gate], gates_per_cliff[rb_pattern[0][1]][basis_gate]]))) # Calculate the predicted epc # from the known depolarizing errors on the simulation if error_source == "depolarization": # Error per gate from noise model epgs_1q = {'u1': 0, 'u2': p1Q/2, 'u3': 2*p1Q/2} epg_2q = p2Q*3/4 pred_epc = rb.rb_utils.calculate_2q_epc( gate_per_cliff=gates_per_cliff, epg_2q=epg_2q, qubit_pair=[0, 2], list_epgs_1q=[epgs_1q, epgs_1q]) # using the predicted primitive gate errors from the coherence limit if error_source == "from_T1_T2": # Predicted primitive gate errors from the coherence limit u2_error = rb.rb_utils.coherence_limit(1,[t1],[t2],gate1Q) u3_error = rb.rb_utils.coherence_limit(1,[t1],[t2],2*gate1Q) epg_2q = rb.rb_utils.coherence_limit(2,[t1,t1],[t2,t2],gate2Q) epgs_1q = {'u1': 0, 'u2': u2_error, 'u3': u3_error} pred_epc = rb.rb_utils.calculate_2q_epc( gate_per_cliff=gates_per_cliff, epg_2q=epg_2q, qubit_pair=[0, 1], list_epgs_1q=[epgs_1q, epgs_1q]) return pred_epc def get_count_data(result_list): ### another way to obtain the observed counts Y_list = [] for rbseed, result in enumerate(result_list): row_list = [] for c_index, c_value in enumerate(nCliffs): if nQ == 2: list_bitstring = ['00'] elif nQ == 3: list_bitstring = ['000', '100'] # because q2 measured in c1 total_counts = 0 for bitstring in list_bitstring: total_counts += result.get_counts()[c_index][bitstring] row_list.append(total_counts) Y_list.append(row_list) return np.array(Y_list) #Number of qubits nQ = 2 #There are 2 qubits: Q0,Q1. #Number of seeds (random sequences) nseeds = 10 # more data for the Rev. Mr. Bayes #Number of Cliffords in the sequence (start, stop, steps) nCliffs = np.arange(1,200,20) #2Q RB Q0,Q1 rb_pattern = [[0,1]] length_multiplier = 1 rb_opts = {} rb_opts ['length_vector'] = nCliffs rb_opts ['nseeds'] = nseeds rb_opts ['rb_pattern'] = rb_pattern rb_opts ['length_multiplier'] = length_multiplier rb_circs , xdata = rb.randomized_benchmarking_seq(**rb_opts ) backend = device basis_gates = ['u1','u2','u3','cx'] # use U,CX for now shots = 1024 result_list = [] transpile_list = [] import time for rb_seed,rb_circ_seed in enumerate(rb_circs): print('Compiling seed %d'%rb_seed) rb_circ_transpile = qiskit.transpile(rb_circ_seed, optimization_level=0, basis_gates=basis_gates) print('Runing seed %d'%rb_seed) job = qiskit.execute(rb_circ_transpile, shots=shots, backend=backend) job_monitor(job) result_list.append(job.result()) transpile_list.append(rb_circ_transpile) print("Finished Real Jobs") print(rb_circs[0][0]) #Create an RBFitter object rbfit = rb.RBFitter(result_list, xdata, rb_opts['rb_pattern']) m_gates, Y, alpha_ref, alpha_lower, alpha_upper, mu_AB, cov_AB, sigma_theta =\ obtain_priors_and_data_from_fitter(printout = True) ### a check of the count matrix np.sum((Y == (get_count_data(result_list)))*1) == Y.size pooled = get_bayesian_model("pooled") pm.model_to_graphviz(pooled) trace_p = get_trace(pooled) azp_summary = get_summary(pooled, trace_p) azp_summary hierarchical = get_bayesian_model("hierarchical") pm.model_to_graphviz(hierarchical) trace_h = get_trace(hierarchical) azh_summary = get_summary(hierarchical, trace_h) azh_summary # Leave-one-out Cross-validation (LOO) comparison df_comp_loo = az.compare({"hierarchical": trace_h, "pooled": trace_p}) df_comp_loo az.plot_compare(df_comp_loo, insample_dev=False); # predict EPC from the noisy model #pred_epc = get_predicted_EPC(error_source = 'from_T1_T2') # this was for a noise model pred_epc = 0.0165 # will not appear on graphs for real device but at this point functions need value (WIP) print("Fake 2Q Error per Clifford: %e"%pred_epc) EPC_compare_fitter_to_bayes(pooled, azp_summary, trace_p) EPC_compare_fitter_to_bayes(hierarchical, azh_summary, trace_h) GSP_compare_fitter_to_bayes(pooled, azp_summary) GSP_compare_fitter_to_bayes(hierarchical, azh_summary) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright %load_ext watermark %watermark -n -u -v -iv -w
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit.visualization import plot_circuit_layout from qiskit.providers.fake_provider import FakeVigo backend = FakeVigo() ghz = QuantumCircuit(3, 3) ghz.h(0) ghz.cx(0,range(1,3)) ghz.barrier() ghz.measure(range(3), range(3)) new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3) plot_circuit_layout(new_circ_lv3, backend)
https://github.com/Slope86/QiskitExtension
Slope86
import math import random from qiskit_extension.quantum_circuit2 import QuantumCircuit2 as qc2 from qiskit_extension.state_vector2 import StateVector2 as sv2 state_unknown = sv2.from_label((random.random(), "0"), (random.random(), "1")) state_unknown.show_state() # Create a 2bits quantum circuit circ_init = qc2(2) # Entangle two ground state qubits to an EPR pair circ_init.h(0) circ_init.cx(0,1) # Put the ground state into the circuit to get the EPR pair state_EPR = sv2(circ_init) # Show state_EPR, confirm it is EPR pair state_EPR.show_state() # Combined state_unknown and state_EPR into a 3-qubit sv2 object state_before_teleport = state_unknown.expand(state_EPR) state_before_teleport.show_state() # Create the circuit for Bell measurement circ_bell = qc2(3) circ_bell.cx(0,1) circ_bell.h(0) # Bell measurement on qubits(0,1), and store the four possible states as a list after measurement # list[0b00]=state after measurement result is 00, # list[0b01]=state after measurement result is 01, # ... list_state_after_measure = state_before_teleport.evolve(circ_bell).measure([0,1]) # Show the four possible states after the Bell measurement # Display format: (|00> indicates the measured state, followed by a colon indicating [the remaining state after measurement result is 00]) # |00>: 1/2|0> + 1/2|1> ... state_before_teleport.evolve(circ_bell).show_measure([0,1]) state_after_teleport = list_state_after_measure[0b00] state_after_teleport.show_state(hide=[0,1]) # Correction circuit circ_correction = qc2(3) circ_correction.x(2) # Applying the correction circuit state_after_teleport = list_state_after_measure[0b01].evolve(circ_correction) state_after_teleport.show_state(hide=[0,1]) # Correction circuit circ_correction = qc2(3) circ_correction.z(2) # Applying the correction circuit state_after_teleport = list_state_after_measure[0b10].evolve(circ_correction) state_after_teleport.show_state(hide=[0,1]) # Correction circuit circ_correction = qc2(3) circ_correction.x(2) circ_correction.z(2) # Applying the correction circuit state_after_teleport = list_state_after_measure[0b11].evolve(circ_correction) state_after_teleport.show_state(hide=[0,1])
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
import unittest from matplotlib.pyplot import close import numpy as np import hypothesis.strategies as st from hypothesis import given, settings from qiskit import QuantumCircuit, Aer, execute from qiskit.circuit.library import QFT from math import pi, degrees, sqrt, sin, cos # importing sys import sys from sympy import false # adding Folder_2 to the system path import pathlib sys.path.insert(0, str(pathlib.Path().resolve())+f"/Property_Assertion") from QuantumAssertions import assertPhase ##################################################################################### ### Change the file to import from, in order to test a mutant version of the code ### ################################################################################################## ### e.g. from Add_mutant_1 import remove_garbage, generate_binary, encode_message, measure_message ################################################################################################## from QuantumFourierTransform import qft_rotations, flip_endian, qft_rotations_not_inplace ########################################################################### ## Define composite strategies to generate lists of ints in equal length ## ########################################################################### @st.composite def size_and_value_to_input(draw): circuit_size = draw(st.integers(min_value=1, max_value=4)) value = draw(st.integers(min_value=0, max_value=(2**circuit_size)-1)) return(circuit_size,value) ########################## ## test generate binary ## ########################## @given(size_and_value_to_input()) @settings(deadline=None) def test_qft_then_inverse(vals): size = vals[0] value = vals[1] qc = QuantumCircuit(size) binValue = bin(value)[2:].zfill(size)[::-1] for i in range(size): if binValue[i] == "1": qc.x(i) qft_rotations(qc, size) qc.append(QFT(num_qubits=size, do_swaps=false, inverse=True), [i for i in range(size)]) qc.measure_all() backend = Aer.get_backend('aer_simulator') job = execute(qc, backend, shots=1, memory=True) readings = job.result().get_memory()[0] assert(value == int(readings,2)) @given(size_and_value_to_input()) @settings(deadline=None) def test_specific_phase(vals): size = vals[0] value = vals[1] qc = QuantumCircuit(size) binValue = bin(value)[2:].zfill(size)[::-1] for i in range(size): if binValue[i] == "1": qc.x(i) qft_rotations(qc, size) backend = Aer.get_backend('aer_simulator') expected_values = [] print(size) print(value) for i in range(size): expected_values.append(degrees(pi*value/2**i)%360) assertPhase(backend, qc, [i for i in range(size)], expected_values, 3000000, 0.01) @given(size_and_value_to_input()) @settings(deadline=None) def test_superposition_inputs(vals): size = vals[0] value = vals[1] qc = QuantumCircuit(size) expected_values = [] for i in range(size): expected_values.append(degrees(pi*value/2**i)%360) init_vector = calculate_tensor_product(angle_to_vector(expected_values))[0] #for vect in init_vector: #print(vect) qc.initialize(init_vector, [i for i in range(size)]) qc.append(qft_rotations_not_inplace(size).inverse(), [i for i in range(size)]) qc.measure_all() backend = Aer.get_backend('aer_simulator') job = execute(qc, backend, shots=10000)#run the circuit 1000000 times assert(len(job.result().get_counts()) == 1) assert(int(job.result().get_counts().most_frequent(), 2) == value) print(int(job.result().get_counts().most_frequent(), 2)) print(job.result().get_counts()) print(value) ########################### ## Define helper methods ## ########################### def calculate_tensor_product(vectors): """ takes in array of pairs of complex numbers returns statevector array (recursively) """ if vectors == []: return vectors elif len(vectors) == 1: return vectors else: v1 = vectors.pop(-1) v2 = vectors.pop(-1) newvect = [] for v1_val in v1: for v2_val in v2: newvect.append(v1_val*v2_val) vectors.append(newvect) return calculate_tensor_product(vectors) def angle_to_vector(expected_values): """ takes in array of angles (degrees) returns pairs of complex numbers """ plus = 1/sqrt(2) minus = -1/sqrt(2) plus_i = complex(0,1)/sqrt(2) minus_i = complex(0,-1)/sqrt(2) ret_vector = [] for angle in expected_values: basis_arr = [0, 90, 180, 270, 360] closest_basis_arr = [abs(x-angle) for x in basis_arr] closest = basis_arr[closest_basis_arr.index(min(closest_basis_arr))] closest_angle = closest_basis_arr[closest_basis_arr.index(min(closest_basis_arr))] #print("closest " + str(closest)) #print("closest angle " + str(closest_angle)) basis_arr.pop(closest_basis_arr.index(min(closest_basis_arr))) closest_basis_arr.pop(closest_basis_arr.index(min(closest_basis_arr))) second_closest = basis_arr[closest_basis_arr.index(min(closest_basis_arr))] second_closest_angle = closest_basis_arr[closest_basis_arr.index(min(closest_basis_arr))] #print("second closest " + str(second_closest)) #print("second closest angle " + str(second_closest_angle)) if closest == 0: if second_closest == 90: ret_vector.append([1/sqrt(2) , cos(closest_angle * pi / 180) * plus + sin(closest_angle * pi / 180) * plus_i]) else: ret_vector.append([1/sqrt(2) , cos(closest_angle * pi / 180) * plus + sin(closest_angle * pi / 180) * minus_i]) elif closest == 90: if second_closest == 180: ret_vector.append([1/sqrt(2) , cos(closest_angle * pi / 180) * plus_i + sin(closest_angle * pi / 180) * minus]) else: ret_vector.append([1/sqrt(2) , cos(closest_angle * pi / 180) * plus_i + sin(closest_angle * pi / 180) * plus]) elif closest == 180: if second_closest == 270: ret_vector.append([1/sqrt(2) , cos(closest_angle * pi / 180) * minus + sin(closest_angle * pi / 180) * minus_i]) else: ret_vector.append([1/sqrt(2) , cos(closest_angle * pi / 180) * minus + sin(closest_angle * pi / 180) * plus_i]) elif closest == 270: if second_closest == 360: ret_vector.append([1/sqrt(2) , cos(closest_angle * pi / 180) * minus_i + sin(closest_angle * pi / 180) * plus]) else: ret_vector.append([1/sqrt(2) , cos(closest_angle * pi / 180) * minus_i + sin(closest_angle * pi / 180) * minus]) elif closest == 360: if second_closest == 90: ret_vector.append([1/sqrt(2) , cos(closest_angle * pi / 180) * plus + sin(closest_angle * pi / 180) * plus_i]) else: ret_vector.append([1/sqrt(2) , cos(closest_angle * pi / 180) * plus + sin(closest_angle * pi / 180) * minus_i]) #print(ret_vector) return ret_vector if __name__ == "__main__": #test_qft_then_inverse() test_specific_phase() #test_superposition_inputs()
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
#initialization import matplotlib.pyplot as plt import numpy as np import math # importing Qiskit from qiskit import Aer, transpile, assemble from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit.circuit.library import QFT # import basic plot tools from qiskit.visualization import plot_histogram, plot_bloch_multivector def qft_dagger(qc, n): """n-qubit QFTdagger the first n qubits in circ""" # Don't forget the Swaps! for qubit in range(n//2): qc.swap(qubit, n-qubit-1) for j in range(n): for m in range(j): qc.cp(-math.pi/float(2**(j-m)), m, j) qc.h(j) def generalised_qpe(amt_estimation_qubits, angle, shots=10000): # Create and set up circuit qpe3 = QuantumCircuit(amt_estimation_qubits+1, amt_estimation_qubits) # Apply H-Gates to counting qubits: for qubit in range(amt_estimation_qubits): qpe3.h(qubit) # Prepare our eigenstate |psi>: qpe3.x(amt_estimation_qubits) repetitions = 1 for counting_qubit in range(amt_estimation_qubits): for i in range(repetitions): qpe3.cp(angle, counting_qubit, amt_estimation_qubits); repetitions *= 2 # Do the inverse QFT: qft_dagger(qpe3, amt_estimation_qubits) # Measure of course! qpe3.barrier() for n in range(amt_estimation_qubits): qpe3.measure(n,n) # Let's see the results! aer_sim = Aer.get_backend('aer_simulator') t_qpe3 = transpile(qpe3, aer_sim) qobj = assemble(t_qpe3, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() answer2 = {int(k,2)/2**amt_estimation_qubits: v for k, v in answer.items()} print(answer2) print("Most frequent '" + answer.most_frequent() + "'") print("Approx rotation angle by Z from the unitary in degrees '" + str(360 * int(answer.most_frequent(), 2)/2**amt_estimation_qubits) + "'") print("Phase Calculation " + answer.most_frequent()) ##return(plot_histogram(answer)) ##comment out the return if you want to see the histogram return((int(answer.most_frequent(), 2)/2**amt_estimation_qubits)) #generalised_qpe(7,(13*math.pi/9)) #generalised_qpe(2,(3*math.pi/4)) generalised_qpe(7,(13*math.pi/9)) def visualise_rotation_angle(angle): sim = Aer.get_backend('aer_simulator') q = QuantumRegister(1,'q') c = ClassicalRegister(1,'c') qc = QuantumCircuit(q,c) qc.h(0) qc.p(angle, 0); qc.save_statevector() statevector = sim.run(qc).result().get_statevector() return(plot_bloch_multivector(statevector)) visualise_rotation_angle((2*math.pi)/3) visualise_rotation_angle(2*math.pi*(generalised_qpe(3,(2*math.pi)/3)))
https://github.com/Manish-Sudhir/QiskitCheck
Manish-Sudhir
import warnings from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute, Aer, transpile, IBMQ, assemble from qiskit.tools.monitor import job_monitor from qiskit.circuit.library import QFT from qiskit.visualization import plot_bloch_multivector, plot_histogram, array_to_latex warnings.filterwarnings("ignore", category=DeprecationWarning) import numpy as np import pandas as pd import math from math import sqrt from scipy.stats import chi2_contingency, ttest_ind, chisquare, ttest_rel, normaltest from statsmodels.stats.proportion import proportions_ztest from statsmodels.stats.weightstats import ztest pi = np.pi def flip_endian(dict): newdict = {} for key in list(dict): newdict[key[::-1]] = dict.pop(key) return newdict def set_measure_x(circuit, n): for num in range(n): circuit.h(num) def set_measure_y(circuit, n): for num in range(n): circuit.sdg(num) circuit.h(num) def qft_rotations(circuit, n): #if qubit amount is 0, then do nothing and return if n == 0: #set it to measure the x axis set_measure_x(qc, 2) qc.measure_all() return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(pi/2**(n-qubit), qubit, n) return qft_rotations(circuit, n) backend = Aer.get_backend('aer_simulator') qc = QuantumCircuit(2) qc.x(0) circ = qft_rotations(qc,2)#call the recursive qft method print(circ) #set it to measure the x axis set_measure_x(qc, 2) job = execute(qc, backend, shots=100000)#run the circuit 1000000 times print(flip_endian(job.result().get_counts()))#return the result counts def measure_z(circuit, qubit_indexes): cBitIndex = 0 for index in qubit_indexes: # print(index) circuit.measure(index, cBitIndex) cBitIndex+=1 return circuit def measure_x(circuit, qubitIndexes): cBitIndex = 0 for index in qubitIndexes: circuit.h(index) circuit.measure(index, cBitIndex) cBitIndex+=1 return circuit def measure_y(circuit, qubit_indexes): cBitIndex = 0 for index in qubit_indexes: circuit.sdg(index) circuit.h(index) circuit.measure(index, cBitIndex) cBitIndex+=1 return circuit qc1 = QuantumCircuit(2,2) qc1.h(0) qc1.cnot(0,1) qc1.measure(0,0) qc1.measure(1,1) # print(qc1) qc2 = QuantumCircuit(2,2) qc2.x(0) qc2.h(0) qc2.cnot(0,1) # qc2.swap(0,1) qc2.measure(0,1) qc2.measure(1,0) # qc2.measure_all() # print(qc2) backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute([qc1, qc2], backend_sim, shots=10) result_sim = job_sim.result() counts1 = result_sim.get_memory(qc1,memory=True) counts2 = result_sim.get_memory(qc2,memory=True) print(counts1, counts2) qc3 = QuantumCircuit(2,2) qc3.h(1) qc3.h(0) qubits_to_assert = [0,1] yQuantumCircuit = measure_y(qc3.copy(), qubits_to_assert) xQuantumCircuit = measure_x(qc3.copy(), qubits_to_assert) zQuantumCircuit = measure_z(qc3, qubits_to_assert) yJob = execute(yQuantumCircuit, backend, shots=20, memory=True) yMemory = yJob.result().get_memory() yCounts = yJob.result().get_counts() print(type(yMemory)) def qft_dagger(qc, n): for j in range(n): for m in range(j): qc.cp(math.pi/float(2**(j-m)), m, j) qc.h(j) return qc q = QuantumCircuit(2) # qc.x(0) q.x(0) q.x(1) q.measure_all() print(q) qft_rotations(q,2) q2 = qft_dagger(q,2)# #call the recursive qft method backend = Aer.get_backend('aer_simulator') job = execute([q,q2], backend, shots=1000000)#run the circuit 1000000 times counts = job.result().get_counts(q) counts2 = job.result().get_counts(q2) print(counts)#return the result counts print(counts2) def getDf(qc,qubits_to_assert,measurements_to_make,backend): ## classical register must be of same length as amount of qubits to assert ## if there is no classical register add them according to length of qubit list if (qc.num_clbits == 0): qc.add_register(ClassicalRegister(len(qubits_to_assert))) elif (len(qubits_to_assert) != 2): raise ValueError("QuantumCircuit classical register must be of length 2") ## divide measurements to make by 3 as we need to run measurements twice, one for x and one for y measurements_to_make = measurements_to_make // 3 yQuantumCircuit = measure_y(qc.copy(), qubits_to_assert) xQuantumCircuit = measure_x(qc.copy(), qubits_to_assert) zQuantumCircuit = measure_z(qc, qubits_to_assert) yJob = execute(yQuantumCircuit, backend, shots=measurements_to_make, memory=True) yMemory = yJob.result().get_memory() yCounts = yJob.result().get_counts() # print("yCounts",yCounts) ## get x axis results xJob = execute(xQuantumCircuit, backend, shots=measurements_to_make, memory=True) xMemory = xJob.result().get_memory() xCounts = xJob.result().get_counts() # print("xCounts",xCounts) ## get z axis results zJob = execute(zQuantumCircuit, backend, shots=measurements_to_make, memory=True) zMemory = zJob.result().get_memory() zCounts = zJob.result().get_counts() # print("zCounts",zCounts) resDf = pd.DataFrame(columns=['0','1','+','i','-','-i']) # resDf = pd.DataFrame(columns=['zAxis','xAxis','yAxis']) classical_qubit_index = 1 for qubit in qubits_to_assert: zero_amount, one_amount, plus_amount, i_amount, minus_amount, minus_i_amount = 0,0,0,0,0,0 for experiment in xCounts: if (experiment[2-classical_qubit_index] == '0'): plus_amount += xCounts[experiment] else: minus_amount += xCounts[experiment] for experiment in yCounts: if (experiment[2-classical_qubit_index] == '0'): i_amount += yCounts[experiment] else: minus_i_amount += yCounts[experiment] for experiment in zCounts: if (experiment[2-classical_qubit_index] == '0'): zero_amount += zCounts[experiment] else: one_amount += zCounts[experiment] df = {'0':zero_amount, '1':one_amount, '+':plus_amount, 'i':i_amount, '-':minus_amount,'-i':minus_i_amount} # df = {'zAxis':zero_amount+one_amount, # 'xAxis':plus_amount+ minus_amount, # 'yAxis':i_amount+minus_i_amount} resDf = resDf.append(df, ignore_index = True) classical_qubit_index+=1 resDf['+'] = resDf['+'].astype(int) resDf['i'] = resDf['i'].astype(int) resDf['-'] = resDf['-'].astype(int) resDf['-i'] = resDf['-i'].astype(int) resDf['0'] = resDf['0'].astype(int) resDf['1'] = resDf['1'].astype(int) # resDf['zAxis'] = resDf['zAxis'].astype(int) # resDf['xAxis'] = resDf['xAxis'].astype(int) # resDf['yAxis'] = resDf['yAxis'].astype(int) return resDf # Completed but more testing required ## assert that qubits are equal def assertEqual(backend, quantumCircuit1,quantumCircuit2, qubits_to_assert, measurements_to_make, experiments, alpha): ## needs to make at least 2 measurements, one for x axis, one for y axis ## realistically we need more for any statistical significance if (measurements_to_make < 2): raise ValueError("Must make at least 2 measurements") # makes sure qubits_to_assert is a list if (not isinstance(qubits_to_assert, list)): qubits_to_assert = [qubits_to_assert] measqc1 = measure_z(quantumCircuit1.copy(),qubits_to_assert) measqc2 = measure_z(quantumCircuit2.copy(),qubits_to_assert) # quantumCircuit1.measure() # quantumCircuit2.measure() job_sim = execute([measqc1, measqc2], backend, shots=100) result_sim = job_sim.result() counts1 = result_sim.get_counts(measqc1) print("c1:", counts1) counts2 = result_sim.get_counts(measqc2) print("c2:", counts2) dict3={k:[v] for k,v in counts2.items()} for k,v in counts1.items(): dict3[k]= dict3[k] + [v] if k in dict3 else [v] print(dict3) # measurements=[] for k,v in dict3.items(): if len(v) <= 1: raise(AssertionError("Measurements are not in the same states")) # measurements.append(v) q1Vals = [] q2Vals = [] # Get Df is a function I made to return a dataframe containing measurements for each each qubit across all axes and I use 5 such different measurements for my dataset for i in range(experiments): resDf1 = getDf(quantumCircuit1,qubits_to_assert,measurements_to_make,backend) # print("resdf 1:") # print(resDf1) q1Vals.extend(resDf1['1'].tolist()+resDf1['-'].tolist()+resDf1['-i'].tolist()) resDf2 = getDf(quantumCircuit2,qubits_to_assert,measurements_to_make,backend) # print("resdf 2: ") # print(resDf2) q2Vals.extend(resDf2['1'].tolist()+resDf2['-'].tolist()+resDf2['-i'].tolist()) # resDf1['1'] # print(resDf1['1'].tolist()) # q2Vals.extend([resDf1.at[1,'1'],resDf1.at[1,'-'],resDf1.at[1,'-i']]) # zStat_z, zPvalue = proportions_ztest(count=[resDf1['1'][0],resDf2['1'][1]], nobs=[measurements_to_make, measurements_to_make], alternative='two-sided') print("q1: ",q1Vals) print("q2: ",q2Vals) tTest, pValue = ttest_ind(q1Vals, q2Vals, alternative = 'two-sided') # Apply t test # zStat_z, zPvalue = proportions_ztest(count=[q1Vals,q2Vals], nobs=[measurements_to_make, measurements_to_make], alternative='two-sided') print("stat: ",tTest ,"pValue: ", pValue) if pValue > alpha: print("The two qubits are equal (fail to reject null hypothesis) ") else: print("There is a significant difference between the two qubits (reject null hypothesis)") qc = QuantumCircuit(2,2) backend = Aer.get_backend('aer_simulator') # qc.initialize([0, 1/np.sqrt(2), -1.j/np.sqrt(2), 0], qc.qubits) qc.x(0) qc.h(0) # qc.h(1) qc.cnot(0,1) # qc.p(0.5*2*math.pi/100, 1) # qc.h(1) # qc.p(10*2*math.pi/100, 0) # qc.p(20*2*math.pi/100, 1) qc.measure(0,0) qc.measure(1,1) # qc.measure_all() qc1 = QuantumCircuit(2,2) # qc1.x(1) qc1.h(0) qc1.cnot(0,1) # qc1.measure_all() qc1.measure(0,0) qc1.measure(1,1) qc3 = QuantumCircuit(2,2) qc3.x(0) qc3.x(1) qc4=qft_dagger(qc3,2) # from qiskit.quantum_info import Operator # Op1 = Operator(qc) # Op2 = Operator(qc1) # if Op1.equiv(Op2): # print("True") # else: # print("False") assertEqual(backend, qc1,qc2, [0,1], 30000, 30, 0.05) # assertEntangled(backend,circ,[1,0],3000,10,0.05) qc1 = QuantumCircuit(2,2) qc1.x(0) qc1.h(0) qc1.cnot(0,1) # qc1.h(1) print(qc1) # qc1.measure_z() qc1.measure(0,0) qc1.measure(1,1) # qc1.copy() job = execute(qc1,backend,shots=10000,memory=True) counts = job.result().get_counts() # counts2 = job.result().get_counts(c1) print(counts) # zQuantumCircuit1 = measure_z(qc1, qubits_to_assert) # zJob1 = execute(zQuantumCircuit1,backend,shots=10000,memory=True) # zCounts1=zJob1.result().get_counts() # print("z1", zCounts1) # xQuantumCircuit1 = measure_x(qc1, qubits_to_assert) # xJob1 = execute(xQuantumCircuit1,backend,shots=10000,memory=True) # xCounts1=xJob1.result().get_counts() # print("x1", xCounts1) # yQuantumCircuit1 = measure_y(qc1, qubits_to_assert) # yJob1 = execute(yQuantumCircuit1,backend,shots=10000,memory=True) # yCounts1=yJob1.result().get_counts() # print("y1", yCounts1) qc2 = QuantumCircuit(2,2) qc2.x(1) qc2.h(0) qc2.cnot(1,0) print(qc2) # qc2.h(0) qc2.measure(0,0) qc2.measure(1,1) job2 = execute(qc2,backend,shots=10000,memort=True) counts2 = job2.result().get_counts() print(counts2) # zQuantumCircuit2 = measure_z(qc2, qubits_to_assert) # zJob2 = execute(zQuantumCircuit2,backend,shots=10000,memory=True) # zCounts2=zJob2.result().get_counts() # print("z2",zCounts2) # xQuantumCircuit2 = measure_x(qc2, qubits_to_assert) # xJob2 = execute(xQuantumCircuit2,backend,shots=10000,memory=True) # xCounts2=xJob2.result().get_counts() # print("x2", xCounts2) # yQuantumCircuit2 = measure_y(qc2, qubits_to_assert) # yJob2 = execute(yQuantumCircuit2,backend,shots=10000,memory=True) # yCounts2=yJob2.result().get_counts() # print("y2", yCounts2) # tempD = { k: [counts[k],counts2[k]] for k in counts} # print(tempD) # from collections import defaultdict # dd = defaultdict(list) # dics=[counts,counts2] # for dic in dics: # for key,val in dic.items(): # dd[key].append(val) # print(dd) dict3={k:[v] for k,v in counts2.items()} for k,v in counts.items(): dict3[k]= dict3[k] + [v] if k in dict3 else [v] print(dict3) measurements=[] for k,v in dict3.items(): if len(v) <= 1: raise(AssertionError("There exists key(s) with just 1 measurement")) measurements.append(v) meas1 = measurements[0] meas2 = measurements[1] size = [10000,10000] # testStat,pValue1 = proportions_ztest(meas1,size,alternative='two-sided') # testStat,pValue2 = proportions_ztest(meas2,size,alternative='two-sided') zStat_z, pValue1 = proportions_ztest(count=[meas1[0],meas1[1]],nobs=size, alternative='two-sided') zStat_z, pValue2 = proportions_ztest(count=[meas2[0],meas2[1]],nobs=size, alternative='two-sided') print(pValue1) print(pValue2) if pValue1 > 0.05 and pValue2 > 0.05: print("The two qubits are equal (fail to reject null hypothesis) ") elif(pValue1<=0.05): print("There is a significant difference between the two qubits (reject null hypothesis)") elif (pValue2 <= 0.05): print("There is a significant difference between the two qubits (reject null hypothesis)") # qcList = [qc1,qc2] # index=0 # for i in qcList: # index+=1 # measurements_to_make=30000 # qubits_to_assert=[0,1] # measurements_to_make = measurements_to_make // 3 # yQuantumCircuit = measure_y(i.copy(), qubits_to_assert) # xQuantumCircuit = measure_x(i.copy(), qubits_to_assert) # zQuantumCircuit = measure_z(i, qubits_to_assert) # yJob = execute(yQuantumCircuit, backend, shots=measurements_to_make, memory=True) # yMemory = yJob.result().get_memory() # yCounts = yJob.result().get_counts() # print("y counts for", index, yCounts) # ## get x axis results # xJob = execute(xQuantumCircuit, backend, shots=measurements_to_make, memory=True) # xMemory = xJob.result().get_memory() # xCounts = xJob.result().get_counts() # print("x counts for", index,xCounts) # ## get z axis results # zJob = execute(zQuantumCircuit, backend, shots=measurements_to_make, memory=True) # zMemory = zJob.result().get_memory() # zCounts = zJob.result().get_counts() # print("z counts for", index,zCounts) # for i in range(5): # job_sim = execute([qc, qc1], backend_sim, shots=10000) # result_sim = job_sim.result() # counts1 = result_sim.get_counts(qc) # # print(counts1) # yo.extend(list(counts1.values())) # # print(yo) # counts2 = result_sim.get_counts(qc1) # print(counts2) # yo2.extend(list(counts2.values())) # # print(yo2) # # print(counts1, counts2) qc1 = QuantumCircuit(2,2) qc1.x(0) qc1.h(0) qc1.cnot(0,1) # qc1.h(1) print(qc1) qc1.measure(0,0) qc1.measure(1,1) qc2 = QuantumCircuit(2,2) # qc2.x(1) qc2.h(0) qc2.cnot(0,1) print(qc2) # qc2.h(0) qc2.measure(0,0) qc2.measure(1,1) yo=[] yo2=[] for i in range(2): job_sim = execute([qc1.copy(), qc2.copy()], backend, shots=10000) result_sim = job_sim.result() counts1 = result_sim.get_counts(qc1) print(i,"c1:", counts1) counts2 = result_sim.get_counts(qc2) print(i,"c2:",counts2) dict3={k:[v] for k,v in counts2.items()} for k,v in counts1.items(): dict3[k]= dict3[k] + [v] if k in dict3 else [v] print(dict3) measurements=[] for k,v in dict3.items(): if len(v) <= 1: raise(AssertionError("There exists key(s) with just 1 measurement")) measurements.append(v) # print("meas",measurements) resDf1 = getDf(qc1,[0,1],30000,backend) print("resdf1:") print(resDf1) resDf2 = getDf(qc2,[0,1],30000,backend) print("resdf2:") print(resDf2) yo.extend(resDf1['1'].tolist()+resDf1['-'].tolist()+resDf1['-i'].tolist()) yo2.extend(resDf2['1'].tolist()+resDf2['-'].tolist()+resDf2['-i'].tolist()) print("yo:",yo) print("yo2:",yo2) tTest, pValue = ttest_ind(yo, yo2, alternative = 'two-sided') # Apply t test print("stat: ",tTest, "pValue: ", pValue) if pValue > 0.05: print("The two qubits are equal (fail to reject null hypothesis) ") else: print("There is a significant difference between the two qubits (reject null hypothesis)") from qiskit.aqua.components.uncertainty_models import NormalDistribution q = QuantumRegister(2) c= ClassicalRegister(2) qc2 = QuantumCircuit(q,c) qc2.x(0) qc2.h(0) # qc2.h(0) qc2.cnot(0,1) normal = NormalDistribution(num_target_qubits=2,mu=0,sigma=1,low=-1,high=1) normal.build(qc2,q) print(qc2) # qc2.h(0) qc2.measure(0,0) qc2.measure(1,1) q1=[] q2=[] resDf2 = getDf(qc2,[0,1],10000,backend) print("resdf2:") print(resDf2) job = execute(qc2,backend,shots=10000) result = job.result() counts1 = result.get_counts() q1.extend(counts1.values()) print(q1) # q1 = np.array([488, 488, 520, 508, 509, 521, 495, 495, 519, 529, 497, 522, 472, 472, 501, 509, 511, 480, 516, 516, 491, 513, 487, 493]) # q2 = np.array([498, 502, 475, 477, 497, 524, 492, 508, 511, 490, 533, 491, 482, 518, 500, 513, 506, 515, 484, 516, 488, 503, 499, 497]) # q1= np.array([4897, 4897, 4992, 4998, 4940, 5092, 5014, 5014, 4939, 5047, 4970, 4938, 5015, 5015, 4962, 4956, 5057, 4993, 5086, 5086, 4961, 5069, 4939, 4979, 4984, 4984, 4943, 4965, 5010, 4956]) # q2= np.array([5098, 10000, 5075, 5044, 5087, 5081, 5013, 10000, 5011, 4948, 5042, 4944, 5043, 10000, 5002, 4980, 4991, 5015, 5003, 10000, 4933, 4961, 5037, 5024, 4997, 10000, 5044, 5019, 4989, 4966]) # q3 = np.array([483, 483, 508, 531, 469, 501, 517, 517, 492, 469, 531, 499, 492, 492, 486, 528, 505, 505, 508, 508, 514, 472, 495, 495, 501, 501, 498, 486, 522, 475, 499, 499, 502, 514, 478, 525, 513, 513, 508, 529, 487, 524, 487, 487, 492, 471, 513, 476]) # q4 = np.array([504, 496, 509, 484, 519, 501, 496, 504, 491, 516, 481, 499, 521, 479, 481, 507, 483, 507, 479, 521, 519, 493, 517, 493, 482, 518, 523, 506, 486, 502, 518, 482, 477, 494, 514, 498, 515, 485, 486, 468, 497, 488, 485, 515, 514, 532, 503, 512]) # q5 = np.array([5062, 5062, 4989, 4967, 4969, 5024, 4938, 4938, 5011, 5033, 5031, 4976, 5016, 5016, 4956, 4998, 5083, 5006, 4984, 4984, 5044, 5002, 4917, 4994, 4992, 4992, 4987, 4988, 4995, 5073, 5008, 5008, 5013, 5012, 5005, 4927, 5014, 5014, 4982, 5093, 5085, 4915, 4986, 4986, 5018, 4907, 4915, 5085, 5092, 5092, 5003, 4923, 5081, 5014, 4908, 4908, 4997, 5077, 4919, 4986]) # q6 = np.array([4994, 5006, 4907, 5012, 4982, 4988, 5006, 4994, 5093, 4988, 5018, 5012, 4988, 5012, 4988, 4965, 4962, 5033, 5012, 4988, 5012, 5035, 5038, 4967, 4979, 5021, 4976, 4978, 5042, 4976, 5021, 4979, 5024, 5022, 4958, 5024, 4801, 5199, 4953, 4971, 4968, 5083, 5199, 4801, 5047, 5029, 5032, 4917, 4961, 5039, 4986, 5018, 4961, 5030, 5039, 4961, 5014, 4982, 5039, 4970]) # #both normal q1=np.array([4902, 5098, 4908, 5042, 5013, 4993, 5098, 4902, 5092, 4958, 4987, 5007, 5078, 4922, 4956, 4979, 4984, 4890, 4922, 5078, 5044, 5021, 5016, 5110, 4912, 5088, 5023, 5068, 5101, 5039, 5088, 4912, 4977, 4932, 4899, 4961, 5028, 4972, 5046, 5020, 5085, 4969, 4972, 5028, 4954, 4980, 4915, 5031, 5015, 4985, 4996, 4939, 5003, 5002, 4985, 5015, 5004, 5061, 4997, 4998]) q2=np.array([5011, 4989, 4981, 5002, 4984, 5010, 4989, 5011, 5019, 4998, 5016, 4990, 5023, 4977, 4960, 5011, 4944, 4914, 4977, 5023, 5040, 4989, 5056, 5086, 4944, 5056, 4946, 5034, 4984, 5071, 5056, 4944, 5054, 4966, 5016, 4929, 4983, 5017, 5108, 5099, 5097, 5112, 5017, 4983, 4892, 4901, 4903, 4888, 4995, 5005, 4976, 5001, 4909, 5075, 5005, 4995, 5024, 4999, 5091, 4925]) # q9= np.array([5064, 5064, 4968, 5067, 5031, 5055, 4936, 4936, 5032, 4933, 4969, 4945, 4914, 4914, 5007, 5066, 5053, 5103, 5086, 5086, 4993, 4934, 4947, 4897, 4970, 4970, 5012, 5057, 4987, 5032, 5030, 5030, 4988, 4943, 5013, 4968, 5039, 5039, 4987, 5004, 4993, 5050, 4961, 4961, 5013, 4996, 5007, 4950, 5084, 5084, 5012, 5035, 4972, 4979, 4916, 4916, 4988, 4965, 5028, 5021]) # q10= np.array([4967, 10000, 4950, 4979, 4892, 4925, 5033, 0, 5050, 5021, 5108, 5075, 4953, 10000, 5069, 4994, 5009, 4912, 5047, 0, 4931, 5006, 4991, 5088, 5004, 10000, 5087, 4976, 4996, 4976, 4996, 0, 4913, 5024, 5004, 5024, 4995, 10000, 5054, 4979, 4950, 4984, 5005, 0, 4946, 5021, 5050, 5016, 5013, 10000, 4956, 4991, 5071, 5011, 4987, 0, 5044, 5009, 4929, 4989]) # q11=np.array([4958, 4958, 5037, 5058, 4987, 5007, 5050, 5050, 4975, 4978, 5006, 5026, 4940, 4940, 5047, 4957, 4970, 4964, 5069, 5069, 4977, 5057, 4919, 4960, 5021, 5021, 5030, 4942, 4917, 4971]) resDf=pd.DataFrame(columns=['q1','q2']) # df1=pd.DataFrame(columns=['q1']) df1={'q1':q3,'q2':q4} # df2=pd.DataFrame(columns=['q2']) # df2={'q2':[1,2,3,4,5]} resDf = resDf.append(df1,ignore_index=True) # resDf = resDf.append(df2,ignore_index=True) print(resDf) from sklearn.preprocessing import PowerTransformer # pt = PowerTransformer(method='yeo-johnson') # pt2 = PowerTransformer(method='yeo-johnson') # q11=q11.reshape(-1,1) # pt2.fit(q11) # transf2=pt2.transform(q11) from scipy.stats import rankdata n=len(q1) newQ1 = (rankdata(q1)/(n+1))*2 -1 newQ1 = np.arctanh(newQ1) # k2,p2 = normaltest(transf2) k2,p2 = normaltest(newQ1) print("lol:",p2) # interpret alpha = 0.05 if p2 > alpha: print('Sample looks Gaussian (fail to reject H0)') else: print('Sample does not look Gaussian (reject H0)') # q10=q10.reshape(-1,1) # pt.fit(q10) # transf1=pt.transform(q10) # n=len(q2) newQ2 = (rankdata(q2)/(n+1))*2 -1 newQ2 = np.arctanh(newQ2) k1,p1 = normaltest(newQ2) print("lol:",p1) if p1 > alpha: print('Sample looks Gaussian (fail to reject H0)') else: print('Sample does not look Gaussian (reject H0)') ttest,pVal = ttest_ind(newQ1,newQ2,alternative='two-sided') print("stat: ",tTest, "pValue: ", pValue) if pVal > 0.05: print("The two qubits are equal (fail to reject null hypothesis) ") else: print("There is a significant difference between the two qubits (reject null hypothesis)") # qc1.x(0)
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
PabloMartinezAngerosa
import numpy as np import networkx as nx import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble from qiskit.quantum_info import Statevector from qiskit.aqua.algorithms import NumPyEigensolver from qiskit.quantum_info import Pauli from qiskit.aqua.operators import op_converter from qiskit.aqua.operators import WeightedPauliOperator from qiskit.visualization import plot_histogram from qiskit.providers.aer.extensions.snapshot_statevector import * from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost from utils import mapeo_grafo from collections import defaultdict from operator import itemgetter from scipy.optimize import minimize import matplotlib.pyplot as plt LAMBDA = 10 SEED = 10 SHOTS = 10000 # returns the bit index for an alpha and j def bit(i_city, l_time, num_cities): return i_city * num_cities + l_time # e^(cZZ) def append_zz_term(qc, q_i, q_j, gamma, constant_term): qc.cx(q_i, q_j) qc.rz(2*gamma*constant_term,q_j) qc.cx(q_i, q_j) # e^(cZ) def append_z_term(qc, q_i, gamma, constant_term): qc.rz(2*gamma*constant_term, q_i) # e^(cX) def append_x_term(qc,qi,beta): qc.rx(-2*beta, qi) def get_not_edge_in(G): N = G.number_of_nodes() not_edge = [] for i in range(N): for j in range(N): if i != j: buffer_tupla = (i,j) in_edges = False for edge_i, edge_j in G.edges(): if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)): in_edges = True if in_edges == False: not_edge.append((i, j)) return not_edge def get_classical_simplified_z_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # z term # z_classic_term = [0] * N**2 # first term for l in range(N): for i in range(N): z_il_index = bit(i, l, N) z_classic_term[z_il_index] += -1 * _lambda # second term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_jl z_jl_index = bit(j, l, N) z_classic_term[z_jl_index] += _lambda / 2 # third term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_ij z_ij_index = bit(i, j, N) z_classic_term[z_ij_index] += _lambda / 2 # fourth term not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 4 # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) z_classic_term[z_jlplus_index] += _lambda / 4 # fifthy term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) z_classic_term[z_il_index] += weight_ij / 4 # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) z_classic_term[z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) z_classic_term[z_il_index] += weight_ji / 4 # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) z_classic_term[z_jlplus_index] += weight_ji / 4 return z_classic_term def tsp_obj_2(x, G,_lambda): # obtenemos el valor evaluado en f(x_1, x_2,... x_n) not_edge = get_not_edge_in(G) N = G.number_of_nodes() tsp_cost=0 #Distancia weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # x_il x_il_index = bit(edge_i, l, N) # x_jlplus l_plus = (l+1) % N x_jlplus_index = bit(edge_j, l_plus, N) tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij # add order term because G.edges() do not include order tuples # # x_i'l x_il_index = bit(edge_j, l, N) # x_j'lplus x_jlplus_index = bit(edge_i, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji #Constraint 1 for l in range(N): penal1 = 1 for i in range(N): x_il_index = bit(i, l, N) penal1 -= int(x[x_il_index]) tsp_cost += _lambda * penal1**2 #Contstraint 2 for i in range(N): penal2 = 1 for l in range(N): x_il_index = bit(i, l, N) penal2 -= int(x[x_il_index]) tsp_cost += _lambda*penal2**2 #Constraint 3 for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # x_il x_il_index = bit(i, l, N) # x_j(l+1) l_plus = (l+1) % N x_jlplus_index = bit(j, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda return tsp_cost def get_classical_simplified_zz_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # zz term # zz_classic_term = [[0] * N**2 for i in range(N**2) ] # first term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) # z_jl z_jl_index = bit(j, l, N) zz_classic_term[z_il_index][z_jl_index] += _lambda / 2 # second term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) # z_ij z_ij_index = bit(i, j, N) zz_classic_term[z_il_index][z_ij_index] += _lambda / 2 # third term not_edge = get_not_edge_in(G) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4 # fourth term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4 return zz_classic_term def get_classical_simplified_hamiltonian(G, _lambda): # z term # z_classic_term = get_classical_simplified_z_term(G, _lambda) # zz term # zz_classic_term = get_classical_simplified_zz_term(G, _lambda) return z_classic_term, zz_classic_term def get_cost_circuit(G, gamma, _lambda): N = G.number_of_nodes() N_square = N**2 qc = QuantumCircuit(N_square,N_square) z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda) # z term for i in range(N_square): if z_classic_term[i] != 0: append_z_term(qc, i, gamma, z_classic_term[i]) # zz term for i in range(N_square): for j in range(N_square): if zz_classic_term[i][j] != 0: append_zz_term(qc, i, j, gamma, zz_classic_term[i][j]) return qc def get_mixer_operator(G,beta): N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) for n in range(N**2): append_x_term(qc, n, beta) return qc def get_QAOA_circuit(G, beta, gamma, _lambda): assert(len(beta)==len(gamma)) N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) # init min mix state qc.h(range(N**2)) p = len(beta) for i in range(p): qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda)) qc = qc.compose(get_mixer_operator(G, beta[i])) qc.barrier(range(N**2)) qc.snapshot_statevector("final_state") qc.measure(range(N**2),range(N**2)) return qc def invert_counts(counts): return {k[::-1] :v for k,v in counts.items()} # Sample expectation value def compute_tsp_energy_2(counts, G): energy = 0 get_counts = 0 total_counts = 0 for meas, meas_count in counts.items(): obj_for_meas = tsp_obj_2(meas, G, LAMBDA) energy += obj_for_meas*meas_count total_counts += meas_count mean = energy/total_counts return mean def get_black_box_objective_2(G,p): backend = Aer.get_backend('qasm_simulator') sim = Aer.get_backend('aer_simulator') # function f costo def f(theta): beta = theta[:p] gamma = theta[p:] # Anzats qc = get_QAOA_circuit(G, beta, gamma, LAMBDA) result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result() final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0] state_vector = Statevector(final_state_vector) probabilities = state_vector.probabilities() probabilities_states = invert_counts(state_vector.probabilities_dict()) expected_value = 0 for state,probability in probabilities_states.items(): cost = tsp_obj_2(state, G, LAMBDA) expected_value += cost*probability counts = result.get_counts() mean = compute_tsp_energy_2(invert_counts(counts),G) return mean return f def crear_grafo(cantidad_ciudades): pesos, conexiones = None, None mejor_camino = None while not mejor_camino: pesos, conexiones = rand_graph(cantidad_ciudades) mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False) G = mapeo_grafo(conexiones, pesos) return G, mejor_costo, mejor_camino def run_QAOA(p,ciudades, grafo): if grafo == None: G, mejor_costo, mejor_camino = crear_grafo(ciudades) print("Mejor Costo") print(mejor_costo) print("Mejor Camino") print(mejor_camino) print("Bordes del grafo") print(G.edges()) print("Nodos") print(G.nodes()) print("Pesos") labels = nx.get_edge_attributes(G,'weight') print(labels) else: G = grafo intial_random = [] # beta, mixer Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,np.pi)) # gamma, cost Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,2*np.pi)) init_point = np.array(intial_random) obj = get_black_box_objective_2(G,p) res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True}) print(res_sample) if __name__ == '__main__': # Run QAOA parametros: profundidad p, numero d ciudades, run_QAOA(5, 3, None)
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
import unittest import hypothesis.strategies as st from hypothesis import given, settings, note import matplotlib.pyplot as plt import numpy as np import math from qiskit import QuantumCircuit, Aer, transpile, assemble, execute from qiskit.visualization import plot_histogram from qiskit.circuit.library import CCXGate, CXGate, CSwapGate, HGate, SwapGate, CPhaseGate from math import gcd from numpy.random import randint import pandas as pd from fractions import Fraction from math import gcd # greatest common divisor # Specify variables n_count = 8 # number of counting qubits a = 7 N = 15 def c_amod15(a, power): """Controlled multiplication by a mod 15""" if a not in [2,7,8,11,13]: raise ValueError("'a' must be 2,7,8,11 or 13") U = QuantumCircuit(4) for iteration in range(power): if a in [2,13]: U.swap(0,1) U.swap(1,2) U.swap(2,3) if a in [7,8]: U.swap(2,3) U.swap(1,2) U.swap(0,1) if a == 11: U.swap(1,3) U.swap(0,2) if a in [7,11,13]: for q in range(4): U.x(q) U = U.to_gate() U.name = "%i^%i mod 15" % (a, power) c_U = U.control() return c_U def qft_dagger(n): """n-qubit QFTdagger the first n qubits in circ""" qc = QuantumCircuit(n) # Don't forget the Swaps! for qubit in range(n//2): qc.swap(qubit, n-qubit-1) for j in range(n): for m in range(j): qc.cp(-np.pi/float(2**(j-m)), m, j) qc.h(j) qc.name = "QFT†" return qc def qpe_amod15(a): n_count = 8 qc = QuantumCircuit(4+n_count, n_count) for q in range(n_count): qc.h(q) # Initialize counting qubits in state |+> qc.x(3+n_count) # And auxiliary register in state |1> for q in range(n_count): # Do controlled-U operations qc.append(c_amod15(a, 2**q), [q] + [i+n_count for i in range(4)]) qc.append(qft_dagger(n_count), range(n_count)) # Do inverse-QFT qc.measure(range(n_count), range(n_count)) # Simulate Results aer_sim = Aer.get_backend('aer_simulator') # Setting memory=True below allows us to see a list of each sequential reading backend = Aer.get_backend('aer_simulator') job = execute(qc, backend, shots=1, memory=True) readings = job.result().get_memory() phase = int(readings[0],2)/(2**n_count) print(qc) return phase phase = qpe_amod15(a) # Phase = s/r Fraction(phase).limit_denominator(15) frac = Fraction(phase).limit_denominator(15) s, r = frac.numerator, frac.denominator print(r) guesses = [gcd(a**(r//2)-1, N), gcd(a**(r//2)+1, N)] print(guesses) def find_factor(coprime): a = coprime attempt = 0 factors = [] for i in range(100): attempt += 1 #print("\nAttempt %i:" % attempt) phase = qpe_amod15(a) # Phase = s/r frac = Fraction(phase).limit_denominator(N) # Denominator should (hopefully!) tell us r r = frac.denominator #print("Result: r = %i" % r) if phase != 0: # Guesses for factors are gcd(x^{r/2} ±1 , 15) guesses = [gcd(a**(r//2)-1, N), gcd(a**(r//2)+1, N)] #print("Guessed Factors: %i and %i" % (guesses[0], guesses[1])) for guess in guesses: if guess not in [1,N] and (N % guess) == 0: # Check to see if guess is a factor # print("*** Non-trivial factor found: %i ***" % guess) factors += [guess] return factors find_factor(7) @st.composite def draw_coprime_int(draw): return draw(st.sampled_from([2,7,8,11,13])) @st.composite def draw_non_coprime_int(draw): return draw(st.sampled_from([1,3,4,5,6,9,10,12,14,15])) # @given(draw_coprime_int(), st.integers(min_value=0, max_value=7)) # @settings(deadline=None) # def test_modular_exponentiation_uses_CSWap_CCX_CX_gates(coprime_int, power): # note("coprime integer %i and power %i"%(coprime_int, power)) # circuit = (c_amod15(coprime_int, power).definition) # note(circuit) # for gate in circuit: # note(type(gate[0])) # assert(isinstance(gate[0], CSwapGate) # or isinstance(gate[0], CCXGate) # or isinstance(gate[0], CXGate)) @given(draw_non_coprime_int(), st.integers(min_value=0, max_value=7)) @settings(deadline=None) def test_modular_exponentiation_non_coprime_int_throws_exception(non_coprime_int, power): note("non coprime integer %i and power %i"%(non_coprime_int, power)) # we expect an assertion to be thrown if a non coprime int is supplied # ussing assertRaises() is challenging in jupyter notebook so we just use a try block try: c_amod15(non_coprime_int, power) except ValueError: assert(True) else: assert(False) # @given(st.integers(min_value=1, max_value=25)) # @settings(deadline=None) # def test_qft_dagger_uses_H_Swap_CPhase_gates(qft_dagger_length): # note("qft dagger circuit length %i"%(qft_dagger_length)) # circuit = qft_dagger(qft_dagger_length) # note(circuit) # for gate in circuit: # note(type(gate[0])) # assert(isinstance(gate[0], HGate) # or isinstance(gate[0], SwapGate) # or isinstance(gate[0], CPhaseGate)) @given(draw_coprime_int()) @settings(deadline=None) def test_qpe_amod_15_phase_between_0_and_1(coprime_integer): note("coprime integer %i"%coprime_integer) phase = qpe_amod15(coprime_integer) note("phase %i"%phase) assert(phase >= 0 and phase <= 1) @given(draw_non_coprime_int()) @settings(deadline=None) def test_qpe_amod_15_non_coprime_int_throws_exception(non_coprime_int): note("non coprime integer %i"%(non_coprime_int)) # we expect an assertion to be thrown if a non coprime int is supplied # ussing assertRaises() is challenging in jupyter notebook so we just use a try block try: qpe_amod15(non_coprime_int) except ValueError: assert(True) else: assert(False) @given(draw_coprime_int()) @settings(deadline=None) def test_find_factor_is_3_or_5(coprime_integer): note("coprime integer %i"%coprime_integer) guesses = find_factor(coprime_integer) note(guesses) assert(len(guesses)>0) for guess in guesses: note("guess %i"%guess) assert guess in [3,5] @given(draw_non_coprime_int()) @settings(deadline=None) def test_find_factor_non_coprime_int_throws_exception(non_coprime_int): note("non coprime integer %i"%(non_coprime_int)) # we expect an assertion to be thrown if a non coprime int is supplied # ussing assertRaises() is challenging in jupyter notebook so we just use a try block try: find_factor(non_coprime_int) except ValueError: assert(True) else: assert(False) @st.composite def draw_pair_of_ints(draw): drawnInt = draw(st.integers(min_value=0, max_value=6)) randIncrease = 7 - drawnInt drawnLarger = draw(st.integers(min_value=drawnInt+1, max_value=drawnInt+randIncrease)) return(drawnInt, drawnLarger) @st.composite def draw_larger_pair_of_ints(draw): drawnInt = draw(st.integers(min_value=1, max_value=24)) randIncrease = 25 - drawnInt drawnLarger = draw(st.integers(min_value=drawnInt+1, max_value=drawnInt+randIncrease)) return(drawnInt, drawnLarger) # @given(draw_coprime_int(), draw_pair_of_ints()) # @settings(deadline=None) # def test_modular_exponentiation_circuit_longer_with_larger_power(coprime_int, powers): # smaller, larger = powers # note("coprime integer %i and powers %i, %i"%(coprime_int, smaller, larger)) # circuit = (c_amod15(coprime_int, smaller).definition) # circuitLarger = (c_amod15(coprime_int, larger).definition) # note("smaller circuit length = %i, larger circuit length = %i"%(len(circuit.data), len(circuitLarger.data))) # assert(len(circuit.data) < len(circuitLarger.data)) # @given(draw_coprime_int(), st.integers(min_value=0, max_value=7)) # @settings(deadline=None) # def test_modular_exponentiation_circuit_same_length_with_equal_power(coprime_int, power): # note("coprime integer %i and power %i"%(coprime_int, power)) # circuit = (c_amod15(coprime_int, power).definition) # circuitEqual = (c_amod15(coprime_int, power).definition) # note("circuit 1 length = %i, circuit 2 length = %i"%(len(circuit.data), len(circuitEqual.data))) # assert(len(circuit.data) == len(circuitEqual.data)) # @given(draw_larger_pair_of_ints()) # @settings(deadline=None) # def test_qft_dagger_circuit_is_longer_with_higher_length_parameter(qft_lengths): # length1, length2 = qft_lengths # note("smaller length %i and larger length %i"%(length1, length2)) # circuit = qft_dagger(length1) # circuitLarger = qft_dagger(length2) # note("smaller circuit length = %i, larger circuit length = %i"%(len(circuit.data), len(circuitLarger.data))) # assert(len(circuit.data) < len(circuitLarger.data)) # @given(st.integers(min_value=1, max_value=25)) # @settings(deadline=None) # def test_qft_dagger_circuit_same_length_with_length_parameter(qft_length): # note("length %i"%(qft_length)) # circuit = qft_dagger(qft_length) # circuitEqual = qft_dagger(qft_length) # note("circuit 1 length = %i, circuit 2 length = %i"%(len(circuit.data), len(circuitEqual.data))) # assert(len(circuit.data) == len(circuitEqual.data)) if __name__ == '__main__': # test_modular_exponentiation_uses_CSWap_CCX_CX_gates() test_modular_exponentiation_non_coprime_int_throws_exception() # test_qft_dagger_uses_H_Swap_CPhase_gates() test_qpe_amod_15_phase_between_0_and_1() test_qpe_amod_15_non_coprime_int_throws_exception() test_find_factor_is_3_or_5() test_find_factor_non_coprime_int_throws_exception() # test_modular_exponentiation_circuit_longer_with_larger_power() # test_modular_exponentiation_circuit_same_length_with_equal_power() # test_qft_dagger_circuit_is_longer_with_higher_length_parameter() # test_qft_dagger_circuit_same_length_with_length_parameter()
https://github.com/UST-QuAntiL/qiskit-service
UST-QuAntiL
# ****************************************************************************** # Copyright (c) 2020-2021 University of Stuttgart # # See the NOTICE file(s) distributed with this work for additional # information regarding copyright ownership. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License 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. # ****************************************************************************** import unittest import os from app.config import basedir from app import app, db import qiskit import base64 from qiskit.circuit.random import random_circuit class TranspileTestCase(unittest.TestCase): def setUp(self): # setup environment variables for testing app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///" + os.path.join(basedir, 'test.db') self.client = app.test_client() db.create_all() def tearDown(self): db.session.remove() db.drop_all() def test_version(self): response = self.client.get('/qiskit-service/api/v1.0/version') self.assertEqual(response.status_code, 200) json_data = response.get_json() self.assertTrue("version" in json_data) self.assertEqual(json_data['version'], "1.0") def test_transpile_hadamard_simulator_url(self): # prepare the request request = { 'impl-url': "https://raw.githubusercontent.com/PlanQK/qiskit-service/master/test/data/hadamard.py", 'impl-language': 'Qiskit', 'qpu-name': "ibmq_qasm_simulator", 'input-params': {}, 'token': os.environ["QISKIT_TOKEN"] } # send the request response = self.client.post('/qiskit-service/api/v1.0/transpile', json=request) self.assertEqual(response.status_code, 200) json_data = response.get_json() self.assertIn("width", json_data) self.assertIn("depth", json_data) self.assertIsNotNone(json_data['depth']) self.assertIsNotNone(json_data['width']) self.assertIn('transpiled-qasm', json_data) self.assertIn("total-number-of-operations", json_data) self.assertIn("number-of-multi-qubit-gates", json_data) self.assertIn("multi-qubit-gate-depth", json_data) self.assertIsNotNone(json_data["total-number-of-operations"]) self.assertEqual(json_data["number-of-multi-qubit-gates"], 0) self.assertEqual(json_data["multi-qubit-gate-depth"], 0) self.assertIsNotNone(json_data.get('transpiled-qasm')) r = self.client.post('/qiskit-service/api/v1.0/execute', json=request) self.assertEqual(r.status_code, 202) print(r.headers.get("Location")) def test_transpile_hadamard_simulator_file(self): # prepare the request file_path = (os.path.dirname(__file__)) + '/data/hadamard.py' with open(file_path, 'rb') as f: impl_data = base64.b64encode(f.read()).decode() request = { 'impl-data': impl_data, 'impl-language': 'Qiskit', 'qpu-name': "ibmq_qasm_simulator", 'input-params': {}, 'token': os.environ["QISKIT_TOKEN"] } # send the request response = self.client.post('/qiskit-service/api/v1.0/transpile', json=request) self.assertEqual(response.status_code, 200) json_data = response.get_json() self.assertIn("width", json_data) self.assertIn("depth", json_data) self.assertIsNotNone(json_data['depth']) self.assertIsNotNone(json_data['width']) self.assertIn('transpiled-qasm', json_data) self.assertIn("total-number-of-operations", json_data) self.assertIn("number-of-multi-qubit-gates", json_data) self.assertIn("multi-qubit-gate-depth", json_data) self.assertIsNotNone(json_data["total-number-of-operations"]) self.assertIsNotNone(json_data["number-of-multi-qubit-gates"]) self.assertIsNotNone(json_data["multi-qubit-gate-depth"]) self.assertIsNotNone(json_data.get('transpiled-qasm')) r = self.client.post('/qiskit-service/api/v1.0/execute', json=request) self.assertEqual(r.status_code, 202) print(r.headers.get("Location")) def test_transpile_circuit_sim_file(self): # prepare the request file_path = (os.path.dirname(__file__))+'/data/pattern0-3_1_2nCliffs10seed2.qasm' with open(file_path, 'rb') as f: impl_data = base64.b64encode(f.read()).decode() request = { 'impl-data': impl_data, 'impl-language': 'openqasm', 'qpu-name': "ibmq_qasm_simulator", 'input-params': {}, 'token': os.environ.get("QISKIT_TOKEN", "") } # send the request response = self.client.post('/qiskit-service/api/v1.0/transpile', json=request) self.assertEqual(response.status_code, 200) json_data = response.get_json() self.assertIn("width", json_data) self.assertIn("depth", json_data) self.assertIsNotNone(json_data['depth']) self.assertIsNotNone(json_data['width']) self.assertIn('transpiled-qasm', json_data) self.assertIn("total-number-of-operations", json_data) self.assertIn("number-of-multi-qubit-gates", json_data) self.assertIn("multi-qubit-gate-depth", json_data) self.assertIsNotNone(json_data["total-number-of-operations"]) self.assertIsNotNone(json_data["number-of-multi-qubit-gates"]) self.assertIsNotNone(json_data["multi-qubit-gate-depth"]) self.assertIsNotNone(json_data.get('transpiled-qasm')) r = self.client.post('/qiskit-service/api/v1.0/execute', json=request) self.assertEqual(r.status_code, 202) print(r.headers.get("Location")) def test_transpile_shor_sim_url_qasm(self): # prepare the request request = { 'impl-url': 'https://quantum-circuit.com/api/get/circuit/KzG7MxH6hpBpM9pCt?format=qasm', 'impl-language': 'OpenQASM', 'qpu-name': "ibmq_qasm_simulator", 'input-params': {}, 'token': os.environ["QISKIT_TOKEN"] } # send the request response = self.client.post('/qiskit-service/api/v1.0/transpile', json=request) self.assertEqual(response.status_code, 200) json_data = response.get_json() self.assertIn("width", json_data) self.assertIn("depth", json_data) self.assertIsNotNone(json_data['depth']) self.assertIsNotNone(json_data['width']) self.assertIn('transpiled-qasm', json_data) self.assertIn("total-number-of-operations", json_data) self.assertIn("number-of-multi-qubit-gates", json_data) self.assertIn("multi-qubit-gate-depth", json_data) self.assertIsNotNone(json_data["total-number-of-operations"]) self.assertIsNotNone(json_data["number-of-multi-qubit-gates"]) self.assertIsNotNone(json_data["multi-qubit-gate-depth"]) self.assertIsNotNone(json_data.get('transpiled-qasm')) r = self.client.post('/qiskit-service/api/v1.0/execute', json=request) self.assertEqual(r.status_code, 202) print(r.headers.get("Location")) """ def test_transpile_file_qasm_aws(self): circuit = random_circuit(5, 3, seed=42) circuit = circuit.qasm() impl_data = base64.b64encode(circuit.encode()).decode() # prepare the request request = { 'impl-data': impl_data, 'impl-language': 'OpenQASM', 'provider': 'aws', 'qpu-name': "Aria 2", 'input-params': {}, 'aws_access_key_id': os.environ.get("QISKIT_AWS_TOKEN", ""), 'aws_secret_access_key': os.environ.get("QISKIT_AWS_SECRET", "") } # send the request response = self.client.post('/qiskit-service/api/v1.0/transpile', json=request) self.assertEqual(response.status_code, 200) json_data = response.get_json() self.assertIn("width", json_data) self.assertIn("depth", json_data) self.assertIsNotNone(json_data['depth']) self.assertIsNotNone(json_data['width']) self.assertIn('transpiled-qasm', json_data) self.assertIn("total-number-of-operations", json_data) self.assertIn("number-of-multi-qubit-gates", json_data) self.assertIn("multi-qubit-gate-depth", json_data) self.assertIsNotNone(json_data["total-number-of-operations"]) self.assertIsNotNone(json_data["number-of-multi-qubit-gates"]) self.assertIsNotNone(json_data["multi-qubit-gate-depth"]) self.assertIsNotNone(json_data.get('transpiled-qasm')) """ def test_transpile_circuit_sim_file_qasm(self): # prepare the request file_path = (os.path.dirname(__file__))+'/data/pattern0-3_1_2nCliffs10seed2.qasm' with open(file_path, 'rb') as f: impl_data = base64.b64encode(f.read()).decode() request = { 'impl-data': impl_data, 'impl-language': 'OpenQASM', 'qpu-name': "ibmq_qasm_simulator", 'input-params': {}, 'token': os.environ["QISKIT_TOKEN"] } # send the request response = self.client.post('/qiskit-service/api/v1.0/transpile', json=request) self.assertEqual(response.status_code, 200) json_data = response.get_json() self.assertIn("width", json_data) self.assertIn("depth", json_data) self.assertIsNotNone(json_data['depth']) self.assertIsNotNone(json_data['width']) self.assertIn('transpiled-qasm', json_data) self.assertIn("total-number-of-operations", json_data) self.assertIn("number-of-multi-qubit-gates", json_data) self.assertIn("multi-qubit-gate-depth", json_data) self.assertIsNotNone(json_data["total-number-of-operations"]) self.assertIsNotNone(json_data["number-of-multi-qubit-gates"]) self.assertIsNotNone(json_data["multi-qubit-gate-depth"]) self.assertIsNotNone(json_data.get('transpiled-qasm')) r = self.client.post('/qiskit-service/api/v1.0/execute', json=request) self.assertEqual(r.status_code, 202) print(r.headers.get("Location")) # def test_transpile_shor_simulator(self): # # this test is deprecated, as Shor is no longer natively supported by newer versions of Qiskit # # prepare the request # request = { # 'impl-url': "https://raw.githubusercontent.com/PlanQK/qiskit-service/master/test/data/shor_general_qiskit.py", # 'qpu-name': "ibmq_qasm_simulator", # 'input-params': { # 'N': { # 'rawValue': "9", # 'type': 'Integer' # } # }, # 'token': os.environ["QISKIT_TOKEN"] # } # # # send the request # response = self.client.post('/qiskit-service/api/v1.0/transpile', # json=request) # # self.assertEqual(response.status_code, 200) # json_data = response.get_json() # self.assertIn("width", json_data) # self.assertIn("depth", json_data) # self.assertIsNotNone(json_data['depth']) # self.assertIsNotNone(json_data['width']) # self.assertIn('transpiled-qasm', json_data) # self.assertIn("total-number-of-operations", json_data) # self.assertIn("number-of-multi-qubit-gates", json_data) # self.assertIn("multi-qubit-gate-depth", json_data) # self.assertIsNotNone(json_data["total-number-of-operations"]) # self.assertIsNotNone(json_data["number-of-multi-qubit-gates"]) # self.assertIsNotNone(json_data["multi-qubit-gate-depth"]) # self.assertIsNotNone(json_data.get('transpiled-qasm')) # # r = self.client.post('/qiskit-service/api/v1.0/execute', json=request) # self.assertEqual(r.status_code, 202) # print(r.headers.get("Location")) # def test_transpile_shor_nairobi(self): # # this test is deprecated, as Shor is no longer natively supported by newer versions of Qiskit # # prepare the request # request = { # 'impl-url': "https://raw.githubusercontent.com/PlanQK/qiskit-service/master/test/data/shor_general_qiskit.py", # 'qpu-name': "ibm_nairobi", # 'input-params': { # 'N': { # 'rawValue': "9", # 'type': 'Integer' # } # }, # 'token': os.environ["QISKIT_TOKEN"] # } # # # send the request # response = self.client.post('/qiskit-service/api/v1.0/transpile', # json=request) # # self.assertEqual(response.status_code, 200) # json_data = response.get_json() # self.assertIn("error", json_data) # self.assertIn("too many qubits", json_data['error']) @unittest.skip("PlanQK access token required") def test_transpile_shor_simulator_planqk_url(self): # prepare the request request = { 'impl-url': "https://platform.planqk.de/qc-catalog/algorithms/e7413acf-c25e-4de8-ab78-75bfc836a839/implementations/1207510f-9007-48b3-93b8-ea51359c0ced/files/1d827208-1976-487e-819b-64df6e990bf3/content", 'impl-language': 'Qiskit', 'qpu-name': "ibmq_qasm_simulator", 'input-params': {}, 'token': os.environ["QISKIT_TOKEN"], "bearer-token": os.environ["BEARER_TOKEN"] } # send the request response = self.client.post('/qiskit-service/api/v1.0/transpile', json=request) self.assertEqual(response.status_code, 200) json_data = response.get_json() self.assertIn("width", json_data) self.assertIn("depth", json_data) self.assertIsNotNone(json_data['depth']) self.assertIsNotNone(json_data['width']) self.assertIn('transpiled-qasm', json_data) self.assertIn("total-number-of-operations", json_data) self.assertIn("number-of-multi-qubit-gates", json_data) self.assertIn("multi-qubit-gate-depth", json_data) self.assertIsNotNone(json_data["total-number-of-operations"]) self.assertIsNotNone(json_data["number-of-multi-qubit-gates"]) self.assertIsNotNone(json_data["multi-qubit-gate-depth"]) self.assertIsNotNone(json_data.get('transpiled-qasm')) r = self.client.post('/qiskit-service/api/v1.0/execute', json=request) self.assertEqual(r.status_code, 202) print(r.headers.get("Location")) def test_batch_execution(self): # Build a thousand circuits. circs = [] for _ in range(1000): circs.append(random_circuit(num_qubits=5, depth=4, measure=True).qasm()) request = { 'impl-qasm': circs, 'impl-language': 'Qiskit', 'qpu-name': "ibmq_qasm_simulator", 'input-params': {}, 'token': os.environ["QISKIT_TOKEN"] } # send the request r = self.client.post('/qiskit-service/api/v1.0/execute', json=request) self.assertEqual(r.status_code, 202) json_data = r.get_json() self.assertIsNotNone("result", json_data) print(r.headers.get("Location")) @unittest.skip("Perth QPU currently not available") def test_noisy_simulator(self): token = os.environ["QISKIT_TOKEN"] request = { 'impl-qasm': "OPENQASM 2.0; include \"qelib1.inc\";qreg q[4];creg c[4];x q[0]; x q[2];barrier q;h q[0];cu1(pi/2) q[1],q[0];h q[1];cu1(pi/4) q[2],q[0];cu1(pi/2) q[2],q[1];h q[2];cu1(pi/8) q[3],q[0];cu1(pi/4) q[3],q[1];cu1(pi/2) q[3],q[2];h q[3];measure q -> c;", 'impl-language': 'Qiskit', 'qpu-name': "aer_qasm_simulator", 'input-params': {}, "noise_model": "ibm_perth", 'token': token } response = self.client.post('/qiskit-service/api/v1.0/execute', json=request) self.assertEqual(response.status_code, 202) print(response.get_json()) @unittest.skip("Perth QPU currently not available") def test_noisy_de_simulator(self): token = os.environ["QISKIT_TOKEN"] request = { 'impl-qasm': "OPENQASM 2.0; include \"qelib1.inc\";qreg q[4];creg c[4];x q[0]; x q[2];barrier q;h q[0];cu1(pi/2) q[1],q[0];h q[1];cu1(pi/4) q[2],q[0];cu1(pi/2) q[2],q[1];h q[2];cu1(pi/8) q[3],q[0];cu1(pi/4) q[3],q[1];cu1(pi/2) q[3],q[2];h q[3];measure q -> c;", 'impl-language': 'Qiskit', 'qpu-name': "aer_qasm_simulator", 'input-params': {}, "noise_model": "ibm_perth", "only-measurement-errors": "True", 'token': token } response = self.client.post('/qiskit-service/api/v1.0/execute', json=request) self.assertEqual(response.status_code, 202) print(response.get_json()) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.pulse_v2 import draw, IQXSimple from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() qc = transpile(qc, FakeBoeblingen(), layout_method='trivial') sched = schedule(qc, FakeBoeblingen()) draw(sched, style=IQXSimple(), backend=FakeBoeblingen())
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, execute from qiskit.visualization import plot_error_map from qiskit.providers.fake_provider import FakeVigoV2 backend = FakeVigoV2() plot_error_map(backend)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2024. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Estimator Pub class """ from __future__ import annotations from numbers import Real from collections.abc import Mapping from typing import Tuple, Union import numpy as np from qiskit import QuantumCircuit from .bindings_array import BindingsArray, BindingsArrayLike from .observables_array import ObservablesArray, ObservablesArrayLike from .shape import ShapedMixin # Public API classes __all__ = ["EstimatorPubLike"] class EstimatorPub(ShapedMixin): """Primitive Unified Bloc for any Estimator primitive. An estimator pub is essentially a tuple ``(circuit, observables, parameter_values, precision)``. If precision is provided this should be used for the target precision of an estimator, if ``precision=None`` the estimator will determine the target precision. """ __slots__ = ("_circuit", "_observables", "_parameter_values", "_precision", "_shape") def __init__( self, circuit: QuantumCircuit, observables: ObservablesArray, parameter_values: BindingsArray | None = None, precision: float | None = None, validate: bool = True, ): """Initialize an estimator pub. Args: circuit: A quantum circuit. observables: An observables array. parameter_values: A bindings array, if the circuit is parametric. precision: An optional target precision for expectation value estimates. validate: Whether to validate arguments during initialization. Raises: ValueError: If the ``observables`` and ``parameter_values`` are not broadcastable, that is, if their shapes, when right-aligned, do not agree or equal 1. """ super().__init__() self._circuit = circuit self._observables = observables self._parameter_values = parameter_values or BindingsArray() self._precision = precision # for ShapedMixin try: # _shape has to be defined to properly be Shaped, so we can't put it in validation self._shape = np.broadcast_shapes(self.observables.shape, self.parameter_values.shape) except ValueError as ex: raise ValueError( f"The observables shape {self.observables.shape} and the " f"parameter values shape {self.parameter_values.shape} are not broadcastable." ) from ex if validate: self.validate() @property def circuit(self) -> QuantumCircuit: """A quantum circuit.""" return self._circuit @property def observables(self) -> ObservablesArray: """An observables array.""" return self._observables @property def parameter_values(self) -> BindingsArray: """A bindings array.""" return self._parameter_values @property def precision(self) -> float | None: """The target precision for expectation value estimates (optional).""" return self._precision @classmethod def coerce(cls, pub: EstimatorPubLike, precision: float | None = None) -> EstimatorPub: """Coerce :class:`~.EstimatorPubLike` into :class:`~.EstimatorPub`. Args: pub: A compatible object for coercion. precision: an optional default precision to use if not already specified by the pub-like object. Returns: An estimator pub. """ # Validate precision kwarg if provided if precision is not None: if not isinstance(precision, Real): raise TypeError(f"precision must be a real number, not {type(precision)}.") if precision < 0: raise ValueError("precision must be non-negative") if isinstance(pub, EstimatorPub): if pub.precision is None and precision is not None: return cls( circuit=pub.circuit, observables=pub.observables, parameter_values=pub.parameter_values, precision=precision, validate=False, # Assume Pub is already validated ) return pub if isinstance(pub, QuantumCircuit): raise ValueError( f"An invalid Estimator pub-like was given ({type(pub)}). " "If you want to run a single pub, you need to wrap it with `[]` like " "`estimator.run([(circuit, observables, param_values)])` " "instead of `estimator.run((circuit, observables, param_values))`." ) if len(pub) not in [2, 3, 4]: raise ValueError( f"The length of pub must be 2, 3 or 4, but length {len(pub)} is given." ) circuit = pub[0] observables = ObservablesArray.coerce(pub[1]) if len(pub) > 2 and pub[2] is not None: values = pub[2] if not isinstance(values, (BindingsArray, Mapping)): values = {tuple(circuit.parameters): values} parameter_values = BindingsArray.coerce(values) else: parameter_values = None if len(pub) > 3 and pub[3] is not None: precision = pub[3] return cls( circuit=circuit, observables=observables, parameter_values=parameter_values, precision=precision, validate=True, ) def validate(self): """Validate the pub.""" if not isinstance(self.circuit, QuantumCircuit): raise TypeError("circuit must be QuantumCircuit.") self.observables.validate() self.parameter_values.validate() if self.precision is not None: if not isinstance(self.precision, Real): raise TypeError(f"precision must be a real number, not {type(self.precision)}.") if self.precision < 0: raise ValueError("precision must be non-negative.") # Cross validate circuits and observables for i, observable in np.ndenumerate(self.observables): num_qubits = len(next(iter(observable))) if self.circuit.num_qubits != num_qubits: raise ValueError( f"The number of qubits of the circuit ({self.circuit.num_qubits}) does " f"not match the number of qubits of the {i}-th observable ({num_qubits})." ) # Cross validate circuits and parameter_values num_parameters = self.parameter_values.num_parameters if num_parameters != self.circuit.num_parameters: raise ValueError( f"The number of values ({num_parameters}) does not match " f"the number of parameters ({self.circuit.num_parameters}) for the circuit." ) EstimatorPubLike = Union[ EstimatorPub, Tuple[QuantumCircuit, ObservablesArrayLike], Tuple[QuantumCircuit, ObservablesArrayLike, BindingsArrayLike], Tuple[QuantumCircuit, ObservablesArrayLike, BindingsArrayLike, Real], ] """A Pub (Primitive Unified Bloc) for an Estimator primitive. A fully specified estimator pub is a tuple ``(circuit, observables, parameter_values, precision)``. If precision is provided this should be used for the target precision of an estimator, if ``precision=None`` the estimator will determine the target precision. .. note:: An Estimator Pub can also be initialized in the following formats which will be converted to the full Pub tuple: * ``(circuit, observables)`` * ``(circuit, observables, parameter_values)`` """
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
PabloMartinezAngerosa
import numpy as np import networkx as nx import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble from qiskit.quantum_info import Statevector from qiskit.aqua.algorithms import NumPyEigensolver from qiskit.quantum_info import Pauli from qiskit.aqua.operators import op_converter from qiskit.aqua.operators import WeightedPauliOperator from qiskit.visualization import plot_histogram from qiskit.providers.aer.extensions.snapshot_statevector import * from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost from utils import mapeo_grafo from collections import defaultdict from operator import itemgetter from scipy.optimize import minimize import matplotlib.pyplot as plt LAMBDA = 10 SEED = 10 SHOTS = 10000 # returns the bit index for an alpha and j def bit(i_city, l_time, num_cities): return i_city * num_cities + l_time # e^(cZZ) def append_zz_term(qc, q_i, q_j, gamma, constant_term): qc.cx(q_i, q_j) qc.rz(2*gamma*constant_term,q_j) qc.cx(q_i, q_j) # e^(cZ) def append_z_term(qc, q_i, gamma, constant_term): qc.rz(2*gamma*constant_term, q_i) # e^(cX) def append_x_term(qc,qi,beta): qc.rx(-2*beta, qi) def get_not_edge_in(G): N = G.number_of_nodes() not_edge = [] for i in range(N): for j in range(N): if i != j: buffer_tupla = (i,j) in_edges = False for edge_i, edge_j in G.edges(): if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)): in_edges = True if in_edges == False: not_edge.append((i, j)) return not_edge def get_classical_simplified_z_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # z term # z_classic_term = [0] * N**2 # first term for l in range(N): for i in range(N): z_il_index = bit(i, l, N) z_classic_term[z_il_index] += -1 * _lambda # second term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_jl z_jl_index = bit(j, l, N) z_classic_term[z_jl_index] += _lambda / 2 # third term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_ij z_ij_index = bit(i, j, N) z_classic_term[z_ij_index] += _lambda / 2 # fourth term not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 4 # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) z_classic_term[z_jlplus_index] += _lambda / 4 # fifthy term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) z_classic_term[z_il_index] += weight_ij / 4 # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) z_classic_term[z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) z_classic_term[z_il_index] += weight_ji / 4 # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) z_classic_term[z_jlplus_index] += weight_ji / 4 return z_classic_term def tsp_obj_2(x, G,_lambda): # obtenemos el valor evaluado en f(x_1, x_2,... x_n) not_edge = get_not_edge_in(G) N = G.number_of_nodes() tsp_cost=0 #Distancia weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # x_il x_il_index = bit(edge_i, l, N) # x_jlplus l_plus = (l+1) % N x_jlplus_index = bit(edge_j, l_plus, N) tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij # add order term because G.edges() do not include order tuples # # x_i'l x_il_index = bit(edge_j, l, N) # x_j'lplus x_jlplus_index = bit(edge_i, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji #Constraint 1 for l in range(N): penal1 = 1 for i in range(N): x_il_index = bit(i, l, N) penal1 -= int(x[x_il_index]) tsp_cost += _lambda * penal1**2 #Contstraint 2 for i in range(N): penal2 = 1 for l in range(N): x_il_index = bit(i, l, N) penal2 -= int(x[x_il_index]) tsp_cost += _lambda*penal2**2 #Constraint 3 for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # x_il x_il_index = bit(i, l, N) # x_j(l+1) l_plus = (l+1) % N x_jlplus_index = bit(j, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda return tsp_cost def get_classical_simplified_zz_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # zz term # zz_classic_term = [[0] * N**2 for i in range(N**2) ] # first term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) # z_jl z_jl_index = bit(j, l, N) zz_classic_term[z_il_index][z_jl_index] += _lambda / 2 # second term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) # z_ij z_ij_index = bit(i, j, N) zz_classic_term[z_il_index][z_ij_index] += _lambda / 2 # third term not_edge = get_not_edge_in(G) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4 # fourth term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4 return zz_classic_term def get_classical_simplified_hamiltonian(G, _lambda): # z term # z_classic_term = get_classical_simplified_z_term(G, _lambda) # zz term # zz_classic_term = get_classical_simplified_zz_term(G, _lambda) return z_classic_term, zz_classic_term def get_cost_circuit(G, gamma, _lambda): N = G.number_of_nodes() N_square = N**2 qc = QuantumCircuit(N_square,N_square) z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda) # z term for i in range(N_square): if z_classic_term[i] != 0: append_z_term(qc, i, gamma, z_classic_term[i]) # zz term for i in range(N_square): for j in range(N_square): if zz_classic_term[i][j] != 0: append_zz_term(qc, i, j, gamma, zz_classic_term[i][j]) return qc def get_mixer_operator(G,beta): N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) for n in range(N**2): append_x_term(qc, n, beta) return qc def get_QAOA_circuit(G, beta, gamma, _lambda): assert(len(beta)==len(gamma)) N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) # init min mix state qc.h(range(N**2)) p = len(beta) for i in range(p): qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda)) qc = qc.compose(get_mixer_operator(G, beta[i])) qc.barrier(range(N**2)) qc.snapshot_statevector("final_state") qc.measure(range(N**2),range(N**2)) return qc def invert_counts(counts): return {k[::-1] :v for k,v in counts.items()} # Sample expectation value def compute_tsp_energy_2(counts, G): energy = 0 get_counts = 0 total_counts = 0 for meas, meas_count in counts.items(): obj_for_meas = tsp_obj_2(meas, G, LAMBDA) energy += obj_for_meas*meas_count total_counts += meas_count mean = energy/total_counts return mean def get_black_box_objective_2(G,p): backend = Aer.get_backend('qasm_simulator') sim = Aer.get_backend('aer_simulator') # function f costo def f(theta): beta = theta[:p] gamma = theta[p:] # Anzats qc = get_QAOA_circuit(G, beta, gamma, LAMBDA) result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result() final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0] state_vector = Statevector(final_state_vector) probabilities = state_vector.probabilities() probabilities_states = invert_counts(state_vector.probabilities_dict()) expected_value = 0 for state,probability in probabilities_states.items(): cost = tsp_obj_2(state, G, LAMBDA) expected_value += cost*probability counts = result.get_counts() mean = compute_tsp_energy_2(invert_counts(counts),G) return mean return f def crear_grafo(cantidad_ciudades): pesos, conexiones = None, None mejor_camino = None while not mejor_camino: pesos, conexiones = rand_graph(cantidad_ciudades) mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False) G = mapeo_grafo(conexiones, pesos) return G, mejor_costo, mejor_camino def run_QAOA(p,ciudades, grafo): if grafo == None: G, mejor_costo, mejor_camino = crear_grafo(ciudades) print("Mejor Costo") print(mejor_costo) print("Mejor Camino") print(mejor_camino) print("Bordes del grafo") print(G.edges()) print("Nodos") print(G.nodes()) print("Pesos") labels = nx.get_edge_attributes(G,'weight') print(labels) else: G = grafo intial_random = [] # beta, mixer Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,np.pi)) # gamma, cost Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,2*np.pi)) init_point = np.array(intial_random) obj = get_black_box_objective_2(G,p) res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True}) print(res_sample) if __name__ == '__main__': # Run QAOA parametros: profundidad p, numero d ciudades, run_QAOA(5, 3, None)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit.library import QFT def create_qpe_circuit(theta, num_qubits): '''Creates a QPE circuit given theta and num_qubits.''' # Step 1: Create a circuit with two quantum registers and one classical register. first = QuantumRegister(size=num_qubits, name='first') # the first register for phase estimation second = QuantumRegister(size=1, name='second') # the second register for storing eigenvector |psi> classical = ClassicalRegister(size=num_qubits, name='readout') # classical register for readout qpe_circuit = QuantumCircuit(first, second, classical) # Step 2: Initialize the qubits. # All qubits are initialized in |0> by default, no extra code is needed to initialize the first register. qpe_circuit.x(second) # Initialize the second register with state |psi>, which is |1> in this example. # Step 3: Create superposition in the first register. qpe_circuit.barrier() # Add barriers to separate each step of the algorithm for better visualization. qpe_circuit.h(first) # Step 4: Apply a controlled-U^(2^j) black box. qpe_circuit.barrier() for j in range(num_qubits): qpe_circuit.cp(theta*2*np.pi*(2**j), j, num_qubits) # Theta doesn't contain the 2 pi factor. # Step 5: Apply an inverse QFT to the first register. qpe_circuit.barrier() qpe_circuit.compose(QFT(num_qubits, inverse=True), inplace=True) # Step 6: Measure the first register. qpe_circuit.barrier() qpe_circuit.measure(first, classical) return qpe_circuit num_qubits = 4 qpe_circuit_fixed_phase = create_qpe_circuit(1/2, num_qubits) # Create a QPE circuit with fixed theta=1/2. qpe_circuit_fixed_phase.draw('mpl') from qiskit.circuit import Parameter theta = Parameter('theta') # Create a parameter `theta` whose values can be assigned later. qpe_circuit_parameterized = create_qpe_circuit(theta, num_qubits) qpe_circuit_parameterized.draw('mpl') number_of_phases = 21 phases = np.linspace(0, 2, number_of_phases) individual_phases = [[ph] for ph in phases] # Phases need to be expressed as a list of lists. from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService() backend = "ibmq_qasm_simulator" # use the simulator from qiskit_ibm_runtime import Sampler, Session with Session(service=service, backend=backend): results = Sampler().run( [qpe_circuit_parameterized]*len(individual_phases), parameter_values=individual_phases ).result() from qiskit.tools.visualization import plot_histogram idx = 6 plot_histogram(results.quasi_dists[idx].binary_probabilities(), legend=[f'$\\theta$={phases[idx]:.3f}']) def most_likely_bitstring(results_dict): '''Finds the most likely outcome bit string from a result dictionary.''' return max(results_dict, key=results_dict.get) def find_neighbors(bitstring): '''Finds the neighbors of a bit string. Example: For bit string '1010', this function returns ('1001', '1011') ''' if bitstring == len(bitstring)*'0': neighbor_left = len(bitstring)*'1' else: neighbor_left = format((int(bitstring,2)-1), '0%sb'%len(bitstring)) if bitstring == len(bitstring)*'1': neighbor_right = len(bitstring)*'0' else: neighbor_right = format((int(bitstring,2)+1), '0%sb'%len(bitstring)) return (neighbor_left, neighbor_right) def estimate_phase(results_dict): '''Estimates the phase from a result dictionary of a QPE circuit.''' # Find the most likely outcome bit string N1 and its neighbors. num_1_key = most_likely_bitstring(results_dict) neighbor_left, neighbor_right = find_neighbors(num_1_key) # Get probabilities of N1 and its neighbors. num_1_prob = results_dict.get(num_1_key) neighbor_left_prob = results_dict.get(neighbor_left) neighbor_right_prob = results_dict.get(neighbor_right) # Find the second most likely outcome N2 and its probability P2 among the neighbors. if neighbor_left_prob is None: # neighbor_left doesn't exist if neighbor_right_prob is None: # both neighbors don't exist, N2 is N1 num_2_key = num_1_key num_2_prob = num_1_prob else: # If only neighbor_left doesn't exist, N2 is neighbor_right. num_2_key = neighbor_right num_2_prob = neighbor_right_prob elif neighbor_right_prob is None: # If only neighbor_right doesn't exist, N2 is neighbor_left. num_2_key = neighbor_left num_2_prob = neighbor_left_prob elif neighbor_left_prob > neighbor_right_prob: # Both neighbors exist and neighbor_left has higher probability, so N2 is neighbor_left. num_2_key = neighbor_left num_2_prob = neighbor_left_prob else: # Both neighbors exist and neighbor_right has higher probability, so N2 is neighor_right. num_2_key = neighbor_right num_2_prob = neighbor_right_prob # Calculate the estimated phases for N1 and N2. num_qubits = len(num_1_key) num_1_phase = (int(num_1_key, 2) / 2**num_qubits) num_2_phase = (int(num_2_key, 2) / 2**num_qubits) # Calculate the weighted average phase from N1 and N2. phase_estimated = (num_1_phase * num_1_prob + num_2_phase * num_2_prob) / (num_1_prob + num_2_prob) return phase_estimated qpe_solutions = [] for idx, result_dict in enumerate(results.quasi_dists): qpe_solutions.append(estimate_phase(result_dict.binary_probabilities())) ideal_solutions = np.append( phases[:(number_of_phases-1)//2], # first period np.subtract(phases[(number_of_phases-1)//2:-1], 1) # second period ) ideal_solutions = np.append(ideal_solutions, np.subtract(phases[-1], 2)) # starting point of the third period import matplotlib.pyplot as plt fig = plt.figure(figsize=(10, 6)) plt.plot(phases, ideal_solutions, '--', label='Ideal solutions') plt.plot(phases, qpe_solutions, 'o', label='QPE solutions') plt.title('Quantum Phase Estimation Algorithm') plt.xlabel('Input Phase') plt.ylabel('Output Phase') plt.legend() import qiskit_ibm_runtime qiskit_ibm_runtime.version.get_version_info() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/GabrielPontolillo/QiskitPBT
GabrielPontolillo
# class that inherits from property based test from qiskit import QuantumCircuit from QiskitPBT.property import Property from QiskitPBT.input_generators import RandomState from QiskitPBT.case_studies.quantum_teleportation.quantum_teleportation import quantum_teleportation class Inq0EqualOutq2(Property): # specify the inputs that are to be generated def get_input_generators(self): state = RandomState(1) return [state] # specify the preconditions for the test def preconditions(self, q0): return True # specify the operations to be performed on the input def operations(self, q0): qc = QuantumCircuit(3, 3) qc.initialize(q0, [0]) qt = quantum_teleportation() # stitch qc and quantum_teleportation together qc = qc.compose(qt) # initialise qubit to compare to: qc2 = QuantumCircuit(1, 1) qc2.initialize(q0, [0]) self.statistical_analysis.assert_equal(self, 2, qc, 0, qc2)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse dc = pulse.DriveChannel d0, d1, d2, d3, d4 = dc(0), dc(1), dc(2), dc(3), dc(4) with pulse.build(name='pulse_programming_in') as pulse_prog: pulse.play([1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], d0) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d1) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], d2) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d3) pulse.play([1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0], d4) pulse_prog.draw()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit top = QuantumCircuit(1) top.x(0); bottom = QuantumCircuit(2) bottom.cry(0.2, 0, 1); tensored = bottom.tensor(top) tensored.draw('mpl')
https://github.com/JohnBurke4/qaoa_testing_framework
JohnBurke4
from Image_Reader import ImageReader from DCT_Classic import DCT import Quantum_Subroutines import os import Image_Compression import cv2 import matplotlib.pyplot as plt import numpy as np from qiskit import QuantumCircuit, Aer, transpile from qiskit_aer.backends.aerbackend import AerBackend from qiskit.providers.fake_provider import FakeSydneyV2 from qiskit_aer import AerSimulator import csv N = 256 dct = DCT.normal1D(N) path = os.path.abspath("StateCompression/images/camera.png") paths = ["camera", "peppers", "bird"] paths = [paths[0]] # image = ImageReader.chopUpImage(image, N)['pieces'][0] basis_gates = ['u1', 'u2', 'u3', 'cx', 'id'] basis_gates = ['u3', 'cx', 'id'] rC = 2 cC = 1 comp = [(2, 1), (2, 2), (4, 2), (4, 4), (8, 4), (8, 8), (16, 8), (16, 16)]#, (32, 16), (32, 32)] comp.reverse() # comp = [comp[1]] # comp = [(8, 8)] # open the file in the write mode f = open('compression_results_5.csv', 'w') # create the csv writer writer = csv.writer(f) headings = ["image", "compression", "psnr", "depth", "gates", "inner_product"] writer.writerow(headings) # write a row to the csv file for im in paths: image = ImageReader.getImage(os.path.abspath("StateCompression/images/" + im + ".png"), N) # print(image) imageNorm = np.linalg.norm(image) normalizedImage = image / imageNorm for c in comp: # print(c) rC = c[0] cC = c[1] compressedImage = Image_Compression.naiveDCTCompression(image, N, rC, cC) norm = np.linalg.norm(compressedImage) normData = compressedImage / norm remade = DCT.remakeImage(normData, dct) inner = np.inner(remade.flatten(), normalizedImage.flatten()) # print("C:", c, "F:", inner**2) nQubits = int(np.log2(N*N)) aQubits = int(nQubits/2)-1 # aQubits = 0 totalQubits = nQubits + aQubits qc = QuantumCircuit(totalQubits) statePrep = Quantum_Subroutines.buildCompressedState(compressedImage, rC, cC) # qc.initialize(normalizedImage.flatten(), range(0, nQubits)) qc.append(statePrep, range(0, nQubits)) qdct = Quantum_Subroutines.QDCT(int(nQubits/2), mctMode="v-chain") qc.append(qdct.inverse(), list(range(0, int(nQubits/2))) + list(range(nQubits, totalQubits))) qc.append(qdct.inverse(), list(range(int(nQubits/2), int(nQubits))) + list(range(nQubits, totalQubits))) sim = Aer.get_backend('aer_simulator') # print("Before") circ = transpile(qc, sim, basis_gates=basis_gates) # circ = transpile(qc, sim) # print("After") depth = circ.depth() gates = sum(dict(circ.count_ops()).values()) circ.save_statevector() result = sim.run(circ).result() out_vector = result.get_statevector().data[0:N*N] imageData = out_vector.real.reshape((N, N)) # imageData = imageData quantumImage = (imageData * imageNorm) # print(quantumImage) psnr = cv2.PSNR(image.astype(int), quantumImage.astype(int)) print("C:", c, "P:", psnr, "D:", depth, "G:", gates, "I:", inner**2) # print("C:", c, "D:", depth, "G:", gates) # row = [im, c[0] * c[1], psnr, depth, gates, inner**2] # # writer.writerow(row) # # plt.title("PSNR: " + str(psnr)) # # plt.imshow(quantumImage, cmap='gray') # # plt.show() # print(image1) # print(image2) # ImageReader.displayImage(image1.astype(np.uint8), "PSNR: " + str(int(psnr))) # ImageReader.displayImage(image2, "Quantum Compressed") # block = np.array([[144, 99, 94, 90], # [148, 99, 94, 90], # [148, 99, 94, 90], # [148, 99, 94, 90]]).transpose() # # print(block) # dct2 = DCT.normal1D(4) # convert = DCT.convertImage2D(block, dct2).astype(int) # print(convert) # convert[0,1] = -12 # convert[1,1] = -15 # convert[2,1] = -4 # convert[3,1] = 4 # print(convert) # remade = DCT.remakeImage(convert, dct2).astype(int) # print(remade) # np.set_printoptions(precision=2) # np.set_printoptions(suppress=True) # convert2 = DCT.convertImage2D(remade, dct2) # convert2[:,2] = 0 # convert2[:,3] = 0 # print(np.linalg.norm(convert2))
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/sathayen/qiskit-docker
sathayen
# Creating quantum circuits from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit.tools.visualization import circuit_drawer qr = QuantumRegister(5) cr = ClassicalRegister(5) qc = QuantumCircuit(qr, cr) def swap_gate(q_swap, q1, q2): q_swap.cx(q1, q2) q_swap.cx(q2, q1) q_swap.cx(q1, q2) #q_swap.measure(qr2, cr2) #circuit_drawer(q_swap) swap_gate(qc, qr[3], qr[4]) qc.measure(qr, cr) circuit_drawer(qc)
https://github.com/minnukota381/Quantum-Computing-Qiskit
minnukota381
from qiskit import * from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram from numpy import pi # Create a quantum circuit with a single qubit # The default initial state of qubit will be |0> or [1,0] qc = QuantumCircuit(1) #Apply the s gate and sdg gate to obtain identity qc.s(0) qc.sdg(0) #Draw the circuit # qc.draw() qc.draw('mpl') #Get the backend for the circuit (simulator or realtime system) backend = Aer.get_backend('statevector_simulator') #execute the circuit using the backend out = execute(qc,backend).result().get_statevector() #plot the result as a bloch sphere visualization plot_bloch_multivector(out) # visualize the output as an animation visualize_transition(qc) #execute the circuit and get the plain result out = execute(qc,backend).result() #getting the count of the result counts = out.get_counts() #plotting the histogram plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.mappers.second_quantization import LogarithmicMapper mapper = LogarithmicMapper(2) from qiskit_nature.second_q.mappers import LogarithmicMapper mapper = LogarithmicMapper(2) from qiskit_nature.second_q.mappers import LogarithmicMapper mapper = LogarithmicMapper(padding=2) from qiskit_nature.circuit.library import HartreeFock from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.mappers.second_quantization import JordanWignerMapper converter = QubitConverter(JordanWignerMapper()) init_state = HartreeFock(num_spin_orbitals=6, num_particles=(2, 1), qubit_converter=converter) print(init_state.draw()) from qiskit_nature.second_q.circuit.library import HartreeFock from qiskit_nature.second_q.mappers import JordanWignerMapper, QubitConverter converter = QubitConverter(JordanWignerMapper()) init_state = HartreeFock(num_spatial_orbitals=3, num_particles=(2, 1), qubit_converter=converter) print(init_state.draw()) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import BasicAer, transpile, QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.h(0) qc.measure(0, 0) qc.x(0).c_if(cr, 0) qc.measure(0, 0) qc.draw('mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, execute from qiskit.providers.fake_provider import FakeVigoV2 from qiskit.visualization import plot_gate_map backend = FakeVigoV2() plot_gate_map(backend)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_optimization import QuadraticProgram from qiskit_optimization.translators import from_docplex_mp # Make a Docplex model from docplex.mp.model import Model mdl = Model("docplex model") x = mdl.binary_var("x") y = mdl.integer_var(lb=-1, ub=5, name="y") mdl.minimize(x + 2 * y) mdl.add_constraint(x - y == 3) mdl.add_constraint((x + y) * (x - y) <= 1) print(mdl.export_as_lp_string()) # load from a Docplex model mod = from_docplex_mp(mdl) print(type(mod)) print() print(mod.prettyprint()) # make an empty problem mod = QuadraticProgram("my problem") print(mod.prettyprint()) # Add variables mod.binary_var(name="x") mod.integer_var(name="y", lowerbound=-1, upperbound=5) mod.continuous_var(name="z", lowerbound=-1, upperbound=5) print(mod.prettyprint()) # Add objective function using dictionaries mod.minimize(constant=3, linear={"x": 1}, quadratic={("x", "y"): 2, ("z", "z"): -1}) print(mod.prettyprint()) # Add objective function using lists/arrays mod.minimize(constant=3, linear=[1, 0, 0], quadratic=[[0, 1, 0], [1, 0, 0], [0, 0, -1]]) print(mod.prettyprint()) print("constant:\t\t\t", mod.objective.constant) print("linear dict:\t\t\t", mod.objective.linear.to_dict()) print("linear array:\t\t\t", mod.objective.linear.to_array()) print("linear array as sparse matrix:\n", mod.objective.linear.coefficients, "\n") print("quadratic dict w/ index:\t", mod.objective.quadratic.to_dict()) print("quadratic dict w/ name:\t\t", mod.objective.quadratic.to_dict(use_name=True)) print( "symmetric quadratic dict w/ name:\t", mod.objective.quadratic.to_dict(use_name=True, symmetric=True), ) print("quadratic matrix:\n", mod.objective.quadratic.to_array(), "\n") print("symmetric quadratic matrix:\n", mod.objective.quadratic.to_array(symmetric=True), "\n") print("quadratic matrix as sparse matrix:\n", mod.objective.quadratic.coefficients) # Add linear constraints mod.linear_constraint(linear={"x": 1, "y": 2}, sense="==", rhs=3, name="lin_eq") mod.linear_constraint(linear={"x": 1, "y": 2}, sense="<=", rhs=3, name="lin_leq") mod.linear_constraint(linear={"x": 1, "y": 2}, sense=">=", rhs=3, name="lin_geq") print(mod.prettyprint()) # Add quadratic constraints mod.quadratic_constraint( linear={"x": 1, "y": 1}, quadratic={("x", "x"): 1, ("y", "z"): -1}, sense="==", rhs=1, name="quad_eq", ) mod.quadratic_constraint( linear={"x": 1, "y": 1}, quadratic={("x", "x"): 1, ("y", "z"): -1}, sense="<=", rhs=1, name="quad_leq", ) mod.quadratic_constraint( linear={"x": 1, "y": 1}, quadratic={("x", "x"): 1, ("y", "z"): -1}, sense=">=", rhs=1, name="quad_geq", ) print(mod.prettyprint()) lin_geq = mod.get_linear_constraint("lin_geq") print("lin_geq:", lin_geq.linear.to_dict(use_name=True), lin_geq.sense, lin_geq.rhs) quad_geq = mod.get_quadratic_constraint("quad_geq") print( "quad_geq:", quad_geq.linear.to_dict(use_name=True), quad_geq.quadratic.to_dict(use_name=True), quad_geq.sense, lin_geq.rhs, ) # Remove constraints mod.remove_linear_constraint("lin_eq") mod.remove_quadratic_constraint("quad_leq") print(mod.prettyprint()) sub = mod.substitute_variables(constants={"x": 0}, variables={"y": ("z", -1)}) print(sub.prettyprint()) sub = mod.substitute_variables(constants={"x": -1}) print(sub.status) from qiskit_optimization import QiskitOptimizationError try: sub = mod.substitute_variables(constants={"x": -1}, variables={"y": ("x", 1)}) except QiskitOptimizationError as e: print("Error: {}".format(e)) mod = QuadraticProgram() mod.binary_var(name="e") mod.binary_var(name="f") mod.continuous_var(name="g") mod.minimize(linear=[1, 2, 3]) print(mod.export_as_lp_string()) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/JackHidary/quantumcomputingbook
JackHidary
from qiskit import QuantumCircuit, Aer, execute, IBMQ from qiskit.utils import QuantumInstance import numpy as np from qiskit.algorithms import Shor IBMQ.enable_account('ENTER API TOKEN HERE') # Enter your API token here provider = IBMQ.get_provider(hub='ibm-q') backend = Aer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1000) my_shor = Shor(quantum_instance) result_dict = my_shor.factor(15) print(result_dict)
https://github.com/mareksubocz/QRBM-qiskit
mareksubocz
import numpy as np import matplotlib.pyplot as plt import torch from torch.autograd import Function from torchvision import datasets, transforms import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import qiskit from qiskit.visualization import * # Concentrating on the first 100 samples n_samples = 100 X_train = datasets.MNIST(root='./data', train=True, download=True, transform=transforms.Compose([transforms.ToTensor()])) # Leaving only labels 0 and 1 idx = np.append(np.where(X_train.targets == 0)[0][:n_samples], np.where(X_train.targets == 1)[0][:n_samples] ) # idx = np.append(idx, # np.where(X_train.targets == 2)[0][:n_samples] # ) # idx = np.append(idx, # np.where(X_train.targets == 3)[0][:n_samples] # ) print(idx) X_train.data = X_train.data[idx] X_train.targets = X_train.targets[idx] train_loader = torch.utils.data.DataLoader(X_train, batch_size=1, shuffle=True) n_samples_show = 6 data_iter = iter(train_loader) fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) while n_samples_show > 0: images, targets = data_iter.__next__() axes[n_samples_show - 1].imshow(images[0].numpy().squeeze(), cmap='gray') axes[n_samples_show - 1].set_xticks([]) axes[n_samples_show - 1].set_yticks([]) axes[n_samples_show - 1].set_title("Labeled: {}".format(targets.item())) n_samples_show -= 1 n_samples = 50 X_test = datasets.MNIST(root='./data', train=False, download=True, transform=transforms.Compose([transforms.ToTensor()])) idx = np.append(np.where(X_test.targets == 0)[0][:n_samples], np.where(X_test.targets == 1)[0][:n_samples]) # idx = np.append(idx, # np.where(X_test.targets == 2)[0][:n_samples] # ) # idx = np.append(idx, # np.where(X_test.targets == 3)[0][:n_samples] # ) X_test.data = X_test.data[idx] X_test.targets = X_test.targets[idx] test_loader = torch.utils.data.DataLoader(X_test, batch_size=1, shuffle=True) def exctract_single_qubit_measurment(dict_of_counts, qubit_range): # print(dict_of_counts) # print(len(list(dict_of_counts.keys())[0])) num_qubits = len(list(dict_of_counts.keys())[0]) result = np.zeros(len(qubit_range)) result = np.zeros(num_qubits) # print(result) for el in dict_of_counts: for i in range(num_qubits): # print("i", i) # print("el[i]", el[i]) if i in qubit_range and el[i] == '1': result[i] += dict_of_counts[el] # print(result) # print(result[qubit_range]) return result[qubit_range] class QuantumCircuit: """ This class provides a simple interface for interaction with the quantum circuit """ def __init__(self, n_qubits, backend, shots): # --- Circuit definition --- self._circuit = qiskit.QuantumCircuit(n_qubits) self.n_qubits = n_qubits all_qubits = [i for i in range(n_qubits)] self.theta = qiskit.circuit.Parameter('theta') self._circuit.h(all_qubits) self._circuit.barrier() self._circuit.ry(self.theta, all_qubits) self._circuit.measure_all() # --------------------------- self.backend = backend self.shots = shots def run(self, thetas): job = qiskit.execute(self._circuit, self.backend, shots = self.shots, parameter_binds = [{self.theta: theta} for theta in thetas]) result = job.result().get_counts(self._circuit) counts = np.array(list(result.values())) states = np.array(list(result.keys())).astype(float) # Compute probabilities for each state probabilities = counts / self.shots # Get state expectation expectation = np.sum(states * probabilities) # print("states: ", states) # print("probabilities: ", probabilities) new_probabilities = exctract_single_qubit_measurment(result, list(range(self.n_qubits)))/self.shots # print("new_probabilities: ", new_probabilities) # new_expectation = np.sum(states * new_probabilities) # print("old expectation", np.array([expectation])) return new_probabilities # return np.array([expectation]) simulator = qiskit.Aer.get_backend('qasm_simulator') circuit = QuantumCircuit(2, simulator, 100) print('Expected value for rotation pi {}'.format(circuit.run([np.pi])[0])) circuit._circuit.draw() class HybridFunction(Function): """ Hybrid quantum - classical function definition """ @staticmethod def forward(ctx, input, quantum_circuit, shift): # print("FORWARD BEGIN") # print("input: ", input) """ Forward pass computation """ ctx.shift = shift ctx.quantum_circuit = quantum_circuit expectation_z = ctx.quantum_circuit.run(input[0].tolist()) # print("expectation_z: ", expectation_z) result = torch.tensor([expectation_z]) # print("result", result) ctx.save_for_backward(input, result) # print("FORWARD END") return result @staticmethod def backward(ctx, grad_output): # print("BACKWARD BEGIN") # print("Grad_output: ", grad_output) """ Backward pass computation """ input, expectation_z = ctx.saved_tensors # print("input_list: ", input.tolist()) input_list = np.array(input.tolist()) shift_right = input_list + np.ones(input_list.shape) * ctx.shift shift_left = input_list - np.ones(input_list.shape) * ctx.shift gradients = [] for i in range(len(input_list)): expectation_right = ctx.quantum_circuit.run(shift_right[i]) expectation_left = ctx.quantum_circuit.run(shift_left[i]) gradient = expectation_right - expectation_left gradients.append(gradient) # print("HALO") gradients = np.array([gradients]).T # print("gradients: ", gradients) # print("BACKWARD END") return torch.tensor([gradients]).float() * grad_output.float(), None, None class Hybrid(nn.Module): """ Hybrid quantum - classical layer definition """ def __init__(self, backend, shots, shift): super(Hybrid, self).__init__() self.quantum_circuit = QuantumCircuit(2, backend, shots) self.shift = shift def forward(self, input): return HybridFunction.apply(input, self.quantum_circuit, self.shift) class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 32, kernel_size=5) self.conv2 = nn.Conv2d(32, 64, kernel_size=5) self.dropout = nn.Dropout2d() self.fc1 = nn.Linear(6400, 64) self.fc2 = nn.Linear(64, 2) self.hybrid = Hybrid(qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi / 2) self.fc3 = nn.Linear(2, 2) def forward(self, x): x = F.relu(self.conv1(x)) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) x = x.view(-1, 6400) x = F.relu(self.fc1(x)) # print(x.size()) x = self.fc2(x) # print("x before hybrid layer", x) # print(x.size()) x = self.hybrid(x) # print("x after hybrid layer", x) # x = F.relu(self.fc3(x.float())) # print("return: ", torch.cat((x, 1 - x), -1)) x = self.fc3(x.float()) # print(torch.cat((x, 1 - x), -1)) # return torch.cat((x, 1 - x), -1) # print("softmax: ", F.softmax(x)) # print("argmax: ", torch.argmax(x)) return F.softmax(x) # return torch.argmax(x) # model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.CrossEntropyLoss() epochs = 20 loss_list = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): # print(target) optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format( 100. * (epoch + 1) / epochs, loss_list[-1])) plt.plot(loss_list) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) n_samples_show = 6 count = 0 fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) model.eval() with torch.no_grad(): for batch_idx, (data, target) in enumerate(test_loader): if count == n_samples_show: break output = model(data) pred = output.argmax(dim=1, keepdim=True) axes[count].imshow(data[0].numpy().squeeze(), cmap='gray') axes[count].set_xticks([]) axes[count].set_yticks([]) axes[count].set_title('Predicted {}'.format(pred.item())) count += 1 import qiskit qiskit.__qiskit_version__
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit top = QuantumCircuit(1) top.x(0); bottom = QuantumCircuit(2) bottom.cry(0.2, 0, 1); tensored = bottom.tensor(top) tensored.draw('mpl')
https://github.com/Alice-Bob-SW/qiskit-alice-bob-provider
Alice-Bob-SW
from qiskit import Aer, IBMQ, execute from qiskit import transpile, assemble from qiskit.tools.monitor import job_monitor from qiskit.tools.monitor import job_monitor import matplotlib.pyplot as plt from qiskit.visualization import plot_histogram, plot_state_city """ Qiskit backends to execute the quantum circuit """ def simulator(qc): """ Run on local simulator :param qc: quantum circuit :return: """ backend = Aer.get_backend("qasm_simulator") shots = 2048 tqc = transpile(qc, backend) qobj = assemble(tqc, shots=shots) job_sim = backend.run(qobj) qc_results = job_sim.result() return qc_results, shots def simulator_state_vector(qc): """ Select the StatevectorSimulator from the Aer provider :param qc: quantum circuit :return: statevector """ simulator = Aer.get_backend('statevector_simulator') # Execute and get counts result = execute(qc, simulator).result() state_vector = result.get_statevector(qc) return state_vector def real_quantum_device(qc): """ Use the IBMQ essex device :param qc: quantum circuit :return: """ provider = IBMQ.load_account() backend = provider.get_backend('ibmq_santiago') shots = 2048 TQC = transpile(qc, backend) qobj = assemble(TQC, shots=shots) job_exp = backend.run(qobj) job_monitor(job_exp) QC_results = job_exp.result() return QC_results, shots def counts(qc_results): """ Get counts representing the wave-function amplitudes :param qc_results: :return: dict keys are bit_strings and their counting values """ return qc_results.get_counts() def plot_results(qc_results): """ Visualizing wave-function amplitudes in a histogram :param qc_results: quantum circuit :return: """ plt.show(plot_histogram(qc_results.get_counts(), figsize=(8, 6), bar_labels=False)) def plot_state_vector(state_vector): """Visualizing state vector in the density matrix representation""" plt.show(plot_state_city(state_vector))
https://github.com/Pitt-JonesLab/mirror-gates
Pitt-JonesLab
# determine depolarizing error rate # such that the fidelity of each two-qubit gate is 0.99 # https://qiskit.org/documentation/locale/de_DE/tutorials/simulators/2_device_noise_simulation.html from mirror_gates.noisy_fidelity import NoiseModelBuilder from qiskit.transpiler.coupling import CouplingMap N = 2 coupling_map = CouplingMap.from_line(N) basis_gates = ["cx", "u", "rxx", "ryy", "id"] builder = NoiseModelBuilder(basis_gates=basis_gates, coupling_map=coupling_map) from mirror_gates.noisy_fidelity import T1, T2 p1, p2 = 0, 0.00658 builder.construct_basic_device_model(p_depol1=p1, p_depol2=p2, t1=T1, t2=T2) noise_model = builder.noise_model from qiskit_aer import AerSimulator, QasmSimulator noisy_simulator = AerSimulator(noise_model=noise_model) simulator = QasmSimulator(method="density_matrix") from qiskit.circuit.library import SiSwapGate from qiskit import QuantumCircuit, transpile qc = QuantumCircuit(2) qc.append(SiSwapGate(), [0, 1]) qc = transpile(qc, noisy_simulator, basis_gates=basis_gates, coupling_map=coupling_map) qc.save_density_matrix(list(range(N))) qc.draw("mpl") # test fidelity from qiskit.quantum_info import state_fidelity perfect_result = simulator.run(qc).result().data()["density_matrix"] noisy_result = noisy_simulator.run(qc).result().data()["density_matrix"] fidelity = state_fidelity(perfect_result, noisy_result) print(fidelity) import numpy as np from scipy.optimize import minimize from qiskit.circuit.library import SiSwapGate from qiskit import QuantumCircuit, transpile from qiskit_aer import AerSimulator, QasmSimulator from qiskit.quantum_info import state_fidelity, random_unitary from mirror_gates.noisy_fidelity import T1, T2, NoiseModelBuilder from qiskit.transpiler.coupling import CouplingMap def fidelity_difference_1Q(p1, desired_fidelity): # Create a 1Q quantum circuit with a random unitary gate each iteration u = random_unitary(2).data qc = QuantumCircuit(1) qc.h(0) qc.unitary(u, 0) return get_fidelity_for_p(p1[0], 0, qc, desired_fidelity) def fidelity_difference_2Q(p2, p1, desired_fidelity): # 2Q quantum circuit qc = QuantumCircuit(2) qc.append(SiSwapGate(), [0, 1]) return get_fidelity_for_p(p1, p2[0], qc, desired_fidelity) def get_fidelity_for_p(p1, p2, qc, desired_fidelity): N = qc.num_qubits coupling_map = CouplingMap.from_line(N) basis_gates = ["cx", "u", "rxx", "ryy", "id"] builder = NoiseModelBuilder(basis_gates=basis_gates, coupling_map=coupling_map) builder.construct_basic_device_model(p_depol1=p1, p_depol2=p2, t1=T1, t2=T2) noise_model = builder.noise_model noisy_simulator = AerSimulator(noise_model=noise_model) simulator = QasmSimulator(method="density_matrix") qc = transpile( qc, noisy_simulator, basis_gates=basis_gates, coupling_map=coupling_map ) qc.save_density_matrix(list(range(N))) perfect_result = simulator.run(qc).result().data()["density_matrix"] noisy_result = noisy_simulator.run(qc).result().data()["density_matrix"] fidelity = state_fidelity(perfect_result, noisy_result) return abs(fidelity - desired_fidelity) if __name__ == "__main__": desired_fidelity_1Q = 0.9995 res_1Q = minimize( fidelity_difference_1Q, [0], args=(desired_fidelity_1Q,), bounds=[(0, 0.1)], method="L-BFGS-B", ) p1_optimal = res_1Q.x[0] desired_fidelity_2Q = 0.99 res_2Q = minimize( fidelity_difference_2Q, [0], args=(p1_optimal, desired_fidelity_2Q), bounds=[(0, 0.1)], method="L-BFGS-B", ) p2_optimal = res_2Q.x[0] print(p1_optimal, p2_optimal)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from sklearn.datasets import make_blobs # example dataset features, labels = make_blobs(n_samples=20, n_features=2, centers=2, random_state=3, shuffle=True) import numpy as np from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler features = MinMaxScaler(feature_range=(0, np.pi)).fit_transform(features) train_features, test_features, train_labels, test_labels = train_test_split( features, labels, train_size=15, shuffle=False ) # number of qubits is equal to the number of features num_qubits = 2 # number of steps performed during the training procedure tau = 100 # regularization parameter C = 1000 from qiskit import BasicAer from qiskit.circuit.library import ZFeatureMap from qiskit.utils import algorithm_globals from qiskit_machine_learning.kernels import FidelityQuantumKernel algorithm_globals.random_seed = 12345 feature_map = ZFeatureMap(feature_dimension=num_qubits, reps=1) qkernel = FidelityQuantumKernel(feature_map=feature_map) from qiskit_machine_learning.algorithms import PegasosQSVC pegasos_qsvc = PegasosQSVC(quantum_kernel=qkernel, C=C, num_steps=tau) # training pegasos_qsvc.fit(train_features, train_labels) # testing pegasos_score = pegasos_qsvc.score(test_features, test_labels) print(f"PegasosQSVC classification test score: {pegasos_score}") grid_step = 0.2 margin = 0.2 grid_x, grid_y = np.meshgrid( np.arange(-margin, np.pi + margin, grid_step), np.arange(-margin, np.pi + margin, grid_step) ) meshgrid_features = np.column_stack((grid_x.ravel(), grid_y.ravel())) meshgrid_colors = pegasos_qsvc.predict(meshgrid_features) import matplotlib.pyplot as plt plt.figure(figsize=(5, 5)) meshgrid_colors = meshgrid_colors.reshape(grid_x.shape) plt.pcolormesh(grid_x, grid_y, meshgrid_colors, cmap="RdBu", shading="auto") plt.scatter( train_features[:, 0][train_labels == 0], train_features[:, 1][train_labels == 0], marker="s", facecolors="w", edgecolors="r", label="A train", ) plt.scatter( train_features[:, 0][train_labels == 1], train_features[:, 1][train_labels == 1], marker="o", facecolors="w", edgecolors="b", label="B train", ) plt.scatter( test_features[:, 0][test_labels == 0], test_features[:, 1][test_labels == 0], marker="s", facecolors="r", edgecolors="r", label="A test", ) plt.scatter( test_features[:, 0][test_labels == 1], test_features[:, 1][test_labels == 1], marker="o", facecolors="b", edgecolors="b", label="B test", ) plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0) plt.title("Pegasos Classification") plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/urwin419/QiskitChecker
urwin419
import numpy as np import qiskit #Create the oracle for the secret string def oracle(circuit: qiskit.QuantumCircuit, bitstring: str): #Get the length of the bitstring length = len(bitstring) #Copy every qubit from the first register to the second register for i in range(length): circuit.cx(i, length+i) #Create a 1-to-1 or 2-to-1 mapping: #Get the index of the last 1 in bitstring l = bitstring.rfind('1') #Flip the qubit with index in the second register for bitstring[index] is 1 for index, s in enumerate(bitstring): if s == '1' and l != -1: circuit.cx(l, length+index) #Create a random permutation #Get random permutation of n qubits permutation = list(np.random.permutation(length)) #Record initial positions ini_p = list(range(length)) for i in range(length-1): if ini_p[i] != permutation[i]: j = permutation.index(ini_p[i]) #Swap qubits circuit.swap(length+i, length+j) #Record the positions of swapped qubits ini_p[i], ini_p[j] = ini_p[j], ini_p[i] #Flip the qubits randomly for i in range(length): if np.random.random() > 0.5: circuit.x(length+i) return circuit #Create the circuit for the Simon's algorithm def algorithm(bitstring: str): #Get the length of the bitstring length = len(bitstring) #Create the quantum circuits simon_circuit = qiskit.QuantumCircuit(length*2, length) #Apply H-gates to all qubits simon_circuit.h(range(length)) #Apply the oracle created simon_circuit = oracle(simon_circuit,bitstring) #Apply H-gates to all qubits simon_circuit.h(range(length)) #Measure all the qubits simon_circuit.measure(range(length), range(length)) return simon_circuit #Calculate the dot-product def dotp(bitstring, result): #Calculate the dot-product by mutiply each position and add them together accum = 0 for i in range(len(bitstring)): accum += int(bitstring[i]) * int(result[i]) #Return the result by modulo 2 return accum % 2 #Run the simulation with the given circuit def simon(bitstring:str): #Get the simulator qasm_simulator = qiskit.Aer.get_backend('qasm_simulator') #Execute the Simon's algorithm job = qiskit.execute(algorithm(bitstring),qasm_simulator, shots=10000) # Get results result = job.result().get_counts() return result
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for drawing of timeline drawer.""" import numpy as np import qiskit from qiskit.test import QiskitTestCase from qiskit.visualization.timeline import drawings, types class TestDrawingObjects(QiskitTestCase): """Tests for drawings.""" def setUp(self) -> None: """Setup.""" super().setUp() # bits self.qubits = list(qiskit.QuantumRegister(2)) # metadata self.meta1 = {"val1": 0, "val2": 1} self.meta2 = {"val1": 2, "val2": 3} # style data self.style1 = {"property1": 0, "property2": 1} self.style2 = {"property1": 2, "property2": 3} def test_line_data_equivalent(self): """Test LineData equivalent check.""" xs = list(np.arange(10)) ys = list(np.ones(10)) obj1 = drawings.LineData( data_type=types.LineType.BARRIER, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta1, styles=self.style1, ) obj2 = drawings.LineData( data_type=types.LineType.BARRIER, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta2, styles=self.style2, ) self.assertEqual(obj1, obj2) def test_line_data_equivalent_abstract_coord(self): """Test LineData equivalent check with abstract coordinate.""" xs = [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT] ys = [types.AbstractCoordinate.BOTTOM, types.AbstractCoordinate.TOP] obj1 = drawings.LineData( data_type=types.LineType.BARRIER, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta1, styles=self.style1, ) obj2 = drawings.LineData( data_type=types.LineType.BARRIER, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta2, styles=self.style2, ) self.assertEqual(obj1, obj2) def test_box_data_equivalent(self): """Test BoxData equivalent check.""" xs = [0, 1] ys = [0, 1] obj1 = drawings.BoxData( data_type=types.BoxType.SCHED_GATE, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta1, styles=self.style1, ) obj2 = drawings.BoxData( data_type=types.BoxType.SCHED_GATE, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta2, styles=self.style2, ) self.assertEqual(obj1, obj2) def test_box_data_equivalent_abstract_coord(self): """Test BoxData equivalent check with abstract coordinate.""" xs = [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT] ys = [types.AbstractCoordinate.BOTTOM, types.AbstractCoordinate.TOP] obj1 = drawings.BoxData( data_type=types.BoxType.SCHED_GATE, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta1, styles=self.style1, ) obj2 = drawings.BoxData( data_type=types.BoxType.SCHED_GATE, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta2, styles=self.style2, ) self.assertEqual(obj1, obj2) def test_text_data_equivalent(self): """Test TextData equivalent check.""" obj1 = drawings.TextData( data_type=types.LabelType.GATE_NAME, bit=self.qubits[0], xval=0, yval=0, text="test", latex="test", meta=self.meta1, styles=self.style1, ) obj2 = drawings.TextData( data_type=types.LabelType.GATE_NAME, bit=self.qubits[0], xval=0, yval=0, text="test", latex="test", meta=self.meta2, styles=self.style2, ) self.assertEqual(obj1, obj2) def test_text_data_equivalent_abstract_coord(self): """Test TextData equivalent check with abstract coordinate.""" obj1 = drawings.TextData( data_type=types.LabelType.GATE_NAME, bit=self.qubits[0], xval=types.AbstractCoordinate.LEFT, yval=types.AbstractCoordinate.BOTTOM, text="test", latex="test", meta=self.meta1, styles=self.style1, ) obj2 = drawings.TextData( data_type=types.LabelType.GATE_NAME, bit=self.qubits[0], xval=types.AbstractCoordinate.LEFT, yval=types.AbstractCoordinate.BOTTOM, text="test", latex="test", meta=self.meta2, styles=self.style2, ) self.assertEqual(obj1, obj2) def test_bit_link_data_equivalent(self): """Test BitLinkData equivalent check.""" obj1 = drawings.GateLinkData( bits=[self.qubits[0], self.qubits[1]], xval=0, styles=self.style1 ) obj2 = drawings.GateLinkData( bits=[self.qubits[0], self.qubits[1]], xval=0, styles=self.style2 ) self.assertEqual(obj1, obj2) def test_bit_link_data_equivalent_abstract_coord(self): """Test BitLinkData equivalent check with abstract coordinate.""" obj1 = drawings.GateLinkData( bits=[self.qubits[0], self.qubits[1]], xval=types.AbstractCoordinate.LEFT, styles=self.style1, ) obj2 = drawings.GateLinkData( bits=[self.qubits[0], self.qubits[1]], xval=types.AbstractCoordinate.LEFT, styles=self.style2, ) self.assertEqual(obj1, obj2)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools import pickle plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.providers.aer import QasmSimulator from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity # Suppress warnings import warnings warnings.filterwarnings('ignore') def trotter_gate(dt, to_instruction = True): qc = QuantumCircuit(2) qc.rx(2*dt,0) qc.rz(2*dt,1) qc.h(1) qc.cx(1,0) qc.rz(-2*dt, 0) qc.rx(-2*dt, 1) qc.rz(2*dt, 1) qc.cx(1,0) qc.h(1) qc.rz(2*dt, 0) return qc.to_instruction() if to_instruction else qc trotter_gate(np.pi / 6, to_instruction=False).draw("mpl") # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate Trot_gate = trotter_gate(dt) # Number of trotter steps trotter_steps = 100 ### CAN BE >= 4 # Initialize quantum circuit for 3 qubits qr = QuantumRegister(7) qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) qc.x([5]) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) # Simulate time evolution under H_heis3 Hamiltonian for _ in range(trotter_steps): qc.append(Trot_gate, [qr[3], qr[5]]) qc.cx(qr[3], qr[1]) qc.cx(qr[5], qr[3]) # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time/trotter_steps}) t3_qc = transpile(qc, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_qc = transpile(t3_qc, optimization_level=3, basis_gates=["sx", "cx", "rz"]) # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(t3_qc, [qr[1], qr[3], qr[5]]) # Display circuit for confirmation # st_qcs[-1].decompose().draw() # view decomposition of trotter gates st_qcs[-1].draw("mpl") # only view trotter gates from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") shots = 8192 reps = 8 jobs = [] for _ in range(reps): # execute job = execute(st_qcs, backend, shots=shots) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3) print('Job ID', cal_job.job_id()) with open("jakarta_100step.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open("jakarta_100step.pkl", "rb") as f: job_list = pickle.load(f) jobs = job_list["jobs"] cal_job = job_list["cal_job"] cal_results = cal_job.result() print("retrieved cal_results") qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') results = [] mit_results = [] for i, job in enumerate(jobs): results.append(job.result()) mit_results.append( meas_fitter.filter.apply(job.result()) ) print("retrieved", i, "th results") # Compute the state tomography based on the st_qcs quantum circuits and the results from those ciricuits def state_tomo(result, st_qcs): # The expected final state; necessary to determine state tomography fidelity target_state = (One^One^Zero).to_matrix() # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) # Fit state tomography results tomo_fitter = StateTomographyFitter(result, st_qcs) rho_fit = tomo_fitter.fit(method='lstsq') # Compute fidelity fid = state_fidelity(rho_fit, target_state) return fid # Compute tomography fidelities for each repetition fids = [] for result in results: fid = state_tomo(result, st_qcs) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids))) mit_fids = [] for mit_result in mit_results: mit_fid = state_tomo(mit_result, st_qcs) mit_fids.append(mit_fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(mit_fids), np.std(mit_fids)))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# You can make the bars more transparent to better see the ones that are behind # if they overlap. import numpy as np from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_city from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0,1) qc.ry(np.pi/3, 0) qc.rx(np.pi/5, 1) state = Statevector(qc) plot_state_city(state, alpha=0.6)
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
PabloMartinezAngerosa
import json import csv import numpy as np import networkx as nx import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble from qiskit.quantum_info import Statevector from qiskit.aqua.algorithms import NumPyEigensolver from qiskit.quantum_info import Pauli from qiskit.aqua.operators import op_converter from qiskit.aqua.operators import WeightedPauliOperator from qiskit.visualization import plot_histogram from qiskit.providers.aer.extensions.snapshot_statevector import * from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost from utils import mapeo_grafo from collections import defaultdict from operator import itemgetter from scipy.optimize import minimize import matplotlib.pyplot as plt LAMBDA = 10 SHOTS = 10000 UNIFORM_CONVERGENCE_SAMPLE = [] # returns the bit index for an alpha and j def bit(i_city, l_time, num_cities): return i_city * num_cities + l_time # e^(cZZ) def append_zz_term(qc, q_i, q_j, gamma, constant_term): qc.cx(q_i, q_j) qc.rz(2*gamma*constant_term,q_j) qc.cx(q_i, q_j) # e^(cZ) def append_z_term(qc, q_i, gamma, constant_term): qc.rz(2*gamma*constant_term, q_i) # e^(cX) def append_x_term(qc,qi,beta): qc.rx(-2*beta, qi) def get_not_edge_in(G): N = G.number_of_nodes() not_edge = [] for i in range(N): for j in range(N): if i != j: buffer_tupla = (i,j) in_edges = False for edge_i, edge_j in G.edges(): if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)): in_edges = True if in_edges == False: not_edge.append((i, j)) return not_edge def get_classical_simplified_z_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # z term # z_classic_term = [0] * N**2 # first term for l in range(N): for i in range(N): z_il_index = bit(i, l, N) z_classic_term[z_il_index] += -1 * _lambda # second term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_jl z_jl_index = bit(j, l, N) z_classic_term[z_jl_index] += _lambda / 2 # third term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_ij z_ij_index = bit(i, j, N) z_classic_term[z_ij_index] += _lambda / 2 # fourth term not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 4 # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) z_classic_term[z_jlplus_index] += _lambda / 4 # fifthy term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) z_classic_term[z_il_index] += weight_ij / 4 # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) z_classic_term[z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) z_classic_term[z_il_index] += weight_ji / 4 # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) z_classic_term[z_jlplus_index] += weight_ji / 4 return z_classic_term def get_classical_simplified_zz_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # zz term # zz_classic_term = [[0] * N**2 for i in range(N**2) ] # first term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) # z_jl z_jl_index = bit(j, l, N) zz_classic_term[z_il_index][z_jl_index] += _lambda / 2 # second term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) # z_ij z_ij_index = bit(i, j, N) zz_classic_term[z_il_index][z_ij_index] += _lambda / 2 # third term not_edge = get_not_edge_in(G) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4 # fourth term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4 return zz_classic_term def get_classical_simplified_hamiltonian(G, _lambda): # z term # z_classic_term = get_classical_simplified_z_term(G, _lambda) # zz term # zz_classic_term = get_classical_simplified_zz_term(G, _lambda) return z_classic_term, zz_classic_term def get_cost_circuit(G, gamma, _lambda): N = G.number_of_nodes() N_square = N**2 qc = QuantumCircuit(N_square,N_square) z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda) # z term for i in range(N_square): if z_classic_term[i] != 0: append_z_term(qc, i, gamma, z_classic_term[i]) # zz term for i in range(N_square): for j in range(N_square): if zz_classic_term[i][j] != 0: append_zz_term(qc, i, j, gamma, zz_classic_term[i][j]) return qc def get_mixer_operator(G,beta): N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) for n in range(N**2): append_x_term(qc, n, beta) return qc def invert_counts(counts): return {k[::-1] :v for k,v in counts.items()} def get_QAOA_circuit(G, beta, gamma, _lambda): assert(len(beta)==len(gamma)) N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) # init min mix state qc.h(range(N**2)) p = len(beta) for i in range(p): qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda)) qc = qc.compose(get_mixer_operator(G, beta[i])) qc.barrier(range(N**2)) qc.snapshot_statevector("final_state") qc.measure(range(N**2),range(N**2)) return qc def tsp_obj(x, G): # obtenemos el valor evaluado en f(x_1, x_2,... x_n) z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, LAMBDA) cost = 0 # z term for index in range(len(x)): z = (int(x[index]) * 2 ) -1 cost += z_classic_term[index] * z ## zz term for i in range(len(x)): z_1 = (int(x[i]) * 2 ) -1 for j in range(len(x)): z_2 = (int(x[j]) * 2 ) -1 cost += zz_classic_term[i][j] * z_1 * z_1 return cost # Sample expectation value def compute_tsp_energy(counts, G): energy = 0 get_counts = 0 total_counts = 0 for meas, meas_count in counts.items(): obj_for_meas = tsp_obj(meas, G) energy += obj_for_meas*meas_count total_counts += meas_count return energy/total_counts # Sample expectation value def compute_tsp_energy_2(counts, G): energy = 0 get_counts = 0 total_counts = 0 for meas, meas_count in counts.items(): obj_for_meas = tsp_obj_2(meas, G, LAMBDA) energy += obj_for_meas*meas_count total_counts += meas_count mean = energy/total_counts return mean def tsp_obj_2(x, G,_lambda): # obtenemos el valor evaluado en f(x_1, x_2,... x_n) not_edge = get_not_edge_in(G) N = G.number_of_nodes() tsp_cost=0 #Distancia weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # x_il x_il_index = bit(edge_i, l, N) # x_jlplus l_plus = (l+1) % N x_jlplus_index = bit(edge_j, l_plus, N) tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij # add order term because G.edges() do not include order tuples # # x_i'l x_il_index = bit(edge_j, l, N) # x_j'lplus x_jlplus_index = bit(edge_i, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji #Constraint 1 for l in range(N): penal1 = 1 for i in range(N): x_il_index = bit(i, l, N) penal1 -= int(x[x_il_index]) tsp_cost += _lambda * penal1**2 #Contstraint 2 for i in range(N): penal2 = 1 for l in range(N): x_il_index = bit(i, l, N) penal2 -= int(x[x_il_index]) tsp_cost += _lambda*penal2**2 #Constraint 3 for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # x_il x_il_index = bit(i, l, N) # x_j(l+1) l_plus = (l+1) % N x_jlplus_index = bit(j, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda return tsp_cost def get_black_box_objective(G,p): backend = Aer.get_backend('qasm_simulator') def f(theta): beta = theta[:p] gamma = theta[p:] qc = get_QAOA_circuit(G, beta, gamma, LAMBDA) counts = execute(qc, backend, seed_simulator=10, shots=SHOTS).result().get_counts() return compute_tsp_energy(invert_counts(counts),G) return f def get_black_box_objective_2(G,p): backend = Aer.get_backend('qasm_simulator') sim = Aer.get_backend('aer_simulator') def f(theta): beta = theta[:p] gamma = theta[p:] qc = get_QAOA_circuit(G, beta, gamma, LAMBDA) result = execute(qc, backend, seed_simulator=10, shots= SHOTS).result() final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0] state_vector = Statevector(final_state_vector) probabilities = state_vector.probabilities() probabilities_states = invert_counts(state_vector.probabilities_dict()) expected_value = 0 for state,probability in probabilities_states.items(): cost = tsp_obj_2(state, G, LAMBDA) expected_value += cost*probability counts = result.get_counts() mean = compute_tsp_energy_2(invert_counts(counts),G) global UNIFORM_CONVERGENCE_SAMPLE UNIFORM_CONVERGENCE_SAMPLE.append({ "beta" : beta, "gamma" : gamma, "counts" : counts, "mean" : mean, "probabilities" : probabilities, "expected_value" : expected_value }) return mean return f def compute_tsp_min_energy_2(counts, G): energy = 0 get_counts = 0 total_counts = 0 min = 1000000000000000000000 index = 0 min_meas = "" for meas, meas_count in counts.items(): index = index + 1 obj_for_meas = tsp_obj_2(meas, G, LAMBDA) if obj_for_meas < min: min = obj_for_meas min_meas = meas return index, min, min_meas def compute_tsp_min_energy_1(counts, G): energy = 0 get_counts = 0 total_counts = 0 min = 1000000000000000000000 index = 0 min_meas = "" for meas, meas_count in counts.items(): index = index + 1 obj_for_meas = tsp_obj(meas, G) if obj_for_meas < min: min = obj_for_meas min_meas = meas return index, min, min_meas def test_counts_2(counts, G): mean_energy2 = compute_tsp_energy_2(invert_counts(counts),G) cantidad, min, min_meas = compute_tsp_min_energy_2(invert_counts(counts),G) print("*************************") print("En el algoritmo 2 (Marina) el valor esperado como resultado es " + str(mean_energy2)) print("El valor minimo de todos los evaluados es " + str(min) + " se evaluaron un total de " + str(cantidad)) print("El vector minimo es " + min_meas) def test_counts_1(counts, G): mean_energy1 = compute_tsp_energy(invert_counts(counts),G) cantidad, min, min_meas = compute_tsp_min_energy_1(invert_counts(counts),G) print("*************************") print("En el algoritmo 1 (Pablo) el valor esperado como resultado es " + str(mean_energy1)) print("El valor minimo de todos los evaluados es " + str(min) + " se evaluaron un total de " + str(cantidad)) print("El vector minimo es " + min_meas) def test_solution(grafo=None, p=7): global UNIFORM_CONVERGENCE_SAMPLE UNIFORM_CONVERGENCE_SAMPLE = [] if grafo == None: cantidad_ciudades = 2 pesos, conexiones = None, None mejor_camino = None while not mejor_camino: pesos, conexiones = rand_graph(cantidad_ciudades) mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False) G = mapeo_grafo(conexiones, pesos) print(mejor_costo) print(mejor_camino) print(G.edges()) print(G.nodes()) else: G = grafo bounds = [] intial_random = [] for i in range(p): bounds.append((0, np.pi)) intial_random.append(np.random.uniform(0,np.pi)) for i in range(p): bounds.append((0, np.pi * 2)) intial_random.append(np.random.uniform(0,2*np.pi)) init_point = np.array(intial_random) # Marina Solutions obj = get_black_box_objective_2(G,p) res_sample_2 = minimize(obj, init_point, method="COBYLA", options={"maxiter":2500,"disp":True}) theta_2 = res_sample_2.x beta = theta_2[:p] gamma = theta_2[p:] _lambda = LAMBDA qc = get_QAOA_circuit(G, beta, gamma, LAMBDA) backend = Aer.get_backend('qasm_simulator') job_2 = execute(qc, backend, shots = SHOTS) resutls_2 = job_2.result().get_counts() test_counts_2(resutls_2, G) return job_2, G, UNIFORM_CONVERGENCE_SAMPLE def create_multiple_p_mismo_grafo(): header = ['p', 'state', 'probability', 'mean'] length_p = 10 with open('qaoa_multiple_p.csv', 'w', encoding='UTF8') as f: writer = csv.writer(f) writer.writerow(header) first_p = False uniform_convergence_sample = [] for p in range(length_p): p = p+1 if first_p == False: job_2, G, uniform_convergence_sample = test_solution(p=p) first_p = True else: job_2, G, uniform_convergence_sample = test_solution(grafo=G, p=p) # Sort the JSON data based on the value of the brand key uniform_convergence_sample.sort(key=lambda x: x["mean"]) mean = uniform_convergence_sample[0]["mean"] print(mean) state = 0 for probability in uniform_convergence_sample[0]["probabilities"]: state += 1 writer.writerow([p,state, probability,mean]) def create_multiple_p_mismo_grafo_multiples_instanncias(): header = ['instance','p','distance', 'mean'] length_p = 4 length_instances = 10 with open('qaoa_multiple_p_distance.csv', 'w', encoding='UTF8') as f: writer = csv.writer(f) writer.writerow(header) instance_index = 0 for instance in range(length_instances): instance_index += 1 first_p = False UNIFORM_CONVERGENCE_P = [] uniform_convergence_sample = [] for p in range(length_p): p = p+1 print("p es igual " + str(p)) if first_p == False: print("Vuelve a llamar a test_solution") job_2, G, uniform_convergence_sample = test_solution(p=p) first_p = True else: job_2, G, uniform_convergence_sample = test_solution(grafo=G, p=p) # Sort the JSON data based on the value of the brand key uniform_convergence_sample.sort(key=lambda x: x["expected_value"]) convergence_min = uniform_convergence_sample[0] UNIFORM_CONVERGENCE_P.append({ "mean":convergence_min["expected_value"], "probabilities": convergence_min["probabilities"] }) cauchy_function_nk = UNIFORM_CONVERGENCE_P[len(UNIFORM_CONVERGENCE_P) - 1] p_index = 0 for p_state in UNIFORM_CONVERGENCE_P: p_index += 1 print(p_index) mean = p_state["mean"] distance_p_cauchy_function_nk = np.max(np.abs(cauchy_function_nk["probabilities"] - p_state["probabilities"])) writer.writerow([instance_index, p_index, distance_p_cauchy_function_nk, mean]) if __name__ == '__main__': create_multiple_p_mismo_grafo_multiples_instanncias() def defult_init(): cantidad_ciudades = 2 pesos, conexiones = None, None mejor_camino = None while not mejor_camino: pesos, conexiones = rand_graph(cantidad_ciudades) mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False) G = mapeo_grafo(conexiones, pesos) print(mejor_costo) print(mejor_camino) print(G.edges()) print(G.nodes()) print("labels") labels = nx.get_edge_attributes(G,'weight') p = 5 obj = get_black_box_objective(G,p) init_point = np.array([0.8,2.2,0.83,2.15,0.37,2.4,6.1,2.2,3.8,6.1]) # Marina Solutions obj = get_black_box_objective_2(G,p) res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True}) print(res_sample) theta_2 = [0.72685401, 2.15678239, 0.86389827, 2.19403121, 0.26916675, 2.19832144, 7.06651453, 3.20333137, 3.81301611, 6.08893568] theta_1 = [0.90644898, 2.15994212, 1.8609325 , 2.14042604, 1.49126214, 2.4127999, 6.10529434, 2.18238732, 3.84056674, 6.07097744] beta = theta_1[:p] gamma = theta_1[p:] qc = get_QAOA_circuit(G, beta, gamma, LAMBDA) backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend) beta = theta_2[:p] gamma = theta_2[p:] qc = get_QAOA_circuit(G, beta, gamma, LAMBDA) backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend)
https://github.com/maheshwaripranav/Qiskit-Fall-Fest-Kolkata-Hackathon
maheshwaripranav
# Essentials import matplotlib.pyplot as plt import numpy as np import pandas as pd # Classical Machine Learning from sklearn.svm import SVC from sklearn.datasets import make_blobs, make_circles from sklearn.cluster import SpectralClustering from sklearn.metrics import normalized_mutual_info_score, accuracy_score from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler, MinMaxScaler # Quantum Machine Learning from qiskit import BasicAer from qiskit.circuit.library import ZZFeatureMap, ZFeatureMap, PauliFeatureMap from qiskit.utils import QuantumInstance, algorithm_globals from qiskit_machine_learning.algorithms import QSVC from qiskit_machine_learning.kernels import QuantumKernel dataset = pd.read_csv(r'iris_data\iris.data') features= dataset.iloc[:, :4].values label = dataset.iloc[:, 4].values for i in range(len(label)): if label[i] == 'Iris-setosa': label[i] = 0 elif label[i] == 'Iris-versicolor': label[i] = 1 elif label[i] == 'Iris-virginica': label[i] = 2 label X_train, X_test, y_train, y_test = train_test_split(features, label, test_size=0.25, random_state=11) sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) # Normalize mms = MinMaxScaler((-1, 1)) X_train = mms.fit_transform(X_train) X_test = mms.transform(X_test) clf = SVC(kernel="linear", random_state=2) clf.fit(X_train, y_train) print("Accuracy is", accuracy_score(y_test, y_pred))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np # Import Qiskit from qiskit import QuantumCircuit from qiskit import Aer, transpile from qiskit.tools.visualization import plot_histogram, plot_state_city import qiskit.quantum_info as qi Aer.backends() simulator = Aer.get_backend('aer_simulator') # Create circuit circ = QuantumCircuit(2) circ.h(0) circ.cx(0, 1) circ.measure_all() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get counts result = simulator.run(circ).result() counts = result.get_counts(circ) plot_histogram(counts, title='Bell-State counts') # Run and get memory result = simulator.run(circ, shots=10, memory=True).result() memory = result.get_memory(circ) print(memory) # Increase shots to reduce sampling variance shots = 10000 # Stabilizer simulation method sim_stabilizer = Aer.get_backend('aer_simulator_stabilizer') job_stabilizer = sim_stabilizer.run(circ, shots=shots) counts_stabilizer = job_stabilizer.result().get_counts(0) # Statevector simulation method sim_statevector = Aer.get_backend('aer_simulator_statevector') job_statevector = sim_statevector.run(circ, shots=shots) counts_statevector = job_statevector.result().get_counts(0) # Density Matrix simulation method sim_density = Aer.get_backend('aer_simulator_density_matrix') job_density = sim_density.run(circ, shots=shots) counts_density = job_density.result().get_counts(0) # Matrix Product State simulation method sim_mps = Aer.get_backend('aer_simulator_matrix_product_state') job_mps = sim_mps.run(circ, shots=shots) counts_mps = job_mps.result().get_counts(0) plot_histogram([counts_stabilizer, counts_statevector, counts_density, counts_mps], title='Counts for different simulation methods', legend=['stabilizer', 'statevector', 'density_matrix', 'matrix_product_state']) from qiskit_aer import AerError # Initialize a GPU backend # Note that the cloud instance for tutorials does not have a GPU # so this will raise an exception. try: simulator_gpu = Aer.get_backend('aer_simulator') simulator_gpu.set_options(device='GPU') except AerError as e: print(e) # Configure a single-precision statevector simulator backend simulator = Aer.get_backend('aer_simulator_statevector') simulator.set_options(precision='single') # Run and get counts result = simulator.run(circ).result() counts = result.get_counts(circ) print(counts) # Construct quantum circuit without measure circ = QuantumCircuit(2) circ.h(0) circ.cx(0, 1) circ.save_statevector() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get statevector result = simulator.run(circ).result() statevector = result.get_statevector(circ) plot_state_city(statevector, title='Bell state') # Construct quantum circuit without measure circ = QuantumCircuit(2) circ.h(0) circ.cx(0, 1) circ.save_unitary() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get unitary result = simulator.run(circ).result() unitary = result.get_unitary(circ) print("Circuit unitary:\n", np.asarray(unitary).round(5)) # Construct quantum circuit without measure steps = 5 circ = QuantumCircuit(1) for i in range(steps): circ.save_statevector(label=f'psi_{i}') circ.rx(i * np.pi / steps, 0) circ.save_statevector(label=f'psi_{steps}') # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get saved data result = simulator.run(circ).result() data = result.data(0) data # Generate a random statevector num_qubits = 2 psi = qi.random_statevector(2 ** num_qubits, seed=100) # Set initial state to generated statevector circ = QuantumCircuit(num_qubits) circ.set_statevector(psi) circ.save_state() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get saved data result = simulator.run(circ).result() result.data(0) # Use initilize instruction to set initial state circ = QuantumCircuit(num_qubits) circ.initialize(psi, range(num_qubits)) circ.save_state() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get result data result = simulator.run(circ).result() result.data(0) num_qubits = 2 rho = qi.random_density_matrix(2 ** num_qubits, seed=100) circ = QuantumCircuit(num_qubits) circ.set_density_matrix(rho) circ.save_state() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get saved data result = simulator.run(circ).result() result.data(0) # Generate a random Clifford C num_qubits = 2 stab = qi.random_clifford(num_qubits, seed=100) # Set initial state to stabilizer state C|0> circ = QuantumCircuit(num_qubits) circ.set_stabilizer(stab) circ.save_state() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get saved data result = simulator.run(circ).result() result.data(0) # Generate a random unitary num_qubits = 2 unitary = qi.random_unitary(2 ** num_qubits, seed=100) # Set initial state to unitary circ = QuantumCircuit(num_qubits) circ.set_unitary(unitary) circ.save_state() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get saved data result = simulator.run(circ).result() result.data(0) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/AbeerVaishnav13/Quantum-Programs
AbeerVaishnav13
# Do the necessary imports import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import IBMQ, Aer, transpile, assemble from qiskit.visualization import plot_histogram, plot_bloch_multivector, array_to_latex from qiskit.extensions import Initialize from qiskit.ignis.verification import marginal_counts from qiskit.quantum_info import random_statevector # Loading your IBM Quantum account(s) provider = IBMQ.load_account() ## SETUP # Protocol uses 3 qubits and 2 classical bits in 2 different registers qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits crz = ClassicalRegister(1, name="crz") # and 2 classical bits crx = ClassicalRegister(1, name="crx") # in 2 different registers teleportation_circuit = QuantumCircuit(qr, crz, crx) def create_bell_pair(qc, a, b): qc.h(a) qc.cx(a,b) qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) create_bell_pair(teleportation_circuit, 1, 2) teleportation_circuit.draw() def alice_gates(qc, psi, a): qc.cx(psi, a) qc.h(psi) qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) ## STEP 1 create_bell_pair(teleportation_circuit, 1, 2) ## STEP 2 teleportation_circuit.barrier() # Use barrier to separate steps alice_gates(teleportation_circuit, 0, 1) teleportation_circuit.draw() def measure_and_send(qc, a, b): """Measures qubits a & b and 'sends' the results to Bob""" qc.barrier() qc.measure(a,0) qc.measure(b,1) qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) create_bell_pair(teleportation_circuit, 1, 2) teleportation_circuit.barrier() # Use barrier to separate steps alice_gates(teleportation_circuit, 0, 1) measure_and_send(teleportation_circuit, 0 ,1) teleportation_circuit.draw() def bob_gates(qc, qubit, crz, crx): qc.x(qubit).c_if(crx, 1) # Apply gates if the registers qc.z(qubit).c_if(crz, 1) # are in the state '1' qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) ## STEP 1 create_bell_pair(teleportation_circuit, 1, 2) ## STEP 2 teleportation_circuit.barrier() # Use barrier to separate steps alice_gates(teleportation_circuit, 0, 1) ## STEP 3 measure_and_send(teleportation_circuit, 0, 1) ## STEP 4 teleportation_circuit.barrier() # Use barrier to separate steps bob_gates(teleportation_circuit, 2, crz, crx) teleportation_circuit.draw() # Create random 1-qubit state psi = random_statevector(2) # Display it nicely display(array_to_latex(psi, prefix="|\\psi\\rangle =")) # Show it on a Bloch sphere plot_bloch_multivector(psi) init_gate = Initialize(psi) init_gate.label = "init" ## SETUP qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits crz = ClassicalRegister(1, name="crz") # and 2 classical registers crx = ClassicalRegister(1, name="crx") qc = QuantumCircuit(qr, crz, crx) ## STEP 0 # First, let's initialize Alice's q0 qc.append(init_gate, [0]) qc.barrier() ## STEP 1 # Now begins the teleportation protocol create_bell_pair(qc, 1, 2) qc.barrier() ## STEP 2 # Send q1 to Alice and q2 to Bob alice_gates(qc, 0, 1) ## STEP 3 # Alice then sends her classical bits to Bob measure_and_send(qc, 0, 1) ## STEP 4 # Bob decodes qubits bob_gates(qc, 2, crz, crx) # Display the circuit qc.draw() sim = Aer.get_backend('aer_simulator') qc.save_statevector() out_vector = sim.run(qc).result().get_statevector() plot_bloch_multivector(out_vector)
https://github.com/meherafrozantar/QiskitClass
meherafrozantar
!pip install qiskit qiskit-aer !pip install qiskit !pip install pylatexenc from qiskit import * from qiskit.tools.monitor import job_monitor from qiskit.tools.visualization import plot_state_qsphere from qiskit.visualization import plot_histogram, plot_bloch_multivector, array_to_latex # create a circuit circuit = QuantumCircuit(1,1) # Apply Gate circuit.h(0) # apply measurement circuit.measure(0,0) # draw circuit circuit.draw(output = 'mpl', initial_state = True) # select a simulator simulator = Aer.get_backend('aer_simulator') # assemble our circuit qobj = assemble(circuit) # run on simulator job = simulator.run(qobj) # monitoring the process job_monitor(job) # get results from job result = job.result() # colllect histogram data count = result.get_counts() plot_histogram(count) # import library from QC from qiskit import IBMQ # Save API Token IBMQ.save_account('737fd5837bd6099f57e56b04978b745c124a13757839bf80b239192c46a5e46d516b297fecf9524320e12303ec1b0392ea164895bcfef7e43cd5413f1f0dd179') # Load account IBMQ.load_account() # Select provider provider = IBMQ.get_provider
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit, transpile from qiskit.quantum_info import Kraus, SuperOp from qiskit_aer import AerSimulator from qiskit.tools.visualization import plot_histogram # Import from Qiskit Aer noise module from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError, pauli_error, depolarizing_error, thermal_relaxation_error) # Construct a 1-qubit bit-flip and phase-flip errors p_error = 0.05 bit_flip = pauli_error([('X', p_error), ('I', 1 - p_error)]) phase_flip = pauli_error([('Z', p_error), ('I', 1 - p_error)]) print(bit_flip) print(phase_flip) # Compose two bit-flip and phase-flip errors bitphase_flip = bit_flip.compose(phase_flip) print(bitphase_flip) # Tensor product two bit-flip and phase-flip errors with # bit-flip on qubit-0, phase-flip on qubit-1 error2 = phase_flip.tensor(bit_flip) print(error2) # Convert to Kraus operator bit_flip_kraus = Kraus(bit_flip) print(bit_flip_kraus) # Convert to Superoperator phase_flip_sop = SuperOp(phase_flip) print(phase_flip_sop) # Convert back to a quantum error print(QuantumError(bit_flip_kraus)) # Check conversion is equivalent to original error QuantumError(bit_flip_kraus) == bit_flip # Measurement miss-assignement probabilities p0given1 = 0.1 p1given0 = 0.05 ReadoutError([[1 - p1given0, p1given0], [p0given1, 1 - p0given1]]) # Create an empty noise model noise_model = NoiseModel() # Add depolarizing error to all single qubit u1, u2, u3 gates error = depolarizing_error(0.05, 1) noise_model.add_all_qubit_quantum_error(error, ['u1', 'u2', 'u3']) # Print noise model info print(noise_model) # Create an empty noise model noise_model = NoiseModel() # Add depolarizing error to all single qubit u1, u2, u3 gates on qubit 0 only error = depolarizing_error(0.05, 1) noise_model.add_quantum_error(error, ['u1', 'u2', 'u3'], [0]) # Print noise model info print(noise_model) # System Specification n_qubits = 4 circ = QuantumCircuit(n_qubits) # Test Circuit circ.h(0) for qubit in range(n_qubits - 1): circ.cx(qubit, qubit + 1) circ.measure_all() print(circ) # Ideal simulator and execution sim_ideal = AerSimulator() result_ideal = sim_ideal.run(circ).result() plot_histogram(result_ideal.get_counts(0)) # Example error probabilities p_reset = 0.03 p_meas = 0.1 p_gate1 = 0.05 # QuantumError objects error_reset = pauli_error([('X', p_reset), ('I', 1 - p_reset)]) error_meas = pauli_error([('X',p_meas), ('I', 1 - p_meas)]) error_gate1 = pauli_error([('X',p_gate1), ('I', 1 - p_gate1)]) error_gate2 = error_gate1.tensor(error_gate1) # Add errors to noise model noise_bit_flip = NoiseModel() noise_bit_flip.add_all_qubit_quantum_error(error_reset, "reset") noise_bit_flip.add_all_qubit_quantum_error(error_meas, "measure") noise_bit_flip.add_all_qubit_quantum_error(error_gate1, ["u1", "u2", "u3"]) noise_bit_flip.add_all_qubit_quantum_error(error_gate2, ["cx"]) print(noise_bit_flip) # Create noisy simulator backend sim_noise = AerSimulator(noise_model=noise_bit_flip) # Transpile circuit for noisy basis gates circ_tnoise = transpile(circ, sim_noise) # Run and get counts result_bit_flip = sim_noise.run(circ_tnoise).result() counts_bit_flip = result_bit_flip.get_counts(0) # Plot noisy output plot_histogram(counts_bit_flip) # T1 and T2 values for qubits 0-3 T1s = np.random.normal(50e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec T2s = np.random.normal(70e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec # Truncate random T2s <= T1s T2s = np.array([min(T2s[j], 2 * T1s[j]) for j in range(4)]) # Instruction times (in nanoseconds) time_u1 = 0 # virtual gate time_u2 = 50 # (single X90 pulse) time_u3 = 100 # (two X90 pulses) time_cx = 300 time_reset = 1000 # 1 microsecond time_measure = 1000 # 1 microsecond # QuantumError objects errors_reset = [thermal_relaxation_error(t1, t2, time_reset) for t1, t2 in zip(T1s, T2s)] errors_measure = [thermal_relaxation_error(t1, t2, time_measure) for t1, t2 in zip(T1s, T2s)] errors_u1 = [thermal_relaxation_error(t1, t2, time_u1) for t1, t2 in zip(T1s, T2s)] errors_u2 = [thermal_relaxation_error(t1, t2, time_u2) for t1, t2 in zip(T1s, T2s)] errors_u3 = [thermal_relaxation_error(t1, t2, time_u3) for t1, t2 in zip(T1s, T2s)] errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand( thermal_relaxation_error(t1b, t2b, time_cx)) for t1a, t2a in zip(T1s, T2s)] for t1b, t2b in zip(T1s, T2s)] # Add errors to noise model noise_thermal = NoiseModel() for j in range(4): noise_thermal.add_quantum_error(errors_reset[j], "reset", [j]) noise_thermal.add_quantum_error(errors_measure[j], "measure", [j]) noise_thermal.add_quantum_error(errors_u1[j], "u1", [j]) noise_thermal.add_quantum_error(errors_u2[j], "u2", [j]) noise_thermal.add_quantum_error(errors_u3[j], "u3", [j]) for k in range(4): noise_thermal.add_quantum_error(errors_cx[j][k], "cx", [j, k]) print(noise_thermal) # Run the noisy simulation sim_thermal = AerSimulator(noise_model=noise_thermal) # Transpile circuit for noisy basis gates circ_tthermal = transpile(circ, sim_thermal) # Run and get counts result_thermal = sim_thermal.run(circ_tthermal).result() counts_thermal = result_thermal.get_counts(0) # Plot noisy output plot_histogram(counts_thermal) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/1chooo/Quantum-Oracle
1chooo
# %% [markdown] # # 第2章原始程式碼 # %% #Program 2.1 Initialize qubit state from qiskit import QuantumCircuit import math qc = QuantumCircuit(4) qc.initialize([1,0],0) qc.initialize([0,1],1) qc.initialize([1/math.sqrt(2), 1/math.sqrt(2)],2) qc.initialize([1/math.sqrt(2), -1/math.sqrt(2)],3) qc.draw('mpl') # %% #Program 2.2 Initialize qubit state and show Bloch sphere from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector import math qc = QuantumCircuit(4) qc.initialize([1,0],0) qc.initialize([0,1],1) qc.initialize([1/math.sqrt(2), 1/math.sqrt(2)],2) qc.initialize([1/math.sqrt(2), -1/math.sqrt(2)],3) state = Statevector.from_instruction(qc) display(qc.draw('mpl')) display(state.draw('bloch')) # %% #Program 2.3 Show Bloch sphere from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector state = Statevector.from_instruction(qc) plot_bloch_multivector(state) # %% #Program 2.4 Measure qubit state from qiskit import QuantumCircuit,execute from qiskit.providers.aer import AerSimulator from qiskit.visualization import plot_histogram qc = QuantumCircuit(4,4) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.initialize([0,1],2) qc.initialize([0,1],3) qc.measure([0,1,2,3],[0,1,2,3]) print(qc) sim=AerSimulator() job=execute(qc, backend=sim, shots=1000) result=job.result() counts=result.get_counts(qc) print("Counts:",counts) plot_histogram(counts) # %% #Program 2.5 Measure qubit state again from qiskit import QuantumCircuit,execute from qiskit.providers.aer import AerSimulator from qiskit.visualization import plot_histogram import math qc = QuantumCircuit(4,4) qc.initialize([1/math.sqrt(2), 1/math.sqrt(2)],0) qc.initialize([1/math.sqrt(2), -1/math.sqrt(2)],1) qc.initialize([1/math.sqrt(2), 1j/math.sqrt(2)],2) qc.initialize([1/math.sqrt(2), -1j/math.sqrt(2)],3) qc.measure([0,1,2,3],[0,1,2,3]) print(qc) sim=AerSimulator() job=execute(qc, backend=sim, shots=1000) result=job.result() counts=result.get_counts(qc) print("Counts:",counts) plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt import numpy as np from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Sampler from qiskit.utils import algorithm_globals from sklearn.model_selection import train_test_split from sklearn.preprocessing import OneHotEncoder, MinMaxScaler from qiskit_machine_learning.algorithms.classifiers import VQC from IPython.display import clear_output algorithm_globals.random_seed = 42 sampler1 = Sampler() sampler2 = Sampler() num_samples = 40 num_features = 2 features = 2 * algorithm_globals.random.random([num_samples, num_features]) - 1 labels = 1 * (np.sum(features, axis=1) >= 0) # in { 0, 1} features = MinMaxScaler().fit_transform(features) features.shape features[0:5, :] labels = OneHotEncoder(sparse=False).fit_transform(labels.reshape(-1, 1)) labels.shape labels[0:5, :] train_features, test_features, train_labels, test_labels = train_test_split( features, labels, train_size=30, random_state=algorithm_globals.random_seed ) train_features.shape def plot_dataset(): plt.scatter( train_features[np.where(train_labels[:, 0] == 0), 0], train_features[np.where(train_labels[:, 0] == 0), 1], marker="o", color="b", label="Label 0 train", ) plt.scatter( train_features[np.where(train_labels[:, 0] == 1), 0], train_features[np.where(train_labels[:, 0] == 1), 1], marker="o", color="g", label="Label 1 train", ) plt.scatter( test_features[np.where(test_labels[:, 0] == 0), 0], test_features[np.where(test_labels[:, 0] == 0), 1], marker="o", facecolors="w", edgecolors="b", label="Label 0 test", ) plt.scatter( test_features[np.where(test_labels[:, 0] == 1), 0], test_features[np.where(test_labels[:, 0] == 1), 1], marker="o", facecolors="w", edgecolors="g", label="Label 1 test", ) plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0) plt.plot([1, 0], [0, 1], "--", color="black") plot_dataset() plt.show() maxiter = 20 objective_values = [] # callback function that draws a live plot when the .fit() method is called def callback_graph(_, objective_value): clear_output(wait=True) objective_values.append(objective_value) plt.title("Objective function value against iteration") plt.xlabel("Iteration") plt.ylabel("Objective function value") stage1_len = np.min((len(objective_values), maxiter)) stage1_x = np.linspace(1, stage1_len, stage1_len) stage1_y = objective_values[:stage1_len] stage2_len = np.max((0, len(objective_values) - maxiter)) stage2_x = np.linspace(maxiter, maxiter + stage2_len - 1, stage2_len) stage2_y = objective_values[maxiter : maxiter + stage2_len] plt.plot(stage1_x, stage1_y, color="orange") plt.plot(stage2_x, stage2_y, color="purple") plt.show() plt.rcParams["figure.figsize"] = (12, 6) original_optimizer = COBYLA(maxiter=maxiter) ansatz = RealAmplitudes(num_features) initial_point = np.asarray([0.5] * ansatz.num_parameters) original_classifier = VQC( ansatz=ansatz, optimizer=original_optimizer, callback=callback_graph, sampler=sampler1 ) original_classifier.fit(train_features, train_labels) print("Train score", original_classifier.score(train_features, train_labels)) print("Test score ", original_classifier.score(test_features, test_labels)) original_classifier.save("vqc_classifier.model") loaded_classifier = VQC.load("vqc_classifier.model") loaded_classifier.warm_start = True loaded_classifier.neural_network.sampler = sampler2 loaded_classifier.optimizer = COBYLA(maxiter=80) loaded_classifier.fit(train_features, train_labels) print("Train score", loaded_classifier.score(train_features, train_labels)) print("Test score", loaded_classifier.score(test_features, test_labels)) train_predicts = loaded_classifier.predict(train_features) test_predicts = loaded_classifier.predict(test_features) # return plot to default figsize plt.rcParams["figure.figsize"] = (6, 4) plot_dataset() # plot misclassified data points plt.scatter( train_features[np.all(train_labels != train_predicts, axis=1), 0], train_features[np.all(train_labels != train_predicts, axis=1), 1], s=200, facecolors="none", edgecolors="r", linewidths=2, ) plt.scatter( test_features[np.all(test_labels != test_predicts, axis=1), 0], test_features[np.all(test_labels != test_predicts, axis=1), 1], s=200, facecolors="none", edgecolors="r", linewidths=2, ) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.pulse_v2 import draw, IQXSimple from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() qc = transpile(qc, FakeBoeblingen(), layout_method='trivial') sched = schedule(qc, FakeBoeblingen()) draw(sched, style=IQXSimple(), backend=FakeBoeblingen())
https://github.com/1chooo/Quantum-Oracle
1chooo
from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.cx(0, 1) qc.draw("mpl")
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test of generated fake backends.""" import math import unittest from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, schedule, transpile, assemble from qiskit.pulse import Schedule from qiskit.qobj import PulseQobj from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider.utils.configurable_backend import ConfigurableFakeBackend from qiskit.providers.fake_provider import FakeAthens, FakePerth from qiskit.utils import optionals def get_test_circuit(): """Generates simple circuit for tests.""" desired_vector = [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)] qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.initialize(desired_vector, [qr[0], qr[1]]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) return qc class GeneratedFakeBackendsTest(QiskitTestCase): """Generated fake backends test.""" def setUp(self) -> None: self.backend = ConfigurableFakeBackend("Tashkent", n_qubits=4) @unittest.skip("Skipped until qiskit-aer#741 is fixed and released") @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test") def test_transpile_schedule_and_assemble(self): """Test transpile, schedule and assemble on generated backend.""" qc = get_test_circuit() circuit = transpile(qc, backend=self.backend) self.assertTrue(isinstance(circuit, QuantumCircuit)) self.assertEqual(circuit.num_qubits, 4) experiments = schedule(circuits=circuit, backend=self.backend) self.assertTrue(isinstance(experiments, Schedule)) self.assertGreater(experiments.duration, 0) qobj = assemble(experiments, backend=self.backend) self.assertTrue(isinstance(qobj, PulseQobj)) self.assertEqual(qobj.header.backend_name, "Tashkent") self.assertEqual(len(qobj.experiments), 1) job = self.backend.run(qobj) result = job.result() self.assertTrue(result.success) self.assertEqual(len(result.results), 1) class FakeBackendsTest(QiskitTestCase): """fake backends test.""" @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test") def test_fake_backends_get_kwargs(self): """Fake backends honor kwargs passed.""" backend = FakeAthens() qc = QuantumCircuit(2) qc.x(range(0, 2)) qc.measure_all() trans_qc = transpile(qc, backend) raw_counts = backend.run(trans_qc, shots=1000).result().get_counts() self.assertEqual(sum(raw_counts.values()), 1000) @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test") def test_fake_backend_v2_noise_model_always_present(self): """Test that FakeBackendV2 instances always run with noise.""" backend = FakePerth() qc = QuantumCircuit(1) qc.x(0) qc.measure_all() res = backend.run(qc, shots=1000).result().get_counts() # Assert noise was present and result wasn't ideal self.assertNotEqual(res, {"1": 1000})
https://github.com/omarcostahamido/qiskit_app_carbon_design
omarcostahamido
import os from flask import Flask, jsonify, request import json import requests # New QISKit libraries from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit from qiskit import execute from qiskit import IBMQ #from qiskit.backends.ibmq import least_busy from qiskit import Aer backend = Aer.get_backend('qasm_simulator') # Visualization libraries from qiskit.tools.visualization import plot_bloch_vector from qutip import Bloch,basis import qutip as qq import numpy as np import math as m from IPython.core.pylabtools import print_figure # Import noise function from noisedev import setup_noise def applyOperators(): ### TEST THE ENANCHEMENTS: requirements (enlarge the JSON comprending the base choice) """ This function is activated by the "makeReq" in the JS file. It works perfoming the gate action on the qubit in the defined basis. INCOME: Json: {gate:"string",base:"string"} OUTCOME: Json:{op:"string",img1:"svg",img2:"svg"} NB:The image is given in sgv format because in this way we can send it by json. """ print('start function applyOperators') data = request.get_json() print('=== input data ===') print(data) print('==========') gate= data['f1'] base= data['base'] sett= data['set'] #base="z" print('invoke function for images creation') images = func(gate,base,sett) # call the function that returns the bloch-spheres images if "h" == gate: op = "Hadarmand Gate" elif "x" == gate: op = "Bit Flip Gate" elif "s" == gate: op = "S operator" elif "sdg" == gate: op = "Sc operator" elif "z" == gate: op = "Z operator" elif "t" == gate: op = "T operator" elif "tdg" == gate: op = "Tc operator" # res = json.dumps({"op": op, "img":images[0], "img2": images[1]}) res = {"op": op, "img":images[0], "img2": images[1]} return res # test def func(f1,b,set): """ This function Perform the gate application on the initial state of qubit and then the state tomography, at the same time compute the analytical bloch state. INCOME: f1="string", b="string" fig_data="svg",fig_data2="svg" """ #### Create the bloch-sphere on qutip b1=Bloch() b2=Bloch() ## create the analyical quantum state and perform tranformation ## Add states to the bloch sphere and plot it b1.add_states(analytic(f1,b)) if not set: states=qtomography(f1,b) b2.add_vectors(states) else: ### implements for states=qtomography_s(f1,b) for i in states: b2.add_points(i) b2.add_vectors(np.average(states,axis=0)) ### b2.render() fig_data = print_figure(b2.fig, 'svg') b1.render() fig_data2 = print_figure(b1.fig, 'svg') #b1.show() #b2.show() b1.clear() b2.clear() return fig_data, fig_data2 def qtomography(f1,b): """ This function perform the tomography on the quantum state and starting from the operator and the basis returs the recontruction of the quantum state. See the reference: https://quantumexperience.ng.bluemix.net/proxy/tutorial/full-user-guide/002-The_Weird_and_Wonderful_World_of_the_Qubit/005-The_Bloch_Sphere.html INCOME: f1="char" -> operator acting on the initial state b="char" -> basis on which is expressed the initial state OUTCOME: blo="3d vector" -> resulting vector expressed as 3d vector """ # let's define the Registers q=QuantumRegister(1) c=ClassicalRegister(1) # Build the circuits pre = QuantumCircuit(q, c) ### TEST IF CONTROLS, the values (x,y,z) have to be the same trasmetted from the json if b == "x": pre.h(q) elif b == "y": print(b) pre.h(q) pre.s(q) #elif b == "z": #pre.h(q) pre.barrier() #measuerement circuits # X meas_x = QuantumCircuit(q, c) meas_x.barrier() meas_x.h(q) meas_x.measure(q, c) # Y meas_y = QuantumCircuit(q, c) meas_y.barrier() meas_y.s(q).inverse() meas_y.h(q) meas_y.measure(q, c) # Z meas_z = QuantumCircuit(q, c) meas_z.barrier() meas_z.measure(q, c) bloch_vector = ['x', 'y', 'z'] circuits = [] for exp_index in range(3): # Circuit where it's applied the operator that we want to plot middle = QuantumCircuit(q, c) # let's put here the operator of which we want know the action on the bloch-sphere #### F1 method_to_call = getattr(middle, f1) method_to_call(q) #### circuits.append(pre + middle + meas_x) circuits.append(pre + middle + meas_y) circuits.append(pre + middle + meas_z) # Execute the circuit job = execute(circuits, backend , shots=1024) result = job.result() num=1 # Plot the result blo=[] for exp_index in range(num): bloch = [0, 0, 0] for bloch_index in range(len(bloch_vector)): data = result.get_counts(circuits[exp_index+bloch_index]) try: p0 = data['0']/1024.0 except KeyError: p0 = 0 try: p1 = data['1']/1024.0 except KeyError: p1 = 0 bloch[bloch_index] = p0-p1 blo.append(bloch) return(blo) def analytic(f1,b): print('start function analytic') """ This function compute the analytical calculation of the gate application on the zero qubit INCOME: f1="char" -> argument that defines the operator b="char" -> argument that defines the choosen basis OUTCOME: st="qutip-Bloch().state_vector" -> Bloch() is an element from the quitip library """ #find the right base vec=np.array([1,0]) # vector expressed in the z base h=np.array([[1,1],[1,-1]])*1/m.sqrt(2) s=np.array([[1,0],[0,1j]]) if b=="x": vec=h@vec if b=="y": vec=s@h@vec # find the operator if f1=='h': opp=h elif f1=='x': opp=np.array([[0,1],[1,0]]) elif f1=='z': opp=np.array([[1,0],[0,-1]]) elif f1=='s': opp=s elif f1=='sdg': opp=np.matrix.conjugate(s) elif f1=='t': opp=np.array([[1,0],[0,np.exp(1j*m.pi/4)]]) elif f1=='tdg': opp=np.array([[1,0],[0,np.exp(-1j*m.pi/4)]]) ar=opp@vec st=(ar[0]*basis(2,0)+ar[1]*basis(2,1)).unit() return(st) def qtomography_s(f1,b): shots_sim=128 points=25 list_vec=[] # Define register q=QuantumRegister(1) c=ClassicalRegister(1) # Build the circuits pre = QuantumCircuit(q, c) ### TEST IF CONTROLS, the values (x,y,z) have to be the same trasmetted from the json if b == "x": pre.h(q) elif b == "y": print(b) pre.h(q) pre.s(q) #elif b == "z": #pre.h(q) pre.barrier() #measuerement circuits # X meas_x = QuantumCircuit(q, c) meas_x.barrier() meas_x.h(q) meas_x.measure(q, c) # Y meas_y = QuantumCircuit(q, c) meas_y.barrier() meas_y.s(q).inverse() meas_y.h(q) meas_y.measure(q, c) # Z meas_z = QuantumCircuit(q, c) meas_z.barrier() meas_z.measure(q, c) bloch_vector = ['x', 'y', 'z'] circuits = [] for exp_index in range(3): # Circuit where it's applied the operator that we want to plot middle = QuantumCircuit(q, c) # let's put here the operator of which we want know the action on the bloch-sphere #### F1 method_to_call = getattr(middle, f1) method_to_call(q) #### circuits.append(pre + middle + meas_x) circuits.append(pre + middle + meas_y) circuits.append(pre + middle + meas_z) for i in range(points): #### CLASSICAL SIMULATION job = execute(circuits, backend = Aer.get_backend('qasm_simulator'), shots=shots_sim) #### result = job.result() bloch = [0, 0, 0] nums=[] noise_vec=[] for bloch_index in range(len(bloch_vector)): data = result.get_counts(circuits[bloch_index]) try: p0 = data['0']/shots_sim except KeyError: p0 = 0 try: p1 = data['1']/shots_sim except KeyError: p1 = 0 bloch[bloch_index] = p0-p1 list_vec.append(bloch) return list_vec
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Noise model class for Qiskit Aer simulators. """ import json import logging from typing import Optional from warnings import warn, catch_warnings, filterwarnings from numpy import ndarray from qiskit.circuit import Instruction, Delay from qiskit.providers.exceptions import BackendPropertyError from qiskit.providers.models import BackendProperties from qiskit.transpiler import PassManager from .device.models import _excited_population, _truncate_t2_value from .device.models import basic_device_gate_errors from .device.models import basic_device_readout_errors from .errors.quantum_error import QuantumError from .errors.readout_error import ReadoutError from .noiseerror import NoiseError from .passes import RelaxationNoisePass from ..backends.backend_utils import BASIS_GATES logger = logging.getLogger(__name__) class AerJSONEncoder(json.JSONEncoder): """ JSON encoder for NumPy arrays and complex numbers. This functions as the standard JSON Encoder but adds support for encoding: complex numbers z as lists [z.real, z.imag] ndarrays as nested lists. """ # pylint: disable=method-hidden,arguments-differ def default(self, obj): if isinstance(obj, ndarray): return obj.tolist() if isinstance(obj, complex): return [obj.real, obj.imag] if hasattr(obj, "to_dict"): return obj.to_dict() return super().default(obj) class QuantumErrorLocation(Instruction): """Instruction for referencing a multi-qubit error in a NoiseModel""" _directive = True def __init__(self, qerror): """Construct a new quantum error location instruction. Args: qerror (QuantumError): the quantum error to reference. """ super().__init__("qerror_loc", qerror.num_qubits, 0, [], label=qerror.id) class NoiseModel: """Noise model class for Qiskit Aer simulators. This class is used to represent noise model for the :class:`~qiskit.providers.aer.QasmSimulator`. It can be used to construct custom noise models for simulator, or to automatically generate a basic device noise model for an IBMQ backend. See the :mod:`~qiskit.providers.aer.noise` module documentation for additional information. **Example: Basic device noise model** An approximate :class:`NoiseModel` can be generated automatically from the properties of real device backends from the IBMQ provider using the :meth:`~NoiseModel.from_backend` method. .. code-block:: python from qiskit import IBMQ, Aer from qiskit.providers.aer.noise import NoiseModel provider = IBMQ.load_account() backend = provider.get_backend('ibmq_vigo') noise_model = NoiseModel.from_backend(backend) print(noise_model) **Example: Custom noise model** Custom noise models can be used by adding :class:`QuantumError` to circuit gate, reset or measure instructions, and :class:`ReadoutError` to measure instructions. .. code-block:: python import qiskit.providers.aer.noise as noise # Error probabilities prob_1 = 0.001 # 1-qubit gate prob_2 = 0.01 # 2-qubit gate # Depolarizing quantum errors error_1 = noise.depolarizing_error(prob_1, 1) error_2 = noise.depolarizing_error(prob_2, 2) # Add errors to noise model noise_model = noise.NoiseModel() noise_model.add_all_qubit_quantum_error(error_1, ['rz', 'sx', 'x']) noise_model.add_all_qubit_quantum_error(error_2, ['cx']) print(noise_model) """ # Checks for standard 1-3 qubit instructions _1qubit_instructions = set([ 'u1', 'u2', 'u3', 'u', 'p', 'r', 'rx', 'ry', 'rz', 'id', 'x', 'y', 'z', 'h', 's', 'sdg', 'sx', 'sxdg', 't', 'tdg']) _2qubit_instructions = set([ 'swap', 'cx', 'cy', 'cz', 'csx', 'cp', 'cu', 'cu1', 'cu2', 'cu3', 'rxx', 'ryy', 'rzz', 'rzx']) _3qubit_instructions = set(['ccx', 'cswap']) def __init__(self, basis_gates=None): """Initialize an empty noise model. Args: basis_gates (list[str] or None): Specify an initial basis_gates for the noise model. If None a default value of ['id', 'rz', 'sx', 'cx'] is used (Default: None). Additional Information: Errors added to the noise model will have their instruction appended to the noise model basis_gates if the instruction is in the :class:`~qiskit.providers.aer.QasmSimulator` basis_gates. If the instruction is not in the :class:`~qiskit.providers.aer.QasmSimulator` basis_gates it is assumed to be a label for a standard gate, and that gate should be added to the `NoiseModel` basis_gates either using the init method, or the :meth:`add_basis_gates` method. """ if basis_gates is None: # Default basis gates is id, rz, sx, cx so that all standard # non-identity instructions can be unrolled to rz, sx, cx, # and identities won't be unrolled self._basis_gates = set(['id', 'rz', 'sx', 'cx']) else: self._basis_gates = set( name for name, _ in self._instruction_names_labels(basis_gates)) # Store gates with a noise model defined self._noise_instructions = set() # Store qubits referenced in noise model. # These include gate qubits in local quantum and readout errors, # and both gate and noise qubits for non-local quantum errors. self._noise_qubits = set() # Default (all-qubit) quantum errors are stored as: # dict(str: QuantumError) # where they keys are the instruction str label self._default_quantum_errors = {} # Local quantum errors are stored as: # dict(str: dict(tuple: QuantumError)) # where the outer keys are the instruction str label and the # inner dict keys are the gate qubits self._local_quantum_errors = {} # Non-local quantum errors are stored as: # dict(str: dict(tuple: dict(tuple: QuantumError))) # where the outer keys are the instruction str label, the middle dict # keys are the gate qubits, and the inner most dict keys are # the noise qubits. self._nonlocal_quantum_errors = {} # Default (all-qubit) readout error is stored as a single # ReadoutError object since there may only be one defined. self._default_readout_error = None # Local readout errors are stored as: # dict(tuple: ReadoutError) # where the dict keys are the gate qubits. self._local_readout_errors = {} # Custom noise passes self._custom_noise_passes = [] @property def basis_gates(self): """Return basis_gates for compiling to the noise model.""" # Convert noise instructions to basis_gates string return sorted(self._basis_gates) @property def noise_instructions(self): """Return the set of noisy instructions for this noise model.""" return sorted(self._noise_instructions) @property def noise_qubits(self): """Return the set of noisy qubits for this noise model.""" return sorted(self._noise_qubits) @classmethod def from_backend(cls, backend, gate_error=True, readout_error=True, thermal_relaxation=True, temperature=0, gate_lengths=None, gate_length_units='ns', standard_gates=None, warnings=True): """Return a noise model derived from a devices backend properties. This function generates a noise model based on: * 1 and 2 qubit gate errors consisting of a :func:`depolarizing_error` followed by a :func:`thermal_relaxation_error`. * Single qubit :class:`ReadoutError` on all measurements. The Error error parameters are tuned for each individual qubit based on the :math:`T_1`, :math:`T_2`, frequency and readout error parameters for each qubit, and the gate error and gate time parameters for each gate obtained from the device backend properties. **Additional Information** The noise model includes the following errors: * If ``readout_error=True`` include single qubit readout errors on measurements. * If ``gate_error=True`` and ``thermal_relaxation=True`` include: * Single-qubit gate errors consisting of a :func:`depolarizing_error` followed by a :func:`thermal_relaxation_error` for the qubit the gate acts on. * Two-qubit gate errors consisting of a 2-qubit :func:`depolarizing_error` followed by single qubit :func:`thermal_relaxation_error` on each qubit participating in the gate. * If ``gate_error=True`` is ``True`` and ``thermal_relaxation=False``: * An N-qubit :func:`depolarizing_error` on each N-qubit gate. * If ``gate_error=False`` and ``thermal_relaxation=True`` include single-qubit :func:`thermal_relaxation_errors` on each qubits participating in a multi-qubit gate. For best practice in simulating a backend make sure that the circuit is compiled using the set of basis gates in the noise module by setting ``basis_gates=noise_model.basis_gates`` and using the device coupling map with ``coupling_map=backend.configuration().coupling_map`` **Specifying custom gate times** The ``gate_lengths`` kwarg can be used to specify custom gate times to add gate errors using the :math:`T_1` and :math:`T_2` values from the backend properties. This should be passed as a list of tuples ``gate_lengths=[(name, value), ...]`` where ``name`` is the gate name string, and ``value`` is the gate time in nanoseconds. If a custom gate is specified that already exists in the backend properties, the ``gate_lengths`` value will override the gate time value from the backend properties. If non-default values are used gate_lengths should be a list Args: backend (BackendV1): backend. gate_error (bool): Include depolarizing gate errors (Default: True). readout_error (Bool): Include readout errors in model (Default: True). thermal_relaxation (Bool): Include thermal relaxation errors (Default: True). temperature (double): qubit temperature in milli-Kelvin (mK) for thermal relaxation errors (Default: 0). gate_lengths (list): Custom gate times for thermal relaxation errors. Used to extend or override the gate times in the backend properties (Default: None)) gate_length_units (str): Time units for gate length values in gate_lengths. Can be 'ns', 'ms', 'us', or 's' (Default: 'ns'). standard_gates (bool): DEPRECATED, If true return errors as standard qobj gates. If false return as unitary qobj instructions (Default: None) warnings (bool): Display warnings (Default: True). Returns: NoiseModel: An approximate noise model for the device backend. Raises: NoiseError: If the input backend is not valid. """ backend_interface_version = getattr(backend, "version", None) if not isinstance(backend_interface_version, int): backend_interface_version = 0 if backend_interface_version == 2: raise NoiseError( "NoiseModel.from_backend does not currently support V2 Backends.") if backend_interface_version <= 1: properties = backend.properties() configuration = backend.configuration() basis_gates = configuration.basis_gates num_qubits = configuration.num_qubits dt = getattr(configuration, "dt", 0) if not properties: raise NoiseError('Qiskit backend {} does not have a ' 'BackendProperties'.format(backend)) elif isinstance(backend, BackendProperties): warn( 'Passing BackendProperties instead of a "backend" object ' 'has been deprecated as of qiskit-aer 0.10.0 and will be ' 'removed no earlier than 3 months from that release date. ' 'Duration dependent delay relaxation noise requires a ' 'backend object.', DeprecationWarning, stacklevel=2) properties = backend basis_gates = set() for prop in properties.gates: basis_gates.add(prop.gate) basis_gates = list(basis_gates) num_qubits = len(properties.qubits) dt = 0 # disable delay noise if dt is unknown else: raise NoiseError('{} is not a Qiskit backend or' ' BackendProperties'.format(backend)) noise_model = NoiseModel(basis_gates=basis_gates) # Add single-qubit readout errors if readout_error: for qubits, error in basic_device_readout_errors(properties): noise_model.add_readout_error(error, qubits, warnings=warnings) if standard_gates is not None: warn( '"standard_gates" option has been deprecated as of qiskit-aer 0.10.0' ' and will be removed no earlier than 3 months from that release date.', DeprecationWarning, stacklevel=2) # Add gate errors with catch_warnings(): filterwarnings( "ignore", category=DeprecationWarning, module="qiskit.providers.aer.noise.device.models" ) gate_errors = basic_device_gate_errors( properties, gate_error=gate_error, thermal_relaxation=thermal_relaxation, gate_lengths=gate_lengths, gate_length_units=gate_length_units, temperature=temperature, standard_gates=standard_gates, warnings=warnings) for name, qubits, error in gate_errors: noise_model.add_quantum_error(error, name, qubits, warnings=warnings) if thermal_relaxation: # Add delay errors via RelaxationNiose pass try: excited_state_populations = [ _excited_population( freq=properties.frequency(q), temperature=temperature ) for q in range(num_qubits)] except BackendPropertyError: excited_state_populations = None try: t1s = [properties.t1(q) for q in range(num_qubits)] t2s = [properties.t2(q) for q in range(num_qubits)] delay_pass = RelaxationNoisePass( t1s=t1s, t2s=[_truncate_t2_value(t1, t2) for t1, t2 in zip(t1s, t2s)], dt=dt, op_types=Delay, excited_state_populations=excited_state_populations ) noise_model._custom_noise_passes.append(delay_pass) except BackendPropertyError: # Device does not have the required T1 or T2 information # in its properties pass return noise_model def is_ideal(self): # pylint: disable=too-many-return-statements """Return True if the noise model has no noise terms.""" # Get default errors if self._default_quantum_errors: return False if self._default_readout_error: return False if self._local_quantum_errors: return False if self._local_readout_errors: return False if self._nonlocal_quantum_errors: return False if self._custom_noise_passes: return False return True def __repr__(self): """Noise model repr""" return "<NoiseModel on {}>".format(list(self._noise_instructions)) def __str__(self): """Noise model string representation""" # Check if noise model is ideal if self.is_ideal(): return "NoiseModel: Ideal" # Get default errors default_error_ops = [] for inst in self._default_quantum_errors: default_error_ops.append('{}'.format(inst)) if self._default_readout_error is not None: if 'measure' not in default_error_ops: default_error_ops.append('measure') # Get local errors local_error_ops = [] for inst, dic in self._local_quantum_errors.items(): for qubits in dic.keys(): local_error_ops.append((inst, qubits)) for qubits in self._local_readout_errors: tmp = ('measure', qubits) if tmp not in local_error_ops: local_error_ops.append(tmp) # Get nonlocal errors nonlocal_error_ops = [] for inst, dic in self._nonlocal_quantum_errors.items(): for qubits, errors in dic.items(): for noise_qubits in errors: nonlocal_error_ops.append((inst, qubits, noise_qubits)) output = "NoiseModel:" output += "\n Basis gates: {}".format(self.basis_gates) if self._noise_instructions: output += "\n Instructions with noise: {}".format( list(self._noise_instructions)) if self._noise_qubits: output += "\n Qubits with noise: {}".format( list(self._noise_qubits)) if default_error_ops: output += "\n All-qubits errors: {}".format(default_error_ops) if local_error_ops: output += "\n Specific qubit errors: {}".format( local_error_ops) if nonlocal_error_ops: output += "\n Non-local specific qubit errors: {}".format( nonlocal_error_ops) return output def __eq__(self, other): """Test if two noise models are equal.""" # This returns True if both noise models have: # the same basis_gates # the same noise_qubits # the same noise_instructions if (not isinstance(other, NoiseModel) or self.basis_gates != other.basis_gates or self.noise_qubits != other.noise_qubits or self.noise_instructions != other.noise_instructions): return False # Check default readout errors is equal if not self._readout_errors_equal(other): return False # Check quantum errors equal if not self._all_qubit_quantum_errors_equal(other): return False if not self._local_quantum_errors_equal(other): return False if not self._nonlocal_quantum_errors_equal(other): return False # If we made it here they are equal return True def reset(self): """Reset the noise model.""" self.__init__() def add_basis_gates(self, instructions, warnings=False): """Add additional gates to the noise model basis_gates. This should be used to add any gates that are identified by a custom gate label in the noise model. Args: instructions (list[str] or list[Instruction]): the instructions error applies to. warnings (bool): [DEPRECATED] display warning if instruction is not in QasmSimulator basis_gates (Default: False). """ for name, _ in self._instruction_names_labels(instructions): # If the instruction is in the default basis gates for the # AerSimulator we add it to the basis gates. if name in BASIS_GATES['automatic']: if name not in ['measure', 'reset', 'initialize', 'kraus', 'superop', 'roerror']: self._basis_gates.add(name) elif warnings: warn('"warnings" option has been deprecated as of qiskit-aer 0.10.0' ' and will be removed no earlier than 3 months from that release date.', DeprecationWarning, stacklevel=2) logger.warning( "Warning: Adding a gate \"%s\" to basis_gates which is " "not in AerSimulator basis_gates.", name) def add_all_qubit_quantum_error(self, error, instructions, warnings=True): """ Add a quantum error to the noise model that applies to all qubits. Args: error (QuantumError): the quantum error object. instructions (str or list[str] or Instruction or list[Instruction]): the instructions error applies to. warnings (bool): Display warning if appending to an instruction that already has an error (Default: True). Raises: NoiseError: if the input parameters are invalid. Additional Information: If the error object is ideal it will not be added to the model. """ # Format input as QuantumError if not isinstance(error, QuantumError): try: error = QuantumError(error) except NoiseError: raise NoiseError("Input is not a valid quantum error.") # Check if error is ideal and if so don't add to the noise model if error.ideal(): return # Add instructions for name, label in self._instruction_names_labels(instructions): self._check_number_of_qubits(error, name) if label in self._default_quantum_errors: new_error = self._default_quantum_errors[label].compose(error) self._default_quantum_errors[label] = new_error if warnings: logger.warning( "WARNING: all-qubit error already exists for " "instruction \"%s\", " "composing with additional error.", label) else: self._default_quantum_errors[label] = error # Check if a specific qubit error has been applied for this instruction if label in self._local_quantum_errors: local_qubits = self._keys2str( self._local_quantum_errors[label].keys()) if warnings: logger.warning( "WARNING: all-qubit error for instruction " "\"%s\" will not apply to qubits: " "%s as specific error already exists.", label, local_qubits) self._noise_instructions.add(label) self.add_basis_gates(name) def add_quantum_error(self, error, instructions, qubits, warnings=True): """ Add a quantum error to the noise model. Args: error (QuantumError): the quantum error object. instructions (str or list[str] or Instruction or list[Instruction]): the instructions error applies to. qubits (Sequence[int]): qubits instruction error applies to. warnings (bool): Display warning if appending to an instruction that already has an error (Default: True). Raises: NoiseError: if the input parameters are invalid. Additional Information: If the error object is ideal it will not be added to the model. """ # Error checking if not isinstance(error, QuantumError): try: error = QuantumError(error) except NoiseError: raise NoiseError("Input is not a valid quantum error.") try: qubits = tuple(qubits) except TypeError as ex: raise NoiseError("Qubits must be convertible to a tuple of integers") from ex # Check if error is ideal and if so don't add to the noise model if error.ideal(): return # Add noise qubits for qubit in qubits: self._noise_qubits.add(qubit) # Add instructions for name, label in self._instruction_names_labels(instructions): self._check_number_of_qubits(error, name) if not isinstance(label, str): raise NoiseError("Qobj invalid instructions.") # Check number of qubits is correct for standard instructions self._check_number_of_qubits(error, name) if label in self._local_quantum_errors: qubit_dict = self._local_quantum_errors[label] else: qubit_dict = {} # Convert qubits list to hashable string if error.num_qubits != len(qubits): raise NoiseError("Number of qubits ({}) does not match " " the error size ({})".format( len(qubits), error.num_qubits)) if qubits in qubit_dict: new_error = qubit_dict[qubits].compose(error) qubit_dict[qubits] = new_error if warnings: logger.warning( "WARNING: quantum error already exists for " "instruction \"%s\" on qubits %s " ", appending additional error.", label, qubits) else: qubit_dict[qubits] = error # Add updated dictionary self._local_quantum_errors[label] = qubit_dict # Check if all-qubit error is already defined for this instruction if label in self._default_quantum_errors: if warnings: logger.warning( "WARNING: Specific error for instruction \"%s\" " "on qubits %s overrides previously defined " "all-qubit error for these qubits.", label, qubits) self._noise_instructions.add(label) self.add_basis_gates(name) def add_nonlocal_quantum_error(self, error, instructions, qubits, noise_qubits, warnings=True): """ Add a non-local quantum error to the noise model (DEPRECATED). .. deprecated:: 0.9.0 Adding nonlocal noise to a noise model is deprecated and will be removed no earlier than 3 months from the qiskit-aer 0.9.0 release date. To add non-local noise to a circuit you should write a custom qiskit transpiler pass. Args: error (QuantumError): the quantum error object. instructions (str or list[str] or Instruction or list[Instruction]): the instructions error applies to. qubits (Sequence[int]): qubits instruction error applies to. noise_qubits (Sequence[int]): Specify the exact qubits the error should be applied to if different to the instruction qubits. warnings (bool): Display warning if appending to an instruction that already has an error (Default: True). Raises: NoiseError: if the input parameters are invalid. Additional Information: If the error object is ideal it will not be added to the model. """ warn('Adding nonlocal noise to a noise model is deprecated as of' ' qiskit-aer 0.9.0 and will be removed no earlier than 3' ' months from that release date. To add non-local noise to' ' a circuit you should write a custom qiskit transpiler pass.', DeprecationWarning) # Error checking if not isinstance(error, QuantumError): try: error = QuantumError(error) except NoiseError: raise NoiseError("Input is not a valid quantum error.") try: qubits = tuple(qubits) noise_qubits = tuple(noise_qubits) except TypeError as ex: raise NoiseError("Qubits must be convertible to a tuple of integers") from ex # Check if error is ideal and if so don't add to the noise model if error.ideal(): return # Add noise qubits for qubit in qubits: self._noise_qubits.add(qubit) for qubit in noise_qubits: self._noise_qubits.add(qubit) # Add instructions for name, label in self._instruction_names_labels(instructions): if label in self._nonlocal_quantum_errors: gate_qubit_dict = self._nonlocal_quantum_errors[label] else: gate_qubit_dict = {} if qubits in gate_qubit_dict: noise_qubit_dict = gate_qubit_dict[qubits] if noise_qubits in noise_qubit_dict: new_error = noise_qubit_dict[noise_qubits].compose(error) noise_qubit_dict[noise_qubits] = new_error else: noise_qubit_dict[noise_qubits] = error gate_qubit_dict[qubits] = noise_qubit_dict if warnings: logger.warning( "Warning: nonlocal error already exists for " "instruction \"%s\" on qubits %s." "Composing additional error.", label, qubits) else: gate_qubit_dict[qubits] = {noise_qubits: error} # Add updated dictionary self._nonlocal_quantum_errors[label] = gate_qubit_dict self._noise_instructions.add(label) self.add_basis_gates(name, warnings=False) def add_all_qubit_readout_error(self, error, warnings=True): """ Add a single-qubit readout error that applies measure on all qubits. Args: error (ReadoutError): the quantum error object. warnings (bool): Display warning if appending to an instruction that already has an error (Default: True) Raises: NoiseError: if the input parameters are invalid. Additional Information: If the error object is ideal it will not be added to the model. """ # Error checking if not isinstance(error, ReadoutError): try: error = ReadoutError(error) except NoiseError: raise NoiseError("Input is not a valid readout error.") # Check if error is ideal and if so don't add to the noise model if error.ideal(): return # Check number of qubits is correct for standard instructions if error.number_of_qubits != 1: raise NoiseError( "All-qubit readout errors must defined as single-qubit errors." ) if self._default_readout_error is not None: if warnings: logger.warning( "WARNING: all-qubit readout error already exists, " "overriding with new readout error.") self._default_readout_error = error # Check if a specific qubit error has been applied for this instruction if self._local_readout_errors: local_qubits = self._keys2str(self._local_readout_errors.keys()) if warnings: logger.warning( "WARNING: The all-qubit readout error will not " "apply to measure of qubits qubits: %s " "as specific readout errors already exist.", local_qubits) self._noise_instructions.add("measure") def add_readout_error(self, error, qubits, warnings=True): """ Add a readout error to the noise model. Args: error (ReadoutError): the quantum error object. qubits (list[int] or tuple[int]): qubits instruction error applies to. warnings (bool): Display warning if appending to an instruction that already has an error [Default: True] Raises: NoiseError: if the input parameters are invalid. Additional Information: If the error object is ideal it will not be added to the model. """ # Error checking if not isinstance(error, ReadoutError): try: error = ReadoutError(error) except NoiseError: raise NoiseError("Input is not a valid readout error.") try: qubits = tuple(qubits) except TypeError as ex: raise NoiseError("Qubits must be convertible to a tuple of integers") from ex # Check if error is ideal and if so don't add to the noise model if error.ideal(): return # Add noise qubits for qubit in qubits: self._noise_qubits.add(qubit) # Check error matches qubit size if error.number_of_qubits != len(qubits): raise NoiseError( "Number of qubits ({}) does not match the readout " "error size ({})".format(len(qubits), error.number_of_qubits)) # Check if we are overriding a previous error if qubits in self._local_readout_errors: if warnings: logger.warning( "WARNING: readout error already exists for qubits " "%s, overriding with new readout error.", qubits) self._local_readout_errors[qubits] = error # Check if all-qubit readout error is already defined if self._default_readout_error is not None: if warnings: logger.warning( "WARNING: Specific readout error on qubits " "%s overrides previously defined " "all-qubit readout error for these qubits.", qubits) self._noise_instructions.add("measure") def to_dict(self, serializable=False): """ Return the noise model as a dictionary. Args: serializable (bool): if `True`, return a dict containing only types that can be serializable by the stdlib `json` module. Returns: dict: a dictionary for a noise model. """ error_list = [] # Add default quantum errors for name, error in self._default_quantum_errors.items(): error_dict = error.to_dict() error_dict["operations"] = [name] error_list.append(error_dict) # Add specific qubit errors for name, qubit_dict in self._local_quantum_errors.items(): for qubits, error in qubit_dict.items(): error_dict = error.to_dict() error_dict["operations"] = [name] error_dict["gate_qubits"] = [qubits] error_list.append(error_dict) # Add non-local errors for name, qubit_dict in self._nonlocal_quantum_errors.items(): for qubits, noise_qubit_dict in qubit_dict.items(): for noise_qubits, error in noise_qubit_dict.items(): error_dict = error.to_dict() error_dict["operations"] = [name] error_dict["gate_qubits"] = [qubits] error_dict["noise_qubits"] = [noise_qubits] error_list.append(error_dict) # Add default readout error if self._default_readout_error is not None: error_dict = self._default_readout_error.to_dict() error_list.append(error_dict) # Add local readout error for qubits, error in self._local_readout_errors.items(): error_dict = error.to_dict() error_dict["gate_qubits"] = [qubits] error_list.append(error_dict) ret = {"errors": error_list} if serializable: ret = json.loads(json.dumps(ret, cls=AerJSONEncoder)) return ret @staticmethod def from_dict(noise_dict): """ Load NoiseModel from a dictionary. Args: noise_dict (dict): A serialized noise model. Returns: NoiseModel: the noise model. Raises: NoiseError: if dict cannot be converted to NoiseModel. """ warn('from_dict has been deprecated as of qiskit-aer 0.10.0' ' and will be removed no earlier than 3 months from that release date.', DeprecationWarning, stacklevel=2) # Return noise model noise_model = NoiseModel() # Get error terms errors = noise_dict.get('errors', []) for error in errors: error_type = error['type'] # Add QuantumError if error_type == 'qerror': noise_ops = tuple( zip(error['instructions'], error['probabilities'])) instruction_names = error['operations'] all_gate_qubits = error.get('gate_qubits', None) all_noise_qubits = error.get('noise_qubits', None) with catch_warnings(): filterwarnings("ignore", category=DeprecationWarning, module="qiskit.providers.aer.noise") qerror = QuantumError(noise_ops) qerror._id = error.get('id', None) or qerror.id if all_gate_qubits is not None: for gate_qubits in all_gate_qubits: # Load non-local quantum error if all_noise_qubits is not None: for noise_qubits in all_noise_qubits: noise_model.add_nonlocal_quantum_error( qerror, instruction_names, gate_qubits, noise_qubits, warnings=False) # Add local quantum error else: noise_model.add_quantum_error( qerror, instruction_names, gate_qubits, warnings=False) else: # Add all-qubit quantum error noise_model.add_all_qubit_quantum_error( qerror, instruction_names, warnings=False) # Add ReadoutError elif error_type == 'roerror': probabilities = error['probabilities'] all_gate_qubits = error.get('gate_qubits', None) roerror = ReadoutError(probabilities) # Add local readout error if all_gate_qubits is not None: for gate_qubits in all_gate_qubits: noise_model.add_readout_error( roerror, gate_qubits, warnings=False) # Add all-qubit readout error else: noise_model.add_all_qubit_readout_error( roerror, warnings=False) # Invalid error type else: raise NoiseError("Invalid error type: {}".format(error_type)) return noise_model def _instruction_names_labels(self, instructions): """Return two lists of instruction name strings and label strings.""" if not isinstance(instructions, (list, tuple)): instructions = [instructions] names_labels = [] for inst in instructions: # If instruction does not have a label we use the name # as the label if isinstance(inst, Instruction): name = inst.name label = getattr(inst, 'label', inst.name) names_labels.append((name, label)) elif isinstance(inst, str): names_labels.append((inst, inst)) else: raise NoiseError('Invalid instruction type {}'.format(inst)) return names_labels def _check_number_of_qubits(self, error, name): """ Check if error is corrected number of qubits for standard instruction. Args: error (QuantumError): the quantum error object. name (str): qobj instruction name to apply error to. Raises: NoiseError: If instruction and error qubit number do not match. """ def error_message(gate_qubits): msg = "{} qubit QuantumError".format(error.num_qubits) + \ " cannot be applied to {} qubit".format(gate_qubits) + \ " instruction \"{}\".".format(name) return msg if name in self._1qubit_instructions and error.num_qubits != 1: raise NoiseError(error_message(1)) if name in self._2qubit_instructions and error.num_qubits != 2: raise NoiseError(error_message(2)) if name in self._3qubit_instructions and error.num_qubits != 3: raise NoiseError(error_message(3)) def _keys2str(self, keys): """Convert dicitonary keys to comma seperated print string.""" tmp = "".join(["{}, ".format(key) for key in keys]) return tmp[:-2] def _readout_errors_equal(self, other): """Check two noise models have equal readout errors""" # Check default readout error is equal if self._default_readout_error != other._default_readout_error: return False # Check local readout errors are equal if sorted(self._local_readout_errors.keys()) != sorted( other._local_readout_errors.keys()): return False for key in self._local_readout_errors: if self._local_readout_errors[key] != other._local_readout_errors[ key]: return False return True def _all_qubit_quantum_errors_equal(self, other): """Check two noise models have equal local quantum errors""" if sorted(self._default_quantum_errors.keys()) != sorted( other._default_quantum_errors.keys()): return False for key in self._default_quantum_errors: if self._default_quantum_errors[ key] != other._default_quantum_errors[key]: return False return True def _local_quantum_errors_equal(self, other): """Check two noise models have equal local quantum errors""" if sorted(self._local_quantum_errors.keys()) != sorted( other._local_quantum_errors.keys()): return False for key in self._local_quantum_errors: inner_dict1 = self._local_quantum_errors[key] inner_dict2 = other._local_quantum_errors[key] if sorted(inner_dict1.keys()) != sorted(inner_dict2.keys()): return False for inner_key in inner_dict1: if inner_dict1[inner_key] != inner_dict2[inner_key]: return False if self._local_quantum_errors[key] != other._local_quantum_errors[ key]: return False return True def _nonlocal_quantum_errors_equal(self, other): """Check two noise models have equal non-local quantum errors""" if sorted(self._nonlocal_quantum_errors.keys()) != sorted( other._nonlocal_quantum_errors.keys()): return False for key in self._nonlocal_quantum_errors: inner_dict1 = self._nonlocal_quantum_errors[key] inner_dict2 = other._nonlocal_quantum_errors[key] if sorted(inner_dict1.keys()) != sorted(inner_dict2.keys()): return False for inner_key in inner_dict1: iinner_dict1 = inner_dict1[inner_key] iinner_dict2 = inner_dict2[inner_key] if sorted(iinner_dict1.keys()) != sorted(iinner_dict2.keys()): return False for iinner_key in iinner_dict1: if iinner_dict1[iinner_key] != iinner_dict2[iinner_key]: return False return True def _pass_manager(self) -> Optional[PassManager]: """ Return the pass manager that add custom noises defined as noise passes (stored in the _custom_noise_passes field). Note that the pass manager does not include passes to add other noises (stored in the different field). """ passes = [] passes.extend(self._custom_noise_passes) if len(passes) > 0: return PassManager(passes) return None
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
MonitSharma
import pennylane as qml from pennylane import numpy as np dev_gaussian = qml.device("default.gaussian", wires=1) @qml.qnode(dev_gaussian) def mean_photon_gaussian(mag_alpha, phase_alpha, phi): qml.Displacement(mag_alpha, phase_alpha, wires=0) qml.Rotation(phi, wires=0) return qml.expval(qml.NumberOperator(0)) def cost(params): return (mean_photon_gaussian(params[0], params[1], params[2]) - 1.0) ** 2 init_params = np.array([0.015, 0.02, 0.005], requires_grad=True) print(cost(init_params)) # initialise the optimizer opt = qml.GradientDescentOptimizer(stepsize=0.1) # set the number of steps steps = 20 # set the initial parameter values params = init_params for i in range(steps): # update the circuit parameters params = opt.step(cost, params) print("Cost after step {:5d}: {:8f}".format(i + 1, cost(params))) print("Optimized mag_alpha:{:8f}".format(params[0])) print("Optimized phase_alpha:{:8f}".format(params[1])) print("Optimized phi:{:8f}".format(params[2]))
https://github.com/icarosadero/maxima_function_qiskit
icarosadero
%matplotlib inline from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * provider = IBMQ.load_account() circ = QuantumCircuit(9,9) #Hadamard for i in [6,7,8]: circ.h(i) circ.barrier(range(9)) #Function circ.cx(6,5) circ.ccx(6,7,4) circ.cx(8,4) circ.barrier(range(9)) for i,j in zip([3,4,5],[0,1,2]): circ.x(i) circ.ch(i,j) circ.x(i) circ.barrier(range(9)) circ.measure(range(9),range(9)) circ.draw("mpl") nruns = 2048 backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(circ, backend_sim, shots=nruns) result_sim = job_sim.result() counts = result_sim.get_counts(circ) plot_histogram(counts) result_raw = sorted(counts.items(), key=lambda x: x[1], reverse=True) result = list(map(lambda x: [x[0][:3],x[0][3:6],x[0][6:],x[1]/nruns],result_raw)) result
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Clifford, random_clifford qc = QuantumCircuit(3) cliff = random_clifford(2) qc.append(cliff, [0, 1]) qc.ccx(0, 1, 2) qc.draw('mpl')
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2019, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # ============================================================================= """Test Quantum Gradient Framework""" import unittest from test.python.opflow import QiskitOpflowTestCase from itertools import product import numpy as np from ddt import ddt, data, idata, unpack from qiskit import QuantumCircuit, QuantumRegister, BasicAer from qiskit.test import slow_test from qiskit.utils import QuantumInstance from qiskit.exceptions import MissingOptionalLibraryError from qiskit.utils import algorithm_globals from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import CG from qiskit.opflow import ( I, X, Y, Z, StateFn, CircuitStateFn, ListOp, CircuitSampler, TensoredOp, SummedOp, ) from qiskit.opflow.gradients import Gradient, NaturalGradient, Hessian from qiskit.opflow.gradients.qfi import QFI from qiskit.opflow.gradients.circuit_gradients import LinComb from qiskit.opflow.gradients.circuit_qfis import LinCombFull, OverlapBlockDiag, OverlapDiag from qiskit.circuit import Parameter from qiskit.circuit import ParameterVector from qiskit.circuit.library import RealAmplitudes, EfficientSU2 from qiskit.utils import optionals if optionals.HAS_JAX: import jax.numpy as jnp @ddt class TestGradients(QiskitOpflowTestCase): """Test Qiskit Gradient Framework""" def setUp(self): super().setUp() algorithm_globals.random_seed = 50 @data("lin_comb", "param_shift", "fin_diff") def test_gradient_p(self, method): """Test the state gradient for p |psi> = 1/sqrt(2)[[1, exp(ia)]] Tr(|psi><psi|Z) = 0 Tr(|psi><psi|X) = cos(a) d<H>/da = - 0.5 sin(a) """ ham = 0.5 * X - 1 * Z a = Parameter("a") params = a q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.p(a, q[0]) op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) state_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [{a: np.pi / 4}, {a: 0}, {a: np.pi / 2}] correct_values = [-0.5 / np.sqrt(2), 0, -0.5] for i, value_dict in enumerate(values_dict): np.testing.assert_array_almost_equal( state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1 ) @data("lin_comb", "param_shift", "fin_diff") def test_gradient_u(self, method): """Test the state gradient for U Tr(|psi><psi|Z) = - 0.5 sin(a)cos(c) Tr(|psi><psi|X) = cos^2(a/2) cos(b+c) - sin^2(a/2) cos(b-c) """ ham = 0.5 * X - 1 * Z a = Parameter("a") b = Parameter("b") c = Parameter("c") q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.u(a, b, c, q[0]) op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) params = [a, b, c] state_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [{a: np.pi / 4, b: 0, c: 0}, {a: np.pi / 4, b: np.pi / 4, c: np.pi / 4}] correct_values = [[0.3536, 0, 0], [0.3232, -0.42678, -0.92678]] for i, value_dict in enumerate(values_dict): np.testing.assert_array_almost_equal( state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1 ) # Tr(|psi><psi|Z) = - 0.5 sin(a)cos(c) # Tr(|psi><psi|X) = cos^2(a/2) cos(b+c) - sin^2(a/2) cos(b-c) # dTr(|psi><psi|H)/da = 0.5(cos(2a)) + 0.5() q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.u(a, a, a, q[0]) op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) params = [a] state_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [{a: np.pi / 4}, {a: np.pi / 2}] correct_values = [[-1.03033], [-1]] for i, value_dict in enumerate(values_dict): np.testing.assert_array_almost_equal( state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1 ) @data("lin_comb", "param_shift") def test_gradient_efficient_su2(self, method): """Test the state gradient for EfficientSU2""" observable = SummedOp( [ 0.2252 * (I ^ I), 0.5716 * (Z ^ Z), 0.3435 * (I ^ Z), -0.4347 * (Z ^ I), 0.091 * (Y ^ Y), 0.091 * (X ^ X), ] ).reduce() d = 2 ansatz = EfficientSU2(observable.num_qubits, reps=d) # Define a set of initial parameters parameters = ansatz.ordered_parameters operator = ~StateFn(observable) @ StateFn(ansatz) values_dict = [ {param: np.pi / 4 for param in parameters}, {param: np.pi / 2 for param in parameters}, ] correct_values = [ [ -0.38617868191914206 + 0j, -0.014055349300198364 + 0j, -0.06385049040183734 + 0j, 0.13620629212619334 + 0j, -0.15180743339043595 + 0j, -0.2378393653877069 + 0j, 0.0024060546876464237 + 0j, 0.09977051760912459 + 0j, 0.40357721595080603 + 0j, 0.010453846462186653 + 0j, -0.04578581127401049 + 0j, 0.04578581127401063 + 0j, ], [ 0.4346999999999997 + 0j, 0.0, 0.0, 0.6625999999999991 + 0j, 0.0, 0.0, -0.34349999999999986 + 0j, 0.0, 0.0, 0.0, 0.0, 0.0, ], ] state_grad = Gradient(method).convert(operator, parameters) for i, value_dict in enumerate(values_dict): np.testing.assert_array_almost_equal( state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1 ) @data("lin_comb", "param_shift", "fin_diff") def test_gradient_rxx(self, method): """Test the state gradient for XX rotation""" ham = TensoredOp([Z, X]) a = Parameter("a") q = QuantumRegister(2) qc = QuantumCircuit(q) qc.h(q[0]) qc.rxx(a, q[0], q[1]) op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) params = [a] state_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [{a: np.pi / 4}, {a: np.pi / 2}] correct_values = [[-0.707], [-1.0]] for i, value_dict in enumerate(values_dict): np.testing.assert_array_almost_equal( state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1 ) @data("lin_comb", "param_shift", "fin_diff") def test_gradient_ryy(self, method): """Test the state gradient for YY rotation""" alpha = Parameter("alpha") ham = TensoredOp([Y, alpha * Y]) a = Parameter("a") q = QuantumRegister(2) qc = QuantumCircuit(q) qc.ryy(a, q[0], q[1]) op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) state_grad = Gradient(grad_method=method).convert(operator=op, params=a) values_dict = [{a: np.pi / 8}, {a: np.pi}] correct_values = [[0], [0]] for i, value_dict in enumerate(values_dict): value_dict[alpha] = 1.0 np.testing.assert_array_almost_equal( state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1 ) @data("lin_comb", "param_shift", "fin_diff") def test_gradient_rzz(self, method): """Test the state gradient for ZZ rotation""" ham = Z ^ X a = Parameter("a") q = QuantumRegister(2) qc = QuantumCircuit(q) qc.h(q[0]) qc.rzz(a, q[0], q[1]) op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) params = [a] state_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [{a: np.pi / 4}, {a: np.pi / 2}] correct_values = [[-0.707], [-1.0]] for i, value_dict in enumerate(values_dict): np.testing.assert_array_almost_equal( state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1 ) @data("lin_comb", "param_shift", "fin_diff") def test_gradient_rzx(self, method): """Test the state gradient for ZX rotation""" ham = Z ^ Z a = Parameter("a") q = QuantumRegister(2) qc = QuantumCircuit(q) qc.h(q) qc.rzx(a, q[0], q[1]) op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) params = [a] state_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [{a: np.pi / 8}, {a: np.pi / 2}] correct_values = [[0.0], [0.0]] for i, value_dict in enumerate(values_dict): np.testing.assert_array_almost_equal( state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1 ) @data("lin_comb", "param_shift", "fin_diff") def test_state_gradient1(self, method): """Test the state gradient Tr(|psi><psi|Z) = sin(a)sin(b) Tr(|psi><psi|X) = cos(a) d<H>/da = - 0.5 sin(a) - 1 cos(a)sin(b) d<H>/db = - 1 sin(a)cos(b) """ ham = 0.5 * X - 1 * Z a = Parameter("a") b = Parameter("b") params = [a, b] q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) state_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [ {a: np.pi / 4, b: np.pi}, {params[0]: np.pi / 4, params[1]: np.pi / 4}, {params[0]: np.pi / 2, params[1]: np.pi / 4}, ] correct_values = [ [-0.5 / np.sqrt(2), 1 / np.sqrt(2)], [-0.5 / np.sqrt(2) - 0.5, -1 / 2.0], [-0.5, -1 / np.sqrt(2)], ] for i, value_dict in enumerate(values_dict): np.testing.assert_array_almost_equal( state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1 ) @data("lin_comb", "param_shift", "fin_diff") def test_state_gradient2(self, method): """Test the state gradient 2 Tr(|psi><psi|Z) = sin(a)sin(a) Tr(|psi><psi|X) = cos(a) d<H>/da = - 0.5 sin(a) - 2 cos(a)sin(a) """ ham = 0.5 * X - 1 * Z a = Parameter("a") # b = Parameter('b') params = [a] q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.rz(a, q[0]) qc.rx(a, q[0]) op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) state_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [{a: np.pi / 4}, {a: 0}, {a: np.pi / 2}] correct_values = [-1.353553, -0, -0.5] for i, value_dict in enumerate(values_dict): np.testing.assert_array_almost_equal( state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1 ) @data("lin_comb", "param_shift", "fin_diff") def test_state_gradient3(self, method): """Test the state gradient 3 Tr(|psi><psi|Z) = sin(a)sin(c(a)) = sin(a)sin(cos(a)+1) Tr(|psi><psi|X) = cos(a) d<H>/da = - 0.5 sin(a) - 1 cos(a)sin(cos(a)+1) + 1 sin^2(a)cos(cos(a)+1) """ ham = 0.5 * X - 1 * Z a = Parameter("a") # b = Parameter('b') params = a c = np.cos(a) + 1 q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.rz(a, q[0]) qc.rx(c, q[0]) op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) state_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [{a: np.pi / 4}, {a: 0}, {a: np.pi / 2}] correct_values = [-1.1220, -0.9093, 0.0403] for i, value_dict in enumerate(values_dict): np.testing.assert_array_almost_equal( state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1 ) @data("lin_comb", "param_shift", "fin_diff") def test_state_gradient4(self, method): """Test the state gradient 4 Tr(|psi><psi|ZX) = -cos(a) daTr(|psi><psi|ZX) = sin(a) """ ham = X ^ Z a = Parameter("a") params = a q = QuantumRegister(2) qc = QuantumCircuit(q) qc.x(q[0]) qc.h(q[1]) qc.crz(a, q[0], q[1]) op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) state_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [{a: np.pi / 4}, {a: 0}, {a: np.pi / 2}] correct_values = [1 / np.sqrt(2), 0, 1] for i, value_dict in enumerate(values_dict): np.testing.assert_array_almost_equal( state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1 ) @data("lin_comb", "param_shift", "fin_diff") def test_state_gradient5(self, method): """Test the state gradient Tr(|psi><psi|Z) = sin(a0)sin(a1) Tr(|psi><psi|X) = cos(a0) d<H>/da0 = - 0.5 sin(a0) - 1 cos(a0)sin(a1) d<H>/da1 = - 1 sin(a0)cos(a1) """ ham = 0.5 * X - 1 * Z a = ParameterVector("a", 2) params = a q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) state_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [ {a: [np.pi / 4, np.pi]}, {a: [np.pi / 4, np.pi / 4]}, {a: [np.pi / 2, np.pi / 4]}, ] correct_values = [ [-0.5 / np.sqrt(2), 1 / np.sqrt(2)], [-0.5 / np.sqrt(2) - 0.5, -1 / 2.0], [-0.5, -1 / np.sqrt(2)], ] for i, value_dict in enumerate(values_dict): np.testing.assert_array_almost_equal( state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1 ) @data("lin_comb", "param_shift", "fin_diff") def test_state_hessian(self, method): """Test the state Hessian Tr(|psi><psi|Z) = sin(a)sin(b) Tr(|psi><psi|X) = cos(a) d^2<H>/da^2 = - 0.5 cos(a) + 1 sin(a)sin(b) d^2<H>/dbda = - 1 cos(a)cos(b) d^2<H>/dbda = - 1 cos(a)cos(b) d^2<H>/db^2 = + 1 sin(a)sin(b) """ ham = 0.5 * X - 1 * Z params = ParameterVector("a", 2) q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) state_hess = Hessian(hess_method=method).convert(operator=op) values_dict = [ {params[0]: np.pi / 4, params[1]: np.pi}, {params[0]: np.pi / 4, params[1]: np.pi / 4}, ] correct_values = [ [[-0.5 / np.sqrt(2), 1 / np.sqrt(2)], [1 / np.sqrt(2), 0]], [[-0.5 / np.sqrt(2) + 0.5, -1 / 2.0], [-1 / 2.0, 0.5]], ] for i, value_dict in enumerate(values_dict): np.testing.assert_array_almost_equal( state_hess.assign_parameters(value_dict).eval(), correct_values[i], decimal=1 ) @unittest.skipIf(not optionals.HAS_JAX, "Skipping test due to missing jax module.") @data("lin_comb", "param_shift", "fin_diff") def test_state_hessian_custom_combo_fn(self, method): """Test the state Hessian with on an operator which includes a user-defined combo_fn. Tr(|psi><psi|Z) = sin(a)sin(b) Tr(|psi><psi|X) = cos(a) d^2<H>/da^2 = - 0.5 cos(a) + 1 sin(a)sin(b) d^2<H>/dbda = - 1 cos(a)cos(b) d^2<H>/dbda = - 1 cos(a)cos(b) d^2<H>/db^2 = + 1 sin(a)sin(b) """ ham = 0.5 * X - 1 * Z a = Parameter("a") b = Parameter("b") params = [(a, a), (a, b), (b, b)] q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.rz(a, q[0]) qc.rx(b, q[0]) op = ListOp( [~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0)], combo_fn=lambda x: x[0] ** 3 + 4 * x[0], ) state_hess = Hessian(hess_method=method).convert(operator=op, params=params) values_dict = [ {a: np.pi / 4, b: np.pi}, {a: np.pi / 4, b: np.pi / 4}, {a: np.pi / 2, b: np.pi / 4}, ] correct_values = [ [-1.28163104, 2.56326208, 1.06066017], [-0.04495626, -2.40716991, 1.8125], [2.82842712, -1.5, 1.76776695], ] for i, value_dict in enumerate(values_dict): np.testing.assert_array_almost_equal( state_hess.assign_parameters(value_dict).eval(), correct_values[i], decimal=1 ) @data("lin_comb", "param_shift", "fin_diff") def test_prob_grad(self, method): """Test the probability gradient dp0/da = cos(a)sin(b) / 2 dp1/da = - cos(a)sin(b) / 2 dp0/db = sin(a)cos(b) / 2 dp1/db = - sin(a)cos(b) / 2 """ a = Parameter("a") b = Parameter("b") params = [a, b] q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) op = CircuitStateFn(primitive=qc, coeff=1.0) prob_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [ {a: np.pi / 4, b: 0}, {params[0]: np.pi / 4, params[1]: np.pi / 4}, {params[0]: np.pi / 2, params[1]: np.pi}, ] correct_values = [ [[0, 0], [1 / (2 * np.sqrt(2)), -1 / (2 * np.sqrt(2))]], [[1 / 4, -1 / 4], [1 / 4, -1 / 4]], [[0, 0], [-1 / 2, 1 / 2]], ] for i, value_dict in enumerate(values_dict): for j, prob_grad_result in enumerate(prob_grad.assign_parameters(value_dict).eval()): np.testing.assert_array_almost_equal( prob_grad_result, correct_values[i][j], decimal=1 ) @data("lin_comb", "param_shift", "fin_diff") def test_prob_hess(self, method): """Test the probability Hessian using linear combination of unitaries method d^2p0/da^2 = - sin(a)sin(b) / 2 d^2p1/da^2 = sin(a)sin(b) / 2 d^2p0/dadb = cos(a)cos(b) / 2 d^2p1/dadb = - cos(a)cos(b) / 2 """ a = Parameter("a") b = Parameter("b") params = [(a, a), (a, b)] q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.rz(a, q[0]) qc.rx(b, q[0]) op = CircuitStateFn(primitive=qc, coeff=1.0) prob_hess = Hessian(hess_method=method).convert(operator=op, params=params) values_dict = [{a: np.pi / 4, b: 0}, {a: np.pi / 4, b: np.pi / 4}, {a: np.pi / 2, b: np.pi}] correct_values = [ [[0, 0], [1 / (2 * np.sqrt(2)), -1 / (2 * np.sqrt(2))]], [[-1 / 4, 1 / 4], [1 / 4, -1 / 4]], [[0, 0], [0, 0]], ] for i, value_dict in enumerate(values_dict): for j, prob_hess_result in enumerate(prob_hess.assign_parameters(value_dict).eval()): np.testing.assert_array_almost_equal( prob_hess_result, correct_values[i][j], decimal=1 ) @idata( product( ["lin_comb", "param_shift", "fin_diff"], [None, "lasso", "ridge", "perturb_diag", "perturb_diag_elements"], ) ) @unpack def test_natural_gradient(self, method, regularization): """Test the natural gradient""" try: for params in (ParameterVector("a", 2), [Parameter("a"), Parameter("b")]): ham = 0.5 * X - 1 * Z q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) nat_grad = NaturalGradient( grad_method=method, regularization=regularization ).convert(operator=op) values_dict = [{params[0]: np.pi / 4, params[1]: np.pi / 2}] # reference values obtained by classically computing the natural gradients correct_values = [[-3.26, 1.63]] if regularization == "ridge" else [[-4.24, 0]] for i, value_dict in enumerate(values_dict): np.testing.assert_array_almost_equal( nat_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1 ) except MissingOptionalLibraryError as ex: self.skipTest(str(ex)) def test_natural_gradient2(self): """Test the natural gradient 2""" with self.assertRaises(TypeError): _ = NaturalGradient().convert(None, None) @idata( zip( ["lin_comb_full", "overlap_block_diag", "overlap_diag"], [LinCombFull, OverlapBlockDiag, OverlapDiag], ) ) @unpack def test_natural_gradient3(self, qfi_method, circuit_qfi): """Test the natural gradient 3""" nat_grad = NaturalGradient(qfi_method=qfi_method) self.assertIsInstance(nat_grad.qfi_method, circuit_qfi) @idata( product( ["lin_comb", "param_shift", "fin_diff"], ["lin_comb_full", "overlap_block_diag", "overlap_diag"], [None, "ridge", "perturb_diag", "perturb_diag_elements"], ) ) @unpack def test_natural_gradient4(self, grad_method, qfi_method, regularization): """Test the natural gradient 4""" # Avoid regularization = lasso intentionally because it does not converge try: ham = 0.5 * X - 1 * Z a = Parameter("a") params = a q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.rz(a, q[0]) op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) nat_grad = NaturalGradient( grad_method=grad_method, qfi_method=qfi_method, regularization=regularization ).convert(operator=op, params=params) values_dict = [{a: np.pi / 4}] correct_values = [[0.0]] if regularization == "ridge" else [[-1.41421342]] for i, value_dict in enumerate(values_dict): np.testing.assert_array_almost_equal( nat_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=3 ) except MissingOptionalLibraryError as ex: self.skipTest(str(ex)) def test_gradient_p_imag(self): """Test the imaginary state gradient for p |psi(a)> = 1/sqrt(2)[[1, exp(ia)]] <psi(a)|X|da psi(a)> = iexp(-ia)/2 <1|H(|0>+exp(ia)|1>) Im(<psi(a)|X|da psi(a)>) = 0.5 cos(a). """ ham = X a = Parameter("a") params = a q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.p(a, q[0]) op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) state_grad = LinComb(aux_meas_op=(-1) * Y).convert(operator=op, params=params) values_dict = [{a: np.pi / 4}, {a: 0}, {a: np.pi / 2}] correct_values = [1 / np.sqrt(2), 1, 0] for i, value_dict in enumerate(values_dict): np.testing.assert_array_almost_equal( state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1 ) def test_qfi_p_imag(self): """Test the imaginary state QFI for RXRY""" x = Parameter("x") y = Parameter("y") circuit = QuantumCircuit(1) circuit.ry(y, 0) circuit.rx(x, 0) state = StateFn(circuit) dx = ( lambda x, y: (-1) * 0.5j * np.array( [ [ -1j * np.sin(x / 2) * np.cos(y / 2) + np.cos(x / 2) * np.sin(y / 2), np.cos(x / 2) * np.cos(y / 2) - 1j * np.sin(x / 2) * np.sin(y / 2), ] ] ) ) dy = ( lambda x, y: (-1) * 0.5j * np.array( [ [ -1j * np.cos(x / 2) * np.sin(y / 2) + np.sin(x / 2) * np.cos(y / 2), 1j * np.cos(x / 2) * np.cos(y / 2) - 1 * np.sin(x / 2) * np.sin(y / 2), ] ] ) ) state_grad = LinCombFull(aux_meas_op=-1 * Y, phase_fix=False).convert( operator=state, params=[x, y] ) values_dict = [{x: 0, y: np.pi / 4}, {x: 0, y: np.pi / 2}, {x: np.pi / 2, y: 0}] for value_dict in values_dict: x_ = list(value_dict.values())[0] y_ = list(value_dict.values())[1] correct_values = [ [ 4 * np.imag(np.dot(dx(x_, y_), np.conj(np.transpose(dx(x_, y_))))[0][0]), 4 * np.imag(np.dot(dy(x_, y_), np.conj(np.transpose(dx(x_, y_))))[0][0]), ], [ 4 * np.imag(np.dot(dy(x_, y_), np.conj(np.transpose(dx(x_, y_))))[0][0]), 4 * np.imag(np.dot(dy(x_, y_), np.conj(np.transpose(dy(x_, y_))))[0][0]), ], ] np.testing.assert_array_almost_equal( state_grad.assign_parameters(value_dict).eval(), correct_values, decimal=3 ) @unittest.skipIf(not optionals.HAS_JAX, "Skipping test due to missing jax module.") @idata(product(["lin_comb", "param_shift", "fin_diff"], [True, False])) @unpack def test_jax_chain_rule(self, method: str, autograd: bool): """Test the chain rule functionality using Jax d<H>/d<X> = 2<X> d<H>/d<Z> = - sin(<Z>) <Z> = Tr(|psi><psi|Z) = sin(a)sin(b) <X> = Tr(|psi><psi|X) = cos(a) d<H>/da = d<H>/d<X> d<X>/da + d<H>/d<Z> d<Z>/da = - 2 cos(a)sin(a) - sin(sin(a)sin(b)) * cos(a)sin(b) d<H>/db = d<H>/d<X> d<X>/db + d<H>/d<Z> d<Z>/db = - sin(sin(a)sin(b)) * sin(a)cos(b) """ a = Parameter("a") b = Parameter("b") params = [a, b] q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) def combo_fn(x): return jnp.power(x[0], 2) + jnp.cos(x[1]) def grad_combo_fn(x): return np.array([2 * x[0], -np.sin(x[1])]) op = ListOp( [ ~StateFn(X) @ CircuitStateFn(primitive=qc, coeff=1.0), ~StateFn(Z) @ CircuitStateFn(primitive=qc, coeff=1.0), ], combo_fn=combo_fn, grad_combo_fn=None if autograd else grad_combo_fn, ) state_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [ {a: np.pi / 4, b: np.pi}, {params[0]: np.pi / 4, params[1]: np.pi / 4}, {params[0]: np.pi / 2, params[1]: np.pi / 4}, ] correct_values = [[-1.0, 0.0], [-1.2397, -0.2397], [0, -0.45936]] for i, value_dict in enumerate(values_dict): np.testing.assert_array_almost_equal( state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1 ) @data("lin_comb", "param_shift", "fin_diff") def test_grad_combo_fn_chain_rule(self, method): """Test the chain rule for a custom gradient combo function.""" np.random.seed(2) def combo_fn(x): amplitudes = x[0].primitive.data pdf = np.multiply(amplitudes, np.conj(amplitudes)) return np.sum(np.log(pdf)) / (-len(amplitudes)) def grad_combo_fn(x): amplitudes = x[0].primitive.data pdf = np.multiply(amplitudes, np.conj(amplitudes)) grad = [] for prob in pdf: grad += [-1 / prob] return grad qc = RealAmplitudes(2, reps=1) grad_op = ListOp([StateFn(qc.decompose())], combo_fn=combo_fn, grad_combo_fn=grad_combo_fn) grad = Gradient(grad_method=method).convert(grad_op) value_dict = dict(zip(qc.ordered_parameters, np.random.rand(len(qc.ordered_parameters)))) correct_values = [ [(-0.16666259133549044 + 0j)], [(-7.244949702732864 + 0j)], [(-2.979791752749964 + 0j)], [(-5.310186078432614 + 0j)], ] np.testing.assert_array_almost_equal( grad.assign_parameters(value_dict).eval(), correct_values ) def test_grad_combo_fn_chain_rule_nat_grad(self): """Test the chain rule for a custom gradient combo function.""" np.random.seed(2) def combo_fn(x): amplitudes = x[0].primitive.data pdf = np.multiply(amplitudes, np.conj(amplitudes)) return np.sum(np.log(pdf)) / (-len(amplitudes)) def grad_combo_fn(x): amplitudes = x[0].primitive.data pdf = np.multiply(amplitudes, np.conj(amplitudes)) grad = [] for prob in pdf: grad += [-1 / prob] return grad try: qc = RealAmplitudes(2, reps=1) grad_op = ListOp( [StateFn(qc.decompose())], combo_fn=combo_fn, grad_combo_fn=grad_combo_fn ) grad = NaturalGradient(grad_method="lin_comb", regularization="ridge").convert( grad_op, qc.ordered_parameters ) value_dict = dict( zip(qc.ordered_parameters, np.random.rand(len(qc.ordered_parameters))) ) correct_values = [[0.20777236], [-18.92560338], [-15.89005475], [-10.44002031]] np.testing.assert_array_almost_equal( grad.assign_parameters(value_dict).eval(), correct_values, decimal=3 ) except MissingOptionalLibraryError as ex: self.skipTest(str(ex)) @data("lin_comb", "param_shift", "fin_diff") def test_operator_coefficient_gradient(self, method): """Test the operator coefficient gradient Tr( | psi > < psi | Z) = sin(a)sin(b) Tr( | psi > < psi | X) = cos(a) """ a = Parameter("a") b = Parameter("b") q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.rz(a, q[0]) qc.rx(b, q[0]) coeff_0 = Parameter("c_0") coeff_1 = Parameter("c_1") ham = coeff_0 * X + coeff_1 * Z op = StateFn(ham, is_measurement=True) @ CircuitStateFn(primitive=qc, coeff=1.0) gradient_coeffs = [coeff_0, coeff_1] coeff_grad = Gradient(grad_method=method).convert(op, gradient_coeffs) values_dict = [ {coeff_0: 0.5, coeff_1: -1, a: np.pi / 4, b: np.pi}, {coeff_0: 0.5, coeff_1: -1, a: np.pi / 4, b: np.pi / 4}, ] correct_values = [[1 / np.sqrt(2), 0], [1 / np.sqrt(2), 1 / 2]] for i, value_dict in enumerate(values_dict): np.testing.assert_array_almost_equal( coeff_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1 ) @data("lin_comb", "param_shift", "fin_diff") def test_operator_coefficient_hessian(self, method): """Test the operator coefficient hessian <Z> = Tr( | psi > < psi | Z) = sin(a)sin(b) <X> = Tr( | psi > < psi | X) = cos(a) d<H>/dc_0 = 2 * c_0 * <X> + c_1 * <Z> d<H>/dc_1 = c_0 * <Z> d^2<H>/dc_0^2 = 2 * <X> d^2<H>/dc_0dc_1 = <Z> d^2<H>/dc_1dc_0 = <Z> d^2<H>/dc_1^2 = 0 """ a = Parameter("a") b = Parameter("b") q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.rz(a, q[0]) qc.rx(b, q[0]) coeff_0 = Parameter("c_0") coeff_1 = Parameter("c_1") ham = coeff_0 * coeff_0 * X + coeff_1 * coeff_0 * Z op = StateFn(ham, is_measurement=True) @ CircuitStateFn(primitive=qc, coeff=1.0) gradient_coeffs = [(coeff_0, coeff_0), (coeff_0, coeff_1), (coeff_1, coeff_1)] coeff_grad = Hessian(hess_method=method).convert(op, gradient_coeffs) values_dict = [ {coeff_0: 0.5, coeff_1: -1, a: np.pi / 4, b: np.pi}, {coeff_0: 0.5, coeff_1: -1, a: np.pi / 4, b: np.pi / 4}, ] correct_values = [[2 / np.sqrt(2), 0, 0], [2 / np.sqrt(2), 1 / 2, 0]] for i, value_dict in enumerate(values_dict): np.testing.assert_array_almost_equal( coeff_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1 ) @data("lin_comb", "param_shift", "fin_diff") def test_circuit_sampler(self, method): """Test the gradient with circuit sampler Tr(|psi><psi|Z) = sin(a)sin(b) Tr(|psi><psi|X) = cos(a) d<H>/da = - 0.5 sin(a) - 1 cos(a)sin(b) d<H>/db = - 1 sin(a)cos(b) """ ham = 0.5 * X - 1 * Z a = Parameter("a") b = Parameter("b") params = [a, b] q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) shots = 8000 if method == "fin_diff": np.random.seed(8) state_grad = Gradient(grad_method=method, epsilon=shots ** (-1 / 6.0)).convert( operator=op ) else: state_grad = Gradient(grad_method=method).convert(operator=op) values_dict = [ {a: np.pi / 4, b: np.pi}, {params[0]: np.pi / 4, params[1]: np.pi / 4}, {params[0]: np.pi / 2, params[1]: np.pi / 4}, ] correct_values = [ [-0.5 / np.sqrt(2), 1 / np.sqrt(2)], [-0.5 / np.sqrt(2) - 0.5, -1 / 2.0], [-0.5, -1 / np.sqrt(2)], ] backend = BasicAer.get_backend("qasm_simulator") with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance(backend=backend, shots=shots) with self.assertWarns(DeprecationWarning): for i, value_dict in enumerate(values_dict): sampler = CircuitSampler(backend=q_instance).convert( state_grad, params={k: [v] for k, v in value_dict.items()} ) np.testing.assert_array_almost_equal( sampler.eval()[0], correct_values[i], decimal=1 ) @data("lin_comb", "param_shift", "fin_diff") def test_circuit_sampler2(self, method): """Test the probability gradient with the circuit sampler dp0/da = cos(a)sin(b) / 2 dp1/da = - cos(a)sin(b) / 2 dp0/db = sin(a)cos(b) / 2 dp1/db = - sin(a)cos(b) / 2 """ a = Parameter("a") b = Parameter("b") params = [a, b] q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) op = CircuitStateFn(primitive=qc, coeff=1.0) shots = 8000 if method == "fin_diff": np.random.seed(8) prob_grad = Gradient(grad_method=method, epsilon=shots ** (-1 / 6.0)).convert( operator=op, params=params ) else: prob_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [ {a: [np.pi / 4], b: [0]}, {params[0]: [np.pi / 4], params[1]: [np.pi / 4]}, {params[0]: [np.pi / 2], params[1]: [np.pi]}, ] correct_values = [ [[0, 0], [1 / (2 * np.sqrt(2)), -1 / (2 * np.sqrt(2))]], [[1 / 4, -1 / 4], [1 / 4, -1 / 4]], [[0, 0], [-1 / 2, 1 / 2]], ] backend = BasicAer.get_backend("qasm_simulator") with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance(backend=backend, shots=shots) with self.assertWarns(DeprecationWarning): for i, value_dict in enumerate(values_dict): sampler = CircuitSampler(backend=q_instance).convert(prob_grad, params=value_dict) result = sampler.eval()[0] self.assertTrue(np.allclose(result[0].toarray(), correct_values[i][0], atol=0.1)) self.assertTrue(np.allclose(result[1].toarray(), correct_values[i][1], atol=0.1)) @idata(["statevector_simulator", "qasm_simulator"]) def test_gradient_wrapper(self, backend_type): """Test the gradient wrapper for probability gradients dp0/da = cos(a)sin(b) / 2 dp1/da = - cos(a)sin(b) / 2 dp0/db = sin(a)cos(b) / 2 dp1/db = - sin(a)cos(b) / 2 """ method = "param_shift" a = Parameter("a") b = Parameter("b") params = [a, b] q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) op = CircuitStateFn(primitive=qc, coeff=1.0) shots = 8000 backend = BasicAer.get_backend(backend_type) with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance( backend=backend, shots=shots, seed_simulator=2, seed_transpiler=2 ) if method == "fin_diff": np.random.seed(8) prob_grad = Gradient(grad_method=method, epsilon=shots ** (-1 / 6.0)).gradient_wrapper( operator=op, bind_params=params, backend=q_instance ) else: with self.assertWarns(DeprecationWarning): prob_grad = Gradient(grad_method=method).gradient_wrapper( operator=op, bind_params=params, backend=q_instance ) values = [[np.pi / 4, 0], [np.pi / 4, np.pi / 4], [np.pi / 2, np.pi]] correct_values = [ [[0, 0], [1 / (2 * np.sqrt(2)), -1 / (2 * np.sqrt(2))]], [[1 / 4, -1 / 4], [1 / 4, -1 / 4]], [[0, 0], [-1 / 2, 1 / 2]], ] with self.assertWarns(DeprecationWarning): for i, value in enumerate(values): result = prob_grad(value) if backend_type == "qasm_simulator": # sparse result result = [result[0].toarray(), result[1].toarray()] self.assertTrue(np.allclose(result[0], correct_values[i][0], atol=0.1)) self.assertTrue(np.allclose(result[1], correct_values[i][1], atol=0.1)) @data(("statevector_simulator", 1e-7), ("qasm_simulator", 2e-1)) @unpack def test_gradient_wrapper2(self, backend_type, atol): """Test the gradient wrapper for gradients checking that statevector and qasm gives the same results dp0/da = cos(a)sin(b) / 2 dp1/da = - cos(a)sin(b) / 2 dp0/db = sin(a)cos(b) / 2 dp1/db = - sin(a)cos(b) / 2 """ method = "lin_comb" a = Parameter("a") b = Parameter("b") params = [a, b] qc = QuantumCircuit(2) qc.h(1) qc.h(0) qc.sdg(1) qc.cz(0, 1) qc.ry(params[0], 0) qc.rz(params[1], 0) qc.h(1) obs = (Z ^ X) - (Y ^ Y) op = StateFn(obs, is_measurement=True) @ CircuitStateFn(primitive=qc) shots = 8192 if backend_type == "qasm_simulator" else 1 values = [[0, np.pi / 2], [np.pi / 4, np.pi / 4], [np.pi / 3, np.pi / 9]] correct_values = [[-4.0, 0], [-2.0, -4.82842712], [-0.68404029, -7.01396121]] for i, value in enumerate(values): backend = BasicAer.get_backend(backend_type) with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance( backend=backend, shots=shots, seed_simulator=2, seed_transpiler=2 ) grad = NaturalGradient(grad_method=method).gradient_wrapper( operator=op, bind_params=params, backend=q_instance ) result = grad(value) self.assertTrue(np.allclose(result, correct_values[i], atol=atol)) @slow_test def test_vqe(self): """Test VQE with gradients""" method = "lin_comb" backend = "qasm_simulator" with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance( BasicAer.get_backend(backend), seed_simulator=79, seed_transpiler=2 ) # Define the Hamiltonian h2_hamiltonian = ( -1.05 * (I ^ I) + 0.39 * (I ^ Z) - 0.39 * (Z ^ I) - 0.01 * (Z ^ Z) + 0.18 * (X ^ X) ) h2_energy = -1.85727503 # Define the Ansatz wavefunction = QuantumCircuit(2) params = ParameterVector("theta", length=8) itr = iter(params) wavefunction.ry(next(itr), 0) wavefunction.ry(next(itr), 1) wavefunction.rz(next(itr), 0) wavefunction.rz(next(itr), 1) wavefunction.cx(0, 1) wavefunction.ry(next(itr), 0) wavefunction.ry(next(itr), 1) wavefunction.rz(next(itr), 0) wavefunction.rz(next(itr), 1) # Conjugate Gradient algorithm optimizer = CG(maxiter=10) grad = Gradient(grad_method=method) # Gradient callable with self.assertWarns(DeprecationWarning): vqe = VQE( ansatz=wavefunction, optimizer=optimizer, gradient=grad, quantum_instance=q_instance ) result = vqe.compute_minimum_eigenvalue(operator=h2_hamiltonian) np.testing.assert_almost_equal(result.optimal_value, h2_energy, decimal=0) def test_qfi_overlap_works_with_bound_parameters(self): """Test all QFI methods work if the circuit contains a gate with bound parameters.""" x = Parameter("x") circuit = QuantumCircuit(1) circuit.ry(np.pi / 4, 0) circuit.rx(x, 0) state = StateFn(circuit) methods = ["lin_comb_full", "overlap_diag", "overlap_block_diag"] reference = 0.5 for method in methods: with self.subTest(method): qfi = QFI(method) value = np.real(qfi.convert(state, [x]).bind_parameters({x: 0.12}).eval()) self.assertAlmostEqual(value[0][0], reference) @ddt class TestParameterGradients(QiskitOpflowTestCase): """Test taking the gradient of parameter expressions.""" def test_grad(self): """Test taking the gradient of parameter expressions.""" x, y = Parameter("x"), Parameter("y") with self.subTest("linear"): expr = 2 * x + y grad = expr.gradient(x) self.assertEqual(grad, 2) grad = expr.gradient(y) self.assertEqual(grad, 1) with self.subTest("polynomial"): expr = x * x * x - x * y + y * y grad = expr.gradient(x) self.assertEqual(grad, 3 * x * x - y) grad = expr.gradient(y) self.assertEqual(grad, -1 * x + 2 * y) def test_converted_to_float_if_bound(self): """Test the gradient is a float when no free symbols are left.""" x = Parameter("x") expr = 2 * x + 1 grad = expr.gradient(x) self.assertIsInstance(grad, float) def test_converted_to_complex_if_bound(self): """Test the gradient is a complex when no free symbols are left.""" x = Parameter("x") x2 = 1j * x expr = 2 * x2 + 1 grad = expr.gradient(x) self.assertIsInstance(grad, complex) @ddt class TestQFI(QiskitOpflowTestCase): """Tests for the quantum Fisher information.""" @data("lin_comb_full", "overlap_block_diag", "overlap_diag") def test_qfi_simple(self, method): """Test if the quantum fisher information calculation is correct for a simple test case. QFI = [[1, 0], [0, 1]] - [[0, 0], [0, cos^2(a)]] """ # create the circuit a, b = Parameter("a"), Parameter("b") qc = QuantumCircuit(1) qc.h(0) qc.rz(a, 0) qc.rx(b, 0) # convert the circuit to a QFI object op = CircuitStateFn(qc) qfi = QFI(qfi_method=method).convert(operator=op) # test for different values values_dict = [{a: np.pi / 4, b: 0.1}, {a: np.pi, b: 0.1}, {a: np.pi / 2, b: 0.1}] correct_values = [[[1, 0], [0, 0.5]], [[1, 0], [0, 0]], [[1, 0], [0, 1]]] for i, value_dict in enumerate(values_dict): actual = qfi.assign_parameters(value_dict).eval() np.testing.assert_array_almost_equal(actual, correct_values[i], decimal=1) def test_qfi_phase_fix(self): """Test the phase-fix argument in a QFI calculation QFI = [[1, 0], [0, 1]]. """ # create the circuit a, b = Parameter("a"), Parameter("b") qc = QuantumCircuit(1) qc.h(0) qc.rz(a, 0) qc.rx(b, 0) # convert the circuit to a QFI object op = CircuitStateFn(qc) qfi = LinCombFull(phase_fix=False).convert(operator=op, params=[a, b]) # test for different values value_dict = {a: np.pi / 4, b: 0.1} correct_values = [[1, 0], [0, 1]] actual = qfi.assign_parameters(value_dict).eval() np.testing.assert_array_almost_equal(actual, correct_values, decimal=2) def test_qfi_maxcut(self): """Test the QFI for a simple MaxCut problem. This is interesting because it contains the same parameters in different gates. """ # create maxcut circuit for the hamiltonian # H = (I ^ I ^ Z ^ Z) + (I ^ Z ^ I ^ Z) + (Z ^ I ^ I ^ Z) + (I ^ Z ^ Z ^ I) x = ParameterVector("x", 2) ansatz = QuantumCircuit(4) # initial hadamard layer ansatz.h(ansatz.qubits) # e^{iZZ} layers def expiz(qubit0, qubit1): ansatz.cx(qubit0, qubit1) ansatz.rz(2 * x[0], qubit1) ansatz.cx(qubit0, qubit1) expiz(2, 1) expiz(3, 0) expiz(2, 0) expiz(1, 0) # mixer layer with RX gates for i in range(ansatz.num_qubits): ansatz.rx(2 * x[1], i) point = {x[0]: 0.4, x[1]: 0.69} # reference computed via finite difference reference = np.array([[16.0, -5.551], [-5.551, 18.497]]) # QFI from gradient framework qfi = QFI().convert(CircuitStateFn(ansatz), params=x[:]) actual = np.array(qfi.bind_parameters(point).eval()).real np.testing.assert_array_almost_equal(actual, reference, decimal=3) def test_qfi_circuit_shared_params(self): """Test the QFI circuits for parameters shared across some gates.""" # create the test circuit x = Parameter("x") circuit = QuantumCircuit(1) circuit.rx(x, 0) circuit.rx(x, 0) # construct the QFI circuits used in the evaluation circuit1 = QuantumCircuit(2) circuit1.h(1) circuit1.x(1) circuit1.cx(1, 0) circuit1.x(1) circuit1.cx(1, 0) # circuit1.rx(x, 0) # trimmed # circuit1.rx(x, 0) # trimmed circuit1.h(1) circuit2 = QuantumCircuit(2) circuit2.h(1) circuit2.x(1) circuit2.cx(1, 0) circuit2.x(1) circuit2.rx(x, 0) circuit2.cx(1, 0) # circuit2.rx(x, 0) # trimmed circuit2.h(1) circuit3 = QuantumCircuit(2) circuit3.h(1) circuit3.cx(1, 0) circuit3.x(1) circuit3.rx(x, 0) circuit3.cx(1, 0) # circuit3.rx(x, 0) # trimmed circuit3.x(1) circuit3.h(1) circuit4 = QuantumCircuit(2) circuit4.h(1) circuit4.rx(x, 0) circuit4.x(1) circuit4.cx(1, 0) circuit4.x(1) circuit4.cx(1, 0) # circuit4.rx(x, 0) # trimmed circuit4.h(1) # this naming and adding of register is required bc circuit's are only equal if the # register have the same names circuit5 = QuantumCircuit(2) circuit5.h(1) circuit5.sdg(1) circuit5.cx(1, 0) # circuit5.rx(x, 0) # trimmed circuit5.h(1) circuit6 = QuantumCircuit(2) circuit6.h(1) circuit6.sdg(1) circuit6.rx(x, 0) circuit6.cx(1, 0) circuit6.h(1) # compare qfi = QFI().convert(StateFn(circuit), params=[x]) circuit_sets = ( [circuit1, circuit2, circuit3, circuit4], [circuit5, circuit6], [circuit5, circuit6], ) list_ops = ( qfi.oplist[0].oplist[0].oplist[:-1], qfi.oplist[0].oplist[0].oplist[-1].oplist[0].oplist, qfi.oplist[0].oplist[0].oplist[-1].oplist[1].oplist, ) # compose both on the same circuit such that the comparison works base = QuantumCircuit(2) for i, (circuit_set, list_op) in enumerate(zip(circuit_sets, list_ops)): for j, (reference, composed_op) in enumerate(zip(circuit_set, list_op)): with self.subTest(f"set {i} circuit {j}"): primitive = composed_op[1].primitive self.assertEqual(base.compose(primitive), base.compose(reference)) def test_overlap_qfi_bound_parameters(self): """Test the overlap QFI works on a circuit with multi-parameter bound gates.""" x = Parameter("x") circuit = QuantumCircuit(1) circuit.u(1, 2, 3, 0) circuit.rx(x, 0) qfi = QFI("overlap_diag").convert(StateFn(circuit), [x]) value = qfi.bind_parameters({x: 1}).eval()[0][0] ref = 0.87737713 self.assertAlmostEqual(value, ref) def test_overlap_qfi_raises_on_multiparam(self): """Test the overlap QFI raises an appropriate error on multi-param unbound gates.""" x = ParameterVector("x", 2) circuit = QuantumCircuit(1) circuit.u(x[0], x[1], 2, 0) with self.assertRaises(NotImplementedError): _ = QFI("overlap_diag").convert(StateFn(circuit), [x]) def test_overlap_qfi_raises_on_unsupported_gate(self): """Test the overlap QFI raises an appropriate error on multi-param unbound gates.""" x = Parameter("x") circuit = QuantumCircuit(1) circuit.p(x, 0) with self.assertRaises(NotImplementedError): _ = QFI("overlap_diag").convert(StateFn(circuit), [x]) @data(-Y, Z - 1j * Y) def test_aux_meas_op(self, aux_meas_op): """Test various auxiliary measurement operators for probability gradients with LinComb Gradient. """ a = Parameter("a") b = Parameter("b") params = [a, b] q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) op = CircuitStateFn(primitive=qc, coeff=1.0) shots = 10000 prob_grad = LinComb(aux_meas_op=aux_meas_op).convert(operator=op, params=params) value_dicts = [{a: [np.pi / 4], b: [0]}, {a: [np.pi / 2], b: [np.pi / 4]}] if aux_meas_op == -Y: correct_values = [ [[-0.5, 0.5], [-1 / (np.sqrt(2) * 2), -1 / (np.sqrt(2) * 2)]], [[-1 / (np.sqrt(2) * 2), 1 / (np.sqrt(2) * 2)], [0, 0]], ] else: correct_values = [ [[-0.5j, 0.5j], [(1 - 1j) / (np.sqrt(2) * 2), (-1 - 1j) / (np.sqrt(2) * 2)]], [ [-1j / (np.sqrt(2) * 2), 1j / (np.sqrt(2) * 2)], [1 / (np.sqrt(2) * 2), -1 / (np.sqrt(2) * 2)], ], ] for backend_type in ["qasm_simulator", "statevector_simulator"]: for j, value_dict in enumerate(value_dicts): with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance( backend=BasicAer.get_backend(backend_type), shots=shots ) result = ( CircuitSampler(backend=q_instance) .convert(prob_grad, params=value_dict) .eval()[0] ) if backend_type == "qasm_simulator": # sparse result result = [result[0].toarray()[0], result[1].toarray()[0]] for i, item in enumerate(result): np.testing.assert_array_almost_equal(item, correct_values[j][i], decimal=1) def test_unsupported_aux_meas_op(self): """Test error for unsupported auxiliary measurement operator in LinComb Gradient. dp0/da = cos(a)sin(b) / 2 dp1/da = - cos(a)sin(b) / 2 dp0/db = sin(a)cos(b) / 2 dp1/db = - sin(a)cos(b) / 2 """ a = Parameter("a") b = Parameter("b") params = [a, b] q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) op = CircuitStateFn(primitive=qc, coeff=1.0) shots = 8000 aux_meas_op = X with self.assertRaises(ValueError): prob_grad = LinComb(aux_meas_op=aux_meas_op).convert(operator=op, params=params) value_dict = {a: [np.pi / 4], b: [0]} backend = BasicAer.get_backend("qasm_simulator") with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance(backend=backend, shots=shots) CircuitSampler(backend=q_instance).convert(prob_grad, params=value_dict).eval() def test_nat_grad_error(self): """Test the NaturalGradient throws an Error. dp0/da = cos(a)sin(b) / 2 dp1/da = - cos(a)sin(b) / 2 dp0/db = sin(a)cos(b) / 2 dp1/db = - sin(a)cos(b) / 2 """ method = "lin_comb" a = Parameter("a") b = Parameter("b") params = [a, b] qc = QuantumCircuit(2) qc.h(1) qc.h(0) qc.sdg(1) qc.cz(0, 1) qc.ry(params[0], 0) qc.rz(params[1], 0) qc.h(1) obs = (Z ^ X) - (Y ^ Y) op = StateFn(obs, is_measurement=True) @ CircuitStateFn(primitive=qc) backend_type = "qasm_simulator" shots = 1 value = [0, np.pi / 2] backend = BasicAer.get_backend(backend_type) with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance( backend=backend, shots=shots, seed_simulator=2, seed_transpiler=2 ) with self.assertWarns(DeprecationWarning): grad = NaturalGradient(grad_method=method).gradient_wrapper( operator=op, bind_params=params, backend=q_instance ) with self.assertWarns(DeprecationWarning): with self.assertRaises(ValueError): grad(value) if __name__ == "__main__": unittest.main()
https://github.com/lmarza/QuantumDeskCalculator
lmarza
import math from qiskit import * from operations import addition, subtraction pie = math.pi def div(dividend, divisor, accumulator,c_dividend, circ, cl_index): d = QuantumRegister(1) circ.add_register(d) circ.x(d[0]) c_dividend_str = '0' while c_dividend_str[0] == '0': subtraction.sub(dividend, divisor, circ) addition.sum(accumulator, d, circ) for i in range(len(dividend)): circ.measure(dividend[i], c_dividend[i]) result = execute(circ, backend=Aer.get_backend('qasm_simulator'), shots=10).result() counts = result.get_counts("qc") #print(counts) c_dividend_str = list(counts.keys())[0] #.split()[0] subtraction.sub(accumulator, d, circ)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# -*- coding: utf-8 -*- """Additional composite gates used in quantum tic tac toe""" import numpy as np def x_bus(qc,*bus): """Negates a whole bus""" for q in bus: qc.x(q) def bus_or(qc,target,*busses): """Negates target if any of input busses is totally true, can add overall phase. Page 16 of reference""" if len(busses)==1: qc.cnx(qc,*busses[0],target) elif len(busses) == 2: #negate everything qc.x_bus(qc,*busses[0],*busses[1],target) qc.ry(np.pi/4,target) qc.any_x(qc,*busses[1],target) qc.ry(np.pi/4,target) qc.any_x(qc,*busses[0],target) qc.ry(-np.pi/4,target) qc.any_x(qc,*busses[1],target) qc.ry(-np.pi/4,target) qc.x_bus(qc,*busses[0],*busses[1]) elif len(busses) >= 3: #Need to negate all qubits, do so for each bus for bus in busses: qc.x_bus(qc,*bus) #Then negate the target also qc.x(target) qc.ry(np.pi/4,target) qc.any_x(qc,*busses[1],target) qc.ry(np.pi/4,target) #Recursiveness here: qc.bus_or(qc,target,*busses[:-1]) qc.ry(-np.pi/4,target) qc.any_x(qc,*busses[1],target) qc.ry(-np.pi/4,target) for bus in busses: qc.x_bus(qc,*bus) #No need to negate target again def any_x(qc,*qubits): """Negate last qubit if any of initial qubits are 1.""" qc.x_bus(qc,*qubits) qc.cnx(qc,*qubits) qc.x_bus(qc,*qubits[:-1]) def cry(qc,theta,q1,q2): """Controlled ry""" qc.ry(theta/2,q2) qc.cx(q1,q2) qc.ry(-theta/2,q2) qc.cx(q1,q2) def cnx(qc,*qubits): """Control n-1 qubits, apply 'not' to last one Follows: @article{PhysRevA.52.3457, title = {Elementary gates for quantum computation}, author = {Barenco, Adriano and Bennett, Charles H. and Cleve, Richard and DiVincenzo, David P. and Margolus, Norman and Shor, Peter and Sleator, Tycho and Smolin, John A. and Weinfurter, Harald}, doi = {10.1103/PhysRevA.52.3457}, url = {https://link.aps.org/doi/10.1103/PhysRevA.52.3457} } Follwing Lemma 7.9, which uses Lemma 5.1 and 4.3 """ if len(qubits) >= 3: last = qubits[-1] #A matrix: (made up of a and Y rotation, lemma4.3) qc.crz(np.pi/2,qubits[-2],qubits[-1]) #cry qc.cry(qc,np.pi/2,qubits[-2],qubits[-1]) #Control not gate qc.cnx(qc,*qubits[:-2],qubits[-1]) #B matrix (cry again, but opposite angle) qc.cry(qc,-np.pi/2,qubits[-2],qubits[-1]) #Control qc.cnx(qc,*qubits[:-2],qubits[-1]) #C matrix (final rotation) qc.crz(-np.pi/2,qubits[-2],qubits[-1]) elif len(qubits)==3: qc.ccx(*qubits) elif len(qubits)==2: qc.cx(*qubits) if __name__ == "__main__": from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import CompositeGate, available_backends, execute q = QuantumRegister(5, "qr") q2 = QuantumRegister(1, "qr") print(len(q2)) c = ClassicalRegister(5, "cr") qc = QuantumCircuit(q, c) qc.cry = cry qc.cnx = cnx qc.any_x = any_x qc.x_bus = x_bus qc.bus_or = bus_or #qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.h(q[-1]) qc.bus_or(qc,q[0],[q[1],q[2],q[3]],[q[4]]) qc.measure(q,c) job_sim = execute(qc, "local_qasm_simulator",shots=100) sim_result = job_sim.result() # Show the results print("simulation: ", sim_result) print(sim_result.get_counts(qc)) print(qc.qasm())
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.providers.aer import QasmSimulator from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity # Suppress warnings import warnings warnings.filterwarnings('ignore') def trotter_gate(dt, to_instruction = True): qc = QuantumCircuit(2) qc.rx(2*dt,0) qc.rz(2*dt,1) qc.h(1) qc.cx(1,0) qc.rz(-2*dt, 0) qc.rx(-2*dt, 1) qc.rz(2*dt, 1) qc.cx(1,0) qc.h(1) qc.rz(2*dt, 0) return qc.to_instruction() if to_instruction else qc trotter_gate(np.pi / 6, to_instruction=False).draw("mpl") # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate Trot_gate = trotter_gate(dt) # Number of trotter steps trotter_steps = 15 ### CAN BE >= 4 # Initialize quantum circuit for 3 qubits qr = QuantumRegister(7) qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) qc.x([5]) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) # Simulate time evolution under H_heis3 Hamiltonian for _ in range(trotter_steps): qc.append(Trot_gate, [qr[3], qr[5]]) qc.cx(qr[3], qr[1]) qc.cx(qr[5], qr[3]) # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time/trotter_steps}) t3_qc = transpile(qc, optimization_level=3, basis_gates=["sx", "cx", "rz"]) # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(t3_qc, [qr[1], qr[3], qr[5]]) # Display circuit for confirmation # st_qcs[-1].decompose().draw() # view decomposition of trotter gates st_qcs[-1].draw("mpl") # only view trotter gates from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # backend = provider.get_backend("ibmq_jakarta") shots = 8192 reps = 8 jobs = [] for _ in range(reps): # execute job = execute(st_qcs, backend, shots=shots) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = [] for job in jobs: mit_results.append( meas_fitter.filter.apply(job.result()) ) # Compute the state tomography based on the st_qcs quantum circuits and the results from those ciricuits def state_tomo(result, st_qcs): # The expected final state; necessary to determine state tomography fidelity target_state = (One^One^Zero).to_matrix() # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) # Fit state tomography results tomo_fitter = StateTomographyFitter(result, st_qcs) rho_fit = tomo_fitter.fit(method='lstsq') # Compute fidelity fid = state_fidelity(rho_fit, target_state) return fid # Compute tomography fidelities for each repetition fids = [] for result in mit_results: fid = state_tomo(result, st_qcs) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeAuckland backend = FakeAuckland() ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) depths = [] for _ in range(100): depths.append( transpile( ghz, backend, layout_method='trivial' # Fixed layout mapped in circuit order ).depth() ) plt.figure(figsize=(8, 6)) plt.hist(depths, align='left', color='#AC557C') plt.xlabel('Depth', fontsize=14) plt.ylabel('Counts', fontsize=14);
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
https://github.com/alejomonbar/Quantum-Supply-Chain-Manager
alejomonbar
%load_ext autoreload %autoreload 2 #pip install pennyane #improt pennylane dependnecies import pennylane as qml from pennylane import numpy as np from pennylane.optimize import NesterovMomentumOptimizer # load the csv files import pandas as pd # plot the historical acc and cost import matplotlib.pyplot as plt import seaborn as sns from IPython.display import clear_output clear_output(wait=False) import os data_train = pd.read_csv("dataset/fair_train.csv") X_train,y_train = data_train[data_train.columns[:16]].values, data_train[data_train.columns[16]].values data_test = pd.read_csv("dataset/classic_test.csv") X_test,y_test = data_test[data_test.columns[:16]].values, data_test[data_test.columns[16]].values (X_train.shape, y_train.shape),(X_test.shape, y_test.shape) n_wires = 4 dev = qml.device("default.qubit", wires=n_wires) def block(weights, wires): qml.CNOT(wires=[wires[0],wires[1]]) qml.RY(weights[0], wires=wires[0]) qml.RY(weights[1], wires=wires[1]) n_block_wires = 2 n_params_block = 2 n_blocks = qml.MERA.get_n_blocks(range(n_wires),n_block_wires) n_blocks @qml.qnode(dev) def circuit(weights, x): qml.AmplitudeEmbedding(x, wires=[0,1,2,3],normalize=True,pad_with=True) for w in weights: qml.MERA(range(n_wires),n_block_wires,block, n_params_block, w) #print(w) #print(x) return qml.expval(qml.PauliZ(1)) def variational_classifier(weights, bias, x): return circuit(weights, x) + bias def square_loss(labels, predictions): loss = 0 for l, p in zip(labels, predictions): loss = loss + (l - p) ** 2 loss = loss / len(labels) return loss def accuracy(labels, predictions): loss = 0 for l, p in zip(labels, predictions): if abs(l - p) < 1e-5: loss = loss + 1 loss = loss / len(labels) return loss def cost(weights, bias, X, Y): #print(1) predictions = [variational_classifier(weights, bias, x) for x in X] return square_loss(Y, predictions) np.random.seed(0) num_layers = 1 weights_init = 2*np.pi * np.random.randn(num_layers,n_blocks, n_params_block, requires_grad=True) bias_init = np.array(0.0, requires_grad=True) print(weights_init, bias_init) print(qml.draw(circuit,expansion_strategy='device',wire_order=[0,1,2,3])(weights_init,np.asarray(X_train[0]))) for i in weights_init: print(i[0]) y_train = np.where(y_train < 1, -1, y_train) y_test = np.where(y_test < 1, -1, y_test) from sklearn.utils import shuffle X,y = shuffle(X_train, y_train, random_state=0) from sklearn.model_selection import train_test_split opt = NesterovMomentumOptimizer(0.4) batch_size = 32 num_data = len(y_train) num_train = 0.9 # train the variational classifier weights = weights_init bias = bias_init print() cost_g = [] acc_train = [] acc_test = [] plt.show() for it in range(50): X_train_70, X_test_30, y_train_70, y_test_30 =train_test_split(np.asarray(X), np.asarray(y), train_size=num_train, test_size=1.0-num_train, shuffle=True) # Update the weights by one optimizer step batch_index = np.random.randint(0, len(X_train_70), (batch_size,)) feats_train_batch = X_train_70[batch_index] Y_train_batch = y_train_70[batch_index] weights, bias, _, _ = opt.step(cost, weights, bias, feats_train_batch, Y_train_batch) # Compute predictions on train and validation set predictions_train = [np.sign(variational_classifier(weights, bias, f)) for f in X_train_70] predictions_val = [np.sign(variational_classifier(weights, bias, f)) for f in X_test_30] # Compute accuracy on train and validation set acc_tra = accuracy(y_train_70, predictions_train) acc_val = accuracy(y_test_30, predictions_val) cost_train = cost(weights, bias,X_train, y_train) cost_g.append(cost_train) acc_train.append(acc_tra) acc_test.append(acc_val) clear_output(wait=True) plt.plot(cost_g,label='cost') plt.plot(acc_train,label='acc_train') plt.plot(acc_test,label='acc_test') plt.legend(['cost','acc_train','acc_test']) plt.show() print( "Iter: {:5d} | Cost: {:0.7f} | Acc train: {:0.7f} | Acc validation: {:0.7f} " "".format(it + 1, cost_train, acc_tra, acc_val) ) print(weights) x_test = [] for x in X_test.tolist(): if sum(x) == 0: x[0]=1 x_test.append( x/ np.linalg.norm(x)) x_test[0] y_test y_test_pred = [np.sign(variational_classifier(weights, bias, f)) for f in x_test] y_test_pred = [] for i in y_pred: if i < 0: y_test_pred.append(-1) else: y_test_pred.append(1) from sklearn.metrics import confusion_matrix, roc_curve, auc from sklearn.preprocessing import StandardScaler # demonstration of calculating metrics for a neural network model using sklearn from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score from sklearn.metrics import cohen_kappa_score from sklearn.metrics import roc_auc_score accuracy = accuracy_score(y_test, y_test_pred) print('Accuracy: %f' % accuracy) # precision tp / (tp + fp) precision = precision_score(y_test, y_test_pred) print('Precision: %f' % precision) # recall: tp / (tp + fn) recall = recall_score(y_test, y_test_pred) print('Recall: %f' % recall) # f1: 2 tp / (2 tp + fp + fn) f1 = f1_score(y_test, y_test_pred) print('F1 score: %f' % f1) # kappa kappa = cohen_kappa_score(y_test, y_test_pred) print('Cohens kappa: %f' % kappa) # ROC AUC auc = roc_auc_score(y_test, y_test_pred) print('ROC AUC: %f' % auc) # confusion matrix test_matrix = confusion_matrix(y_test, y_test_pred) print(test_matrix) ax = sns.heatmap(test_matrix, annot=True, cmap='Blues', fmt='g') ax.set_title('Seaborn Confusion Matrix with labels\n\n'); ax.set_xlabel('\nPredicted Values') ax.set_ylabel('Actual Values '); ax.xaxis.set_ticklabels(['0','1']) ax.yaxis.set_ticklabels(['0','1']) ## Display the visualization of the Confusion Matrix. plt.show() y_pred_1 = [int(i) for i in y_test_pred ] y_pred_1 = ["{}\n".format(i) for i in y_pred_1] with open(r'mera_1_layers.csv', 'w') as fp: fp.writelines(y_pred_1)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Alias for Qiskit QPY import.""" def __getattr__(name): import warnings from qiskit import qpy # Skip warning on special Python dunders, which Python occasionally queries on its own accord. if f"__{name[2:-2]}__" != name: warnings.warn( f"Module '{__name__}' is deprecated since Qiskit Terra 0.23," " and will be removed in a future release. Please import from 'qiskit.qpy' instead.", category=DeprecationWarning, stacklevel=2, ) return getattr(qpy, name)