Esempio n. 1
0
    def test_kraus_circuit_noise(self, method, device):
        """Test simulation with Kraus quantum errors in circuit."""
        backend = self.backend(method=method, device=device)
        shots = 1000
        error0 = noise.amplitude_damping_error(0.05)
        error1 = noise.amplitude_damping_error(0.15)
        error01 = error1.tensor(error0)

        # Target Circuit 0
        tc0 = QuantumCircuit(2)
        tc0.h(0)
        tc0.append(qi.Kraus(error0), [0])
        tc0.cx(0, 1)
        tc0.append(qi.Kraus(error01), [0, 1])
        target_probs0 = qi.DensityMatrix(tc0).probabilities_dict()

        # Sim circuit 0
        qc0 = QuantumCircuit(2)
        qc0.h(0)
        qc0.append(error0, [0])
        qc0.cx(0, 1)
        qc0.append(error01, [0, 1])
        qc0.measure_all()

        # Target Circuit 1
        tc1 = QuantumCircuit(2)
        tc1.h(1)
        tc1.append(qi.Kraus(error0), [1])
        tc1.cx(1, 0)
        tc1.append(qi.Kraus(error01), [1, 0])
        target_probs1 = qi.DensityMatrix(tc1).probabilities_dict()

        # Sim circuit 1
        qc1 = QuantumCircuit(2)
        qc1.h(1)
        qc1.append(error0, [1])
        qc1.cx(1, 0)
        qc1.append(error01, [1, 0])
        qc1.measure_all()

        result = backend.run([qc0, qc1], shots=shots).result()
        self.assertSuccess(result)
        probs = [{
            key: val / shots
            for key, val in result.get_counts(i).items()
        } for i in range(2)]
        self.assertDictAlmostEqual(target_probs0, probs[0], delta=0.1)
        self.assertDictAlmostEqual(target_probs1, probs[1], delta=0.1)
Esempio n. 2
0
    def _test_kraus_gate_noise_on_QFT(self, **options):
        shots = 10000

        # Build noise model
        error1 = noise.amplitude_damping_error(0.2)
        error2 = error1.tensor(error1)
        noise_model = noise.NoiseModel()
        noise_model.add_all_qubit_quantum_error(error1, ['h'])
        noise_model.add_all_qubit_quantum_error(error2, ['cp', 'swap'])

        backend = self.backend(**options, noise_model=noise_model)
        ideal_circuit = transpile(QFT(3), backend)

        # manaully build noise circuit
        noise_circuit = QuantumCircuit(3)
        for inst, qargs, cargs in ideal_circuit.data:
            noise_circuit.append(inst, qargs, cargs)
            if inst.name == "h":
                noise_circuit.append(error1, qargs)
            elif inst.name in ["cp", "swap"]:
                noise_circuit.append(error2, qargs)
        # compute target counts
        noise_state = DensityMatrix(noise_circuit)
        ref_target = {i: shots * p for i, p in noise_state.probabilities_dict().items()}

        # Run sim
        ideal_circuit.measure_all()
        result = backend.run(ideal_circuit, shots=shots).result()
        self.assertSuccess(result)
        self.compare_counts(result, [ideal_circuit], [ref_target], hex_counts=False, delta=0.1 * shots)
Esempio n. 3
0
def create_amplitude_damping_noise(T_1: float,
                                   t_step: float = 10e-9) -> NoiseModel:
    """Creates an amplitude damping noise model

    Args:
        T_1: Relaxation time (seconds)
        t_step: Discretized time step over which the relaxation occurs over (seconds)
    """

    gamma = 1 - pow(np.e, -1 / T_1 * t_step)
    error = amplitude_damping_error(gamma)
    gate_error = error.tensor(error)

    noise_model = NoiseModel()
    noise_model.add_all_qubit_quantum_error(error, ["id", "u3"])
    noise_model.add_all_qubit_quantum_error(gate_error, ["cx"])
    return noise_model
Esempio n. 4
0
def create_amplitude_damping_noise(T_1, t_step=10e-9):
    """ Creates an amplitude damping noise model
    
    Args:
        T_1 (float) : Relaxation time (seconds)
        t_step (float) : Discretized time step over which the relaxation occurs over (seconds)
    
    Returns:
        qiskit.providers.aer.noise.NoiseModel
    """

    gamma = (1 - pow(np.e, - 1/T_1*t_step))
    error = amplitude_damping_error(gamma)
    gate_error = error.tensor(error)

    noise_model = NoiseModel()
    noise_model.add_all_qubit_quantum_error(error, ['id', 'u3'])
    noise_model.add_all_qubit_quantum_error(gate_error, ['cx'])
    return noise_model
