예제 #1
0
    def test_qsvm_kernel_binary_directly_statevector(self):

        ref_kernel_testing = np.array(
            [[0.1443953, 0.18170069, 0.47479649, 0.14691763],
             [0.33041779, 0.37663733, 0.02115561, 0.16106199]])

        ref_support_vectors = np.array([[2.95309709, 2.51327412],
                                        [3.14159265, 4.08407045],
                                        [4.08407045, 2.26194671],
                                        [4.46106157, 2.38761042]])

        backend = get_aer_backend('statevector_simulator')
        num_qubits = 2
        feature_map = SecondOrderExpansion(num_qubits=num_qubits,
                                           depth=2,
                                           entangler_map={0: [1]})
        svm = QSVMKernel(feature_map, self.training_data, self.testing_data,
                         None)
        svm.random_seed = self.random_seed

        quantum_instance = QuantumInstance(backend,
                                           seed_mapper=self.random_seed)
        result = svm.run(quantum_instance)

        ori_alphas = result['svm']['alphas']

        np.testing.assert_array_almost_equal(result['kernel_matrix_testing'],
                                             ref_kernel_testing,
                                             decimal=4)

        self.assertEqual(len(result['svm']['support_vectors']), 4)
        np.testing.assert_array_almost_equal(result['svm']['support_vectors'],
                                             ref_support_vectors,
                                             decimal=4)

        self.assertEqual(result['testing_accuracy'], 0.5)

        file_path = self._get_resource_path('qsvm_kernel_test.npz')
        svm.save_model(file_path)

        self.assertTrue(os.path.exists(file_path))

        loaded_svm = QSVMKernel(feature_map, self.training_data, None, None)
        loaded_svm.load_model(file_path)

        np.testing.assert_array_almost_equal(
            loaded_svm.ret['svm']['support_vectors'],
            ref_support_vectors,
            decimal=4)

        np.testing.assert_array_almost_equal(loaded_svm.ret['svm']['alphas'],
                                             ori_alphas,
                                             decimal=4)

        loaded_test_acc = loaded_svm.test(svm.test_dataset[0],
                                          svm.test_dataset[1],
                                          quantum_instance)
        self.assertEqual(result['testing_accuracy'], loaded_test_acc)

        np.testing.assert_array_almost_equal(
            loaded_svm.ret['kernel_matrix_testing'],
            ref_kernel_testing,
            decimal=4)

        if os.path.exists(file_path):
            try:
                os.remove(file_path)
            except:
                pass
예제 #2
0
    def test_qsvm_kernel_multiclass_error_correcting_code(self):

        backend = get_aer_backend('qasm_simulator')
        training_input = {
            'A':
            np.asarray([[0.6560706, 0.17605998], [0.25776033, 0.47628296],
                        [0.8690704, 0.70847635]]),
            'B':
            np.asarray([[0.38857596, -0.33775802], [0.49946978, -0.48727951],
                        [0.49156185, -0.3660534]]),
            'C':
            np.asarray([[-0.68088231, 0.46824423], [-0.56167659, 0.65270294],
                        [-0.82139073, 0.29941512]])
        }

        test_input = {
            'A':
            np.asarray([[0.57483139, 0.47120732], [0.48372348, 0.25438544],
                        [0.48142649, 0.15931707]]),
            'B':
            np.asarray([[-0.06048935, -0.48345293], [-0.01065613, -0.33910828],
                        [0.06183066, -0.53376975]]),
            'C':
            np.asarray([[-0.74561108, 0.27047295], [-0.69942965, 0.11885162],
                        [-0.66489165, 0.1181712]])
        }

        total_array = np.concatenate(
            (test_input['A'], test_input['B'], test_input['C']))

        params = {
            'problem': {
                'name': 'svm_classification',
                'random_seed': self.random_seed
            },
            'algorithm': {
                'name': 'QSVM.Kernel',
            },
            'backend': {
                'shots': self.shots
            },
            'multiclass_extension': {
                'name': 'ErrorCorrectingCode',
                'code_size': 5
            },
            'feature_map': {
                'name': 'SecondOrderExpansion',
                'depth': 2,
                'entangler_map': {
                    0: [1]
                }
            }
        }

        algo_input = SVMInput(training_input, test_input, total_array)

        result = run_algorithm(params, algo_input, backend=backend)
        self.assertAlmostEqual(result['testing_accuracy'],
                               0.55555555,
                               places=4,
                               msg='Please ensure you are using C++ simulator')
        self.assertEqual(result['predicted_classes'],
                         ['A', 'A', 'C', 'A', 'A', 'A', 'C', 'C', 'C'])