Esempio n. 5
0
    def __init__(self,
                 name = 'simulator_benchmark',
                 apps = {},
                 qubits = DEFAULT_QUBITS,
                 runtime_names = DEFAULT_RUNTIME,
                 measures = DEFAULT_MEASUREMENT_METHODS,
                 measure_counts = DEFAULT_MEASUREMENT_COUNTS,
                 noise_model_names = DEFAULT_NOISE_MODELS,
                 fusion_bits = DEFAULT_FUSION_BITS,
                 fusion = DEFAULT_FUSION,
                 save_qasm = False,
                 save_conf = False):
        self.timeout = 60 * 1000
        self.__name__ = name
        
        self.apps = apps if isinstance(apps, list) else [app for app in apps]
        self.app2rep = {} if isinstance(apps, list) else apps
        self.qubits = qubits
        self.runtime_names = runtime_names
        self.measures = measures
        self.measure_counts = measure_counts
        self.noise_model_names = noise_model_names 
        self.fusion_bits = fusion_bits
        self.fusion = fusion
        self.save_qasm = save_qasm
        self.save_conf = save_conf

        self.params = (self.apps, self.measures, self.measure_counts, self.noise_model_names, self.qubits)
        self.param_names = ["application", "measure_method", "measure_counts", "noise", "qubit"]
        
        all_simulators = [ QASM_SIMULATOR ]
        
        self.simulators = {}
        self.backend_options_list = {}
        self.backend_qubits = {}

        self.noise_models = {}
        self.noise_models[self.NOISE_IDEAL] = None
        if self.NOISE_DAMPING in self.noise_model_names:
            noise_model = NoiseModel()
            error = amplitude_damping_error(1e-3)
            noise_model.add_all_qubit_quantum_error(error, ['u3'])
            self.noise_models[self.NOISE_DAMPING] = noise_model
        if self.NOISE_DEPOLARIZING in self.noise_model_names:
            noise_model = NoiseModel()
            noise_model.add_all_qubit_quantum_error(depolarizing_error(1e-3, 1), ['u3'])
            noise_model.add_all_qubit_quantum_error(depolarizing_error(1e-2, 2), ['cx'])
            self.noise_models[self.NOISE_DEPOLARIZING] = noise_model

        if self.RUNTIME_STATEVECTOR_CPU in runtime_names:
            self.simulators[self.RUNTIME_STATEVECTOR_CPU] = QASM_SIMULATOR
            self.backend_options_list[self.RUNTIME_STATEVECTOR_CPU] = { 'method': self.RUNTIME_STATEVECTOR_CPU, 
                'fusion_max_qubit': self.fusion_bits,
                'fusion_threshold': 0,
                'fusion_enable': self.fusion
            }
            self.backend_qubits[self.RUNTIME_STATEVECTOR_CPU] = self.qubits
        
        if self.RUNTIME_STATEVECTOR_GPU in runtime_names:
            self.simulators[self.RUNTIME_STATEVECTOR_GPU] = QASM_SIMULATOR
            self.backend_options_list[self.RUNTIME_STATEVECTOR_GPU] = { 'method': self.RUNTIME_STATEVECTOR_GPU, 
                'fusion_max_qubit': self.fusion_bits,
                'fusion_threshold': 0,
                'fusion_enable': self.fusion,
                'max_memory_mb': 307200
            }
            self.backend_qubits[self.RUNTIME_STATEVECTOR_GPU] = self.qubits
        
        if self.RUNTIME_MPS_CPU in runtime_names:
            self.simulators[self.RUNTIME_MPS_CPU] = QASM_SIMULATOR
            self.backend_options_list[self.RUNTIME_MPS_CPU] = { 'method': self.RUNTIME_MPS_CPU }
            self.backend_qubits[self.RUNTIME_MPS_CPU] = self.qubits
        
        if self.RUNTIME_DENSITY_MATRIX_CPU in runtime_names:
            self.simulators[self.RUNTIME_DENSITY_MATRIX_CPU] = QASM_SIMULATOR
            self.backend_options_list[self.RUNTIME_DENSITY_MATRIX_CPU] = { 'method': self.RUNTIME_DENSITY_MATRIX_CPU }
            self.backend_qubits[self.RUNTIME_DENSITY_MATRIX_CPU] = [qubit for qubit in qubits if qubit <= 15]
        
        if self.RUNTIME_DENSITY_MATRIX_GPU in runtime_names:
            self.simulators[self.RUNTIME_DENSITY_MATRIX_GPU] = QASM_SIMULATOR
            self.backend_options_list[self.RUNTIME_DENSITY_MATRIX_GPU] = { 'method': self.RUNTIME_DENSITY_MATRIX_GPU }
            self.backend_qubits[self.RUNTIME_DENSITY_MATRIX_GPU] = [qubit for qubit in qubits if qubit <= 15]