예제 #3
0
    def test_qpe(self, qubitOp, simulator):
        self.algorithm = 'QPE'
        self.log.debug('Testing QPE')

        self.qubitOp = qubitOp

        exact_eigensolver = ExactEigensolver(self.qubitOp, k=1)
        results = exact_eigensolver.run()

        w = results['eigvals']
        v = results['eigvecs']

        self.qubitOp.to_matrix()
        np.testing.assert_almost_equal(self.qubitOp.matrix @ v[0], w[0] * v[0])
        np.testing.assert_almost_equal(
            expm(-1.j * sparse.csc_matrix(self.qubitOp.matrix)) @ v[0],
            np.exp(-1.j * w[0]) * v[0])

        self.ref_eigenval = w[0]
        self.ref_eigenvec = v[0]
        self.log.debug('The exact eigenvalue is:       {}'.format(
            self.ref_eigenval))
        self.log.debug('The corresponding eigenvector: {}'.format(
            self.ref_eigenvec))

        num_time_slices = 50
        n_ancillae = 6

        state_in = Custom(self.qubitOp.num_qubits,
                          state_vector=self.ref_eigenvec)
        iqft = Standard(n_ancillae)

        qpe = QPE(self.qubitOp,
                  state_in,
                  iqft,
                  num_time_slices,
                  n_ancillae,
                  expansion_mode='suzuki',
                  expansion_order=2,
                  shallow_circuit_concat=True)

        backend = get_aer_backend(simulator)
        quantum_instance = QuantumInstance(backend,
                                           shots=100,
                                           pass_manager=PassManager())

        # run qpe
        result = qpe.run(quantum_instance)
        # self.log.debug('transformed operator paulis:\n{}'.format(self.qubitOp.print_operators('paulis')))

        # report result
        self.log.debug('top result str label:         {}'.format(
            result['top_measurement_label']))
        self.log.debug('top result in decimal:        {}'.format(
            result['top_measurement_decimal']))
        self.log.debug('stretch:                      {}'.format(
            result['stretch']))
        self.log.debug('translation:                  {}'.format(
            result['translation']))
        self.log.debug('final eigenvalue from QPE:    {}'.format(
            result['energy']))
        self.log.debug('reference eigenvalue:         {}'.format(
            self.ref_eigenval))
        self.log.debug('ref eigenvalue (transformed): {}'.format(
            (self.ref_eigenval + result['translation']) * result['stretch']))
        self.log.debug('reference binary str label:   {}'.format(
            decimal_to_binary(
                (self.ref_eigenval.real + result['translation']) *
                result['stretch'],
                max_num_digits=n_ancillae + 3,
                fractional_part_only=True)))

        np.testing.assert_approx_equal(result['energy'],
                                       self.ref_eigenval.real,
                                       significant=2)
예제 #4
0
    def test_mcmt(self, num_controls, num_targets,
                  single_control_gate_function):

        if num_controls + num_targets > 10:
            return

        c = QuantumRegister(num_controls, name='c')
        o = QuantumRegister(num_targets, name='o')

        subsets = [tuple(range(i)) for i in range(num_controls + 1)]
        for subset in subsets:
            # Expecting some other modes
            for mode in ['basic']:
                self.log.debug("Subset is {0}".format(subset))
                self.log.debug("Num controls = {0}".format(num_controls))
                self.log.debug("Num targets = {0}".format(num_targets))
                self.log.debug("Gate function is {0}".format(
                    single_control_gate_function.__name__))
                self.log.debug("Mode is {0}".format(mode))
                qc = QuantumCircuit(o, c)
                # Initialize all targets to 1, just to be sure that
                # the generic gate has some effect (f.e. Z gate has no effect
                # on a 0 state)
                qc.x(o)

                if mode == 'basic':
                    if num_controls <= 1:
                        num_ancillae = 0
                    else:
                        num_ancillae = num_controls - 1
                    self.log.debug("Num ancillae is {0} ".format(num_ancillae))

                if num_ancillae > 0:
                    a = QuantumRegister(num_ancillae, name='a')
                    qc.add_register(a)

                for idx in subset:
                    qc.x(c[idx])
                qc.mcmt([c[i] for i in range(num_controls)],
                        [a[i] for i in range(num_ancillae)],
                        single_control_gate_function,
                        o,
                        mode=mode)
                for idx in subset:
                    qc.x(c[idx])

                vec = np.asarray(
                    q_execute(qc, get_aer_backend(
                        'statevector_simulator')).result().get_statevector(
                            qc, decimals=16))
                # target register is initially |11...1>, with length equal to 2**(n_targets)
                vec_exp = np.array([0] * (2**(num_targets) - 1) + [1])
                if (single_control_gate_function.__name__ == "cz"):
                    # Z gate flips the last qubit only if it's applied an odd
                    # number of times
                    if (len(subset) == num_controls
                            and (num_controls % 2) == 1):
                        vec_exp[-1] = -1
                elif (single_control_gate_function.__name__ == "ch"):
                    # if all the control qubits have been activated,
                    # we repeatedly apply the kronecker product of the Hadamard
                    # with itself and then multiply the results for the original
                    # state of the target qubits
                    if (len(subset) == num_controls):
                        h = 1 / np.sqrt(2) * np.array([[1, 1], [1, -1]])
                        h_tot = np.array([1])
                        for i in range(num_targets):
                            h_tot = np.kron(h_tot, h)
                        vec_exp = np.dot(h_tot, vec_exp)
                else:
                    raise ValueError("Gate {0} not implementend yet".format(
                        single_control_gate_function.__name__))
                # append the remaining part of the state
                vec_exp = np.concatenate(
                    (vec_exp,
                     [0] * (2**(num_controls + num_ancillae + num_targets) -
                            vec_exp.size)))
                f = state_fidelity(vec, vec_exp)
                self.assertAlmostEqual(f, 1)
예제 #5
0
 def test_deutschjozsa(self, dj_input):
     backend = get_aer_backend('qasm_simulator')
     oracle = DeutschJozsaOracle(dj_input)
     algorithm = DeutschJozsa(oracle)
     result = algorithm.run(backend)
     self.assertTrue(result['oracle_evaluation'])
예제 #6
0
 def test_simon(self, simon_input):
     backend = get_aer_backend('qasm_simulator')
     oracle = SimonOracle(simon_input)
     algorithm = Simon(oracle)
     result = algorithm.run(backend)
     self.assertTrue(result['oracle_evaluation'])
예제 #7
0
def evaluate_circuit(beta, gamma, Hc, Hm, qr, circuit_init, n_qubits):
    circuit = create_circuit(beta, gamma, Hc, Hm, qr, circuit_init, n_qubits)
    print(circuit.n_qubits)
    return np.real(
        Hc.eval("matrix", circuit,
                get_aer_backend('statevector_simulator'))[0])
예제 #8
0
파일: QC-env-qs.py 프로젝트: Epheflower/QC
def evaluate_circuit(beta_gamma):
    n = len(beta_gamma) // 2
    circuit = create_circuit(beta_gamma[:n], beta_gamma[n:])
    return np.real(
        H_c.eval("matrix", circuit,
                 get_aer_backend('statevector_simulator'))[0])
예제 #9
0
 def test_bernsteinvazirani(self, bv_input):
     backend = get_aer_backend('qasm_simulator')
     oracle = BernsteinVaziraniOracle(bv_input)
     algorithm = BernsteinVazirani(oracle)
     result = algorithm.run(backend)
     self.assertTrue(result['oracle_evaluation'])