Esempio n. 6
0
nwqsim = NWQSimProvider('NWQSim')
print(nwqsim.backends)
backend = nwqsim.backends['dmsim_cpu']
backend.set_n_cpus(4)

#Bell State
circuit = QuantumCircuit(2, 2)
circuit.h(0)
circuit.cx(0, 1)
circuit.measure([0, 1], [0, 1])

noise_model = NoiseModel()
#Add amplitude and phase damping error for 1-qubit
param_amplitude_damping = 0.05
param_phase_damping = 0.03
amplitude_error = amplitude_damping_error(param_amplitude_damping)
phase_error = phase_damping_error(param_phase_damping)
qerror_q1 = phase_error.compose(amplitude_error)

#Add depolarizing error for 2-qubit
param_q2 = 0.08
qerror_q2 = depolarizing_error(param_q2, 2)
q1_superop = SuperOp(qerror_q1)
q2_superop = SuperOp(qerror_q2)
backend.set_noise_1q_sop(q1_superop)
backend.set_noise_2q_sop(q2_superop)

result = execute(circuit, backend, seed_transpiler=111).result()
print(result.get_counts(circuit))
print(result.get_statevector())
Esempio n. 7
0
def main():
    # Noise

    device_backend = FakeVigo()
    coupling_map = device_backend.configuration().coupling_map
    simulator = Aer.get_backend('qasm_simulator')

    noise_model = NoiseModel()
    basis_gates = noise_model.basis_gates
    error = amplitude_damping_error(0.5)
    # error = depolarizing_error(0.5, 1)
    noise_model.add_all_qubit_quantum_error(error, ['id', 'u1', 'u2', 'u3'])

    # Circuit
    circ = QuantumCircuit(1, 1)
    circ.h(0)
    circ.measure([0], [0])
    print("*" * 25 + " Circuit " + "*" * 25)
    print(circ.draw())

    model1 = {'name': 'noisy', 'model': noise_model}
    model2 = {'name': 'ideal', 'model': None}
    noise_models = [model1, model2]
    print()
    print("*" * 25 + " Noise Models " + "*" * 25)
    pprint(noise_models)

    # Execution
    Dataset = [(run_circuit(circ, simulator, nm['model'], coupling_map,
                            basis_gates), nm) for nm in noise_models]

    # Data Prep
    for counts, nm in Dataset:
        counts.setdefault('0', 0)
        counts.setdefault('1', 0)

    X = [[x[1] for x in sorted(counts.items())] for counts, nm in Dataset]
    Y_raw = [nm['name'] for counts, nm in Dataset]
    zeros = [x[0] for x in X]
    le = preprocessing.LabelEncoder()
    le.fit(Y_raw)
    Y = le.transform(Y_raw)
    print()
    print("*" * 25 + " Dataset " + "*" * 25)
    print("Features: ", X)
    print("Labels: ", Y_raw)
    print("Encoded Labels: ", Y)

    # Training Classifier
    clf = RandomForestClassifier(random_state=0)
    clf.fit(X, Y)

    print()
    print("*" * 25 + " Predictions " + "*" * 25)

    # Predict labels on original data
    print("Prediction on training set: ",
          list(le.inverse_transform(clf.predict(X))))

    # Predict labels on new data
    Xtest = []
    Ytest = []
    for i in range(max(0, min(zeros) - 50), min(max(zeros) + 51, 1001)):
        feature = [[i, 1000 - i]]
        prediction = list(le.inverse_transform(clf.predict(feature)))
        # print("Prediction on {}: {}".format(feature, prediction))
        Xtest.append(i)
        Ytest.append(prediction[0])

    # Plot Diagrams

    fig = plt.figure()
    plt.scatter(Xtest, Ytest, label="test set")
    plt.scatter(zeros, Y_raw, label="training set")
    plt.xlabel("Feature = Count of '0' measurements")
    plt.ylabel("Predicted Label")
    plt.legend()
    # fig.axes.append(circ.draw(output='mpl').axes[0])
    plt.show()