예제 #10
0
    def test_qsvm_variational_callback(self):

        tmp_filename = 'qsvm_callback_test.csv'
        is_file_exist = os.path.exists(self._get_resource_path(tmp_filename))
        if is_file_exist:
            os.remove(self._get_resource_path(tmp_filename))

        def store_intermediate_result(eval_count, parameters, cost,
                                      batch_index):
            with open(self._get_resource_path(tmp_filename), 'a') as f:
                content = "{},{},{:.5f},{}".format(eval_count, parameters,
                                                   cost, batch_index)
                print(content, file=f, flush=True)

        np.random.seed(self.random_seed)
        backend = get_aer_backend('qasm_simulator')

        num_qubits = 2
        optimizer = COBYLA(maxiter=3)
        feature_map = SecondOrderExpansion(num_qubits=num_qubits, depth=2)
        var_form = RY(num_qubits=num_qubits, depth=1)

        svm = QSVMVariational(optimizer,
                              feature_map,
                              var_form,
                              self.training_data,
                              self.testing_data,
                              callback=store_intermediate_result)
        svm.random_seed = self.random_seed
        run_config = RunConfig(shots=1024,
                               max_credits=10,
                               memory=False,
                               seed=self.random_seed)
        quantum_instance = QuantumInstance(backend,
                                           run_config,
                                           seed_mapper=self.random_seed)
        svm.run(quantum_instance)

        is_file_exist = os.path.exists(self._get_resource_path(tmp_filename))
        self.assertTrue(is_file_exist, "Does not store content successfully.")

        # check the content
        ref_content = [[
            "0", "[ 0.18863864 -1.08197582  1.74432295  1.29765602]",
            "0.53367", "0"
        ],
                       [
                           "1",
                           "[ 1.18863864 -1.08197582  1.74432295  1.29765602]",
                           "0.57261", "1"
                       ],
                       [
                           "2",
                           "[ 0.18863864 -0.08197582  1.74432295  1.29765602]",
                           "0.47137", "2"
                       ]]
        with open(self._get_resource_path(tmp_filename)) as f:
            idx = 0
            for record in f.readlines():
                eval_count, parameters, cost, batch_index = record.split(",")
                self.assertEqual(eval_count.strip(), ref_content[idx][0])
                self.assertEqual(parameters, ref_content[idx][1])
                self.assertEqual(cost.strip(), ref_content[idx][2])
                self.assertEqual(batch_index.strip(), ref_content[idx][3])
                idx += 1
        if is_file_exist:
            os.remove(self._get_resource_path(tmp_filename))
예제 #11
0
    def test_qsvm_variational_directly(self):
        np.random.seed(self.random_seed)
        backend = get_aer_backend('qasm_simulator')

        num_qubits = 2
        optimizer = SPSA(max_trials=10,
                         save_steps=1,
                         c0=4.0,
                         skip_calibration=True)
        feature_map = SecondOrderExpansion(num_qubits=num_qubits, depth=2)
        var_form = RYRZ(num_qubits=num_qubits, depth=3)

        svm = QSVMVariational(optimizer, feature_map, var_form,
                              self.training_data, self.testing_data)
        svm.random_seed = self.random_seed
        run_config = RunConfig(shots=1024,
                               max_credits=10,
                               memory=False,
                               seed=self.random_seed)
        quantum_instance = QuantumInstance(backend,
                                           run_config,
                                           seed_mapper=self.random_seed)
        result = svm.run(quantum_instance)

        np.testing.assert_array_almost_equal(result['opt_params'],
                                             self.ref_opt_params,
                                             decimal=4)
        np.testing.assert_array_almost_equal(result['training_loss'],
                                             self.ref_train_loss,
                                             decimal=8)

        self.assertEqual(result['testing_accuracy'], 1.0)

        file_path = self._get_resource_path('qsvm_variational_test.npz')
        svm.save_model(file_path)

        self.assertTrue(os.path.exists(file_path))

        loaded_svm = QSVMVariational(optimizer, feature_map, var_form,
                                     self.training_data, None)
        loaded_svm.load_model(file_path)

        np.testing.assert_array_almost_equal(loaded_svm.ret['opt_params'],
                                             self.ref_opt_params,
                                             decimal=4)

        loaded_test_acc = loaded_svm.test(svm.test_dataset[0],
                                          svm.test_dataset[1],
                                          quantum_instance)
        self.assertEqual(result['testing_accuracy'], loaded_test_acc)

        predicted_probs, predicted_labels = loaded_svm.predict(
            self.testing_data['A'], quantum_instance)
        np.testing.assert_array_almost_equal(predicted_probs,
                                             self.ref_prediction_a_probs,
                                             decimal=8)
        np.testing.assert_array_equal(predicted_labels,
                                      self.ref_prediction_a_label)

        if os.path.exists(file_path):
            try:
                os.remove(file_path)
            except:
                pass