def test_qubits_5_zero_vector(self):
     self.custom = Custom(5, state='zero')
     cct = self.custom.construct_circuit('vector')
     np.testing.assert_array_equal(cct, [
         1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
         0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
         0.0, 0.0, 0.0, 0.0, 0.0, 0.0
     ])
Exemplo n.º 2
0
    def test_eoh(self):
        SIZE = 2

        temp = np.random.random((2**SIZE, 2**SIZE))
        h1 = temp + temp.T
        qubit_op = Operator(matrix=h1)

        temp = np.random.random((2**SIZE, 2**SIZE))
        h1 = temp + temp.T
        evo_op = Operator(matrix=h1)

        state_in = Custom(SIZE, state='random')

        evo_time = 1
        num_time_slices = 100

        eoh = EOH(qubit_op, state_in, evo_op, 'paulis', evo_time,
                  num_time_slices)

        backend = get_aer_backend('statevector_simulator')
        quantum_instance = QuantumInstance(backend,
                                           shots=1,
                                           pass_manager=PassManager())
        # self.log.debug('state_out:\n\n')

        ret = eoh.run(quantum_instance)
        self.log.debug('Evaluation result: {}'.format(ret))
Exemplo n.º 3
0
    def test_iqpe(self, qubitOp):
        self.algorithm = 'IQPE'
        self.log.debug('Testing IQPE')

        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
        num_iterations = 12
        state_in = Custom(self.qubitOp.num_qubits, state_vector=self.ref_eigenvec)
        iqpe = IQPE(self.qubitOp, state_in, num_time_slices, num_iterations,
                    paulis_grouping='random', expansion_mode='suzuki', expansion_order=2, shallow_circuit_concat=True)

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

        result = iqpe.run(quantum_instance)

        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 IQPE:   {}'.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=num_iterations + 3,
            fractional_part_only=True
        )))

        np.testing.assert_approx_equal(result['energy'], self.ref_eigenval.real, significant=2)
Exemplo n.º 4
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,
                  paulis_grouping='random',
                  expansion_mode='suzuki',
                  expansion_order=2,
                  shallow_circuit_concat=True)

        backend = get_aer_backend(simulator)
        run_config = RunConfig(shots=100, max_credits=10, memory=False)
        quantum_instance = QuantumInstance(backend,
                                           run_config,
                                           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)
def evolve(n, evo_time, num_time_slices, expansion_order):
    print("n=", n)
    # Problem setuo
    gamma = 0.2
    marked_bonds = generate_marked_bonds(n)
    #print(marked_bonds)
    h, J = generate_h_J(n, marked_bonds)
    classical_ham = generate_classical_ham(n, h, J)
    driver_ham = generate_driver_ham(n, h, J)
    local_min = generate_local_minima(classical_ham, n)
    minima = []
    for string in local_min:
        minima.append(int(string, 2))

    #print(minima)
    qubit_op = Operator(
        matrix=classical_ham
    )  # create the classical operator, which we measure evals of
    # Construct the evolution operator object which we evolve with
    evo_op = Operator(matrix=(
        classical_ham + gamma * driver_ham
    ))  # add to it the driver to form the operator we actually evolve with
    start_index = randint(0, len(local_min) - 1)
    state_num = int(local_min[start_index], 2)
    state = np.zeros(2**n)
    state[state_num] = 1
    print("initial state of the evolution =", state_num)
    # initialise the circuit
    initial_state = Custom(n, 'uniform', state)

    # expansion order can be toggled in order to speed up calculations
    # Create the evolution of hamiltonian object
    eoh = EOH(qubit_op,
              initial_state,
              evo_op,
              'paulis',
              evo_time,
              num_time_slices,
              expansion_mode='trotter',
              expansion_order=expansion_order)

    circtime = time.time()
    # construct the circuit
    circ = eoh.construct_circuit()
    circtime = time.time() - circtime
    qasmtime = time.time()
    # generate the qasm data
    qasm = circ.qasm()
    qasmtime = time.time() - qasmtime
    print("circuit construction time = ", circtime, " qasm write time = ",
          qasmtime)

    file = open("qasm.txt", 'w')
    file.write(str(state_num) + '\n')
    for i in range(0, 2**n):
        energy_i = classical_ham[i][i]
        file.write(str(energy_i) + '\n')
    file.write(qasm)
    file.close()

    # Here is where we cam actually use the inbuilt qiskit simulator
    """
 def build(self, qc, q, q_ancillas=None, params=None):
     custom_state = Custom(self.num_target_qubits, state_vector=np.sqrt(self.probabilities))
     qc.extend(custom_state.construct_circuit('circuit', q))
 def test_qubits_qubits_given_mistmatch(self):
     with self.assertRaises(ValueError):
         self.custom = Custom(5, state_vector=[1.0] * 23)
 def test_qubits_5_randgiven_vector(self):
     self.custom = Custom(5, state_vector=np.random.rand(32))
     cct = self.custom.construct_circuit('vector')
     prob = np.sqrt(np.sum([x**2 for x in cct]))
     self.assertAlmostEqual(prob, 1.0)
class TestInitialStateCustom(QiskitAquaTestCase):
    def test_qubits_2_zero_vector(self):
        self.custom = Custom(2, state='zero')
        cct = self.custom.construct_circuit('vector')
        np.testing.assert_array_equal(cct, [1.0, 0.0, 0.0, 0.0])

    def test_qubits_5_zero_vector(self):
        self.custom = Custom(5, state='zero')
        cct = self.custom.construct_circuit('vector')
        np.testing.assert_array_equal(cct, [
            1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
            0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
            0.0, 0.0, 0.0, 0.0, 0.0, 0.0
        ])

    def test_qubits_2_zero_circuit(self):
        self.custom = Custom(2, state='zero')
        cct = self.custom.construct_circuit('circuit')
        self.assertEqual(cct.qasm(),
                         'OPENQASM 2.0;\ninclude "qelib1.inc";\nqreg q[2];\n')

    def test_qubits_5_zero_circuit(self):
        self.custom = Custom(5, state='zero')
        cct = self.custom.construct_circuit('circuit')
        self.assertEqual(cct.qasm(),
                         'OPENQASM 2.0;\ninclude "qelib1.inc";\nqreg q[5];\n')

    def test_qubits_2_uniform_vector(self):
        self.custom = Custom(2, state='uniform')
        cct = self.custom.construct_circuit('vector')
        np.testing.assert_array_equal(cct, [0.5] * 4)

    def test_qubits_5_uniform_vector(self):
        self.custom = Custom(5, state='uniform')
        cct = self.custom.construct_circuit('vector')
        np.testing.assert_array_almost_equal(cct, [0.1767767] * 32)

    def test_qubits_2_uniform_circuit(self):
        self.custom = Custom(2, state='uniform')
        cct = self.custom.construct_circuit('circuit')
        self.assertEqual(
            cct.qasm(), 'OPENQASM 2.0;\ninclude "qelib1.inc";\nqreg q[2];\n'
            'u2(0.0,3.14159265358979) q[0];\nu2(0.0,3.14159265358979) q[1];\n')

    def test_qubits_2_random_vector(self):
        self.custom = Custom(2, state='random')
        cct = self.custom.construct_circuit('vector')
        prob = np.sqrt(np.sum([x**2 for x in cct]))
        self.assertAlmostEqual(prob, 1.0)

    def test_qubits_5_random_vector(self):
        self.custom = Custom(5, state='random')
        cct = self.custom.construct_circuit('vector')
        prob = np.sqrt(np.sum([x**2 for x in cct]))
        self.assertAlmostEqual(prob, 1.0)

    def test_qubits_2_given_vector(self):
        self.custom = Custom(2, state_vector=[0.5] * 4)
        cct = self.custom.construct_circuit('vector')
        np.testing.assert_array_equal(cct, [0.5] * 4)

    def test_qubits_5_given_vector(self):
        self.custom = Custom(5, state_vector=[1.0] * 32)
        cct = self.custom.construct_circuit('vector')
        np.testing.assert_array_almost_equal(cct, [0.1767767] * 32)

    def test_qubits_5_randgiven_vector(self):
        self.custom = Custom(5, state_vector=np.random.rand(32))
        cct = self.custom.construct_circuit('vector')
        prob = np.sqrt(np.sum([x**2 for x in cct]))
        self.assertAlmostEqual(prob, 1.0)

    def test_qubits_qubits_given_mistmatch(self):
        with self.assertRaises(ValueError):
            self.custom = Custom(5, state_vector=[1.0] * 23)

    def test_qubits_2_zero_vector_wrong_cct_mode(self):
        self.custom = Custom(5, state='zero')
        with self.assertRaises(ValueError):
            cct = self.custom.construct_circuit('matrix')
 def test_qubits_2_given_vector(self):
     self.custom = Custom(2, state_vector=[0.5] * 4)
     cct = self.custom.construct_circuit('vector')
     np.testing.assert_array_equal(cct, [0.5] * 4)
 def test_qubits_2_random_vector(self):
     self.custom = Custom(2, state='random')
     cct = self.custom.construct_circuit('vector')
     prob = np.sqrt(np.sum([x**2 for x in cct]))
     self.assertAlmostEqual(prob, 1.0)
 def test_qubits_2_uniform_circuit(self):
     self.custom = Custom(2, state='uniform')
     cct = self.custom.construct_circuit('circuit')
     self.assertEqual(
         cct.qasm(), 'OPENQASM 2.0;\ninclude "qelib1.inc";\nqreg q[2];\n'
         'u2(0.0,3.14159265358979) q[0];\nu2(0.0,3.14159265358979) q[1];\n')
 def test_qubits_5_uniform_vector(self):
     self.custom = Custom(5, state='uniform')
     cct = self.custom.construct_circuit('vector')
     np.testing.assert_array_almost_equal(cct, [0.1767767] * 32)
 def test_qubits_5_zero_circuit(self):
     self.custom = Custom(5, state='zero')
     cct = self.custom.construct_circuit('circuit')
     self.assertEqual(cct.qasm(),
                      'OPENQASM 2.0;\ninclude "qelib1.inc";\nqreg q[5];\n')
Exemplo n.º 15
0
    def test_evolution(self):
        SIZE = 2
        #SPARSITY = 0
        #X = [[0, 1], [1, 0]]
        #Y = [[0, -1j], [1j, 0]]
        Z = [[1, 0], [0, -1]]
        I = [[1, 0], [0, 1]]
        # + 0.5 * np.kron(Y, X)# + 0.3 * np.kron(Z, X) + 0.4 * np.kron(Z, Y)
        h1 = np.kron(I, Z)

        # np.random.seed(2)
        temp = np.random.random((2**SIZE, 2**SIZE))
        h1 = temp + temp.T
        qubit_op = Operator(matrix=h1)
        # qubit_op_jw.chop_by_threshold(10 ** -10)

        if qubit_op.grouped_paulis is None:
            qubit_op._matrix_to_paulis()
            qubit_op._paulis_to_grouped_paulis()

        for ps in qubit_op.grouped_paulis:
            for p1 in ps:
                for p2 in ps:
                    if p1 != p2:
                        np.testing.assert_almost_equal(
                            p1[1].to_matrix() @ p2[1].to_matrix(),
                            p2[1].to_matrix() @ p1[1].to_matrix())

        state_in = Custom(SIZE, state='random')

        evo_time = 1
        num_time_slices = 3

        # announces params
        self.log.debug('evo time:        {}'.format(evo_time))
        self.log.debug('num time slices: {}'.format(num_time_slices))
        self.log.debug('state_in:        {}'.format(state_in._state_vector))

        # get the exact state_out from raw matrix multiplication
        state_out_exact = qubit_op.evolve(state_in.construct_circuit('vector'),
                                          evo_time, 'matrix', 0)
        # self.log.debug('exact:\n{}'.format(state_out_exact))
        qubit_op_temp = copy.deepcopy(qubit_op)
        for grouping in ['default', 'random']:
            self.log.debug('Under {} paulis grouping:'.format(grouping))
            for expansion_mode in ['trotter', 'suzuki']:
                self.log.debug(
                    'Under {} expansion mode:'.format(expansion_mode))
                for expansion_order in [
                        1, 2, 3, 4
                ] if expansion_mode == 'suzuki' else [1]:
                    # assure every time the operator from the original one
                    qubit_op = copy.deepcopy(qubit_op_temp)
                    if expansion_mode == 'suzuki':
                        self.log.debug(
                            'With expansion order {}:'.format(expansion_order))
                    state_out_matrix = qubit_op.evolve(
                        state_in.construct_circuit('vector'),
                        evo_time,
                        'matrix',
                        num_time_slices,
                        paulis_grouping=grouping,
                        expansion_mode=expansion_mode,
                        expansion_order=expansion_order)

                    quantum_registers = QuantumRegister(qubit_op.num_qubits)
                    qc = state_in.construct_circuit('circuit',
                                                    quantum_registers)
                    qc += qubit_op.evolve(
                        None,
                        evo_time,
                        'circuit',
                        num_time_slices,
                        quantum_registers=quantum_registers,
                        paulis_grouping=grouping,
                        expansion_mode=expansion_mode,
                        expansion_order=expansion_order,
                    )
                    job = q_execute(qc,
                                    get_aer_backend('statevector_simulator'))
                    state_out_circuit = np.asarray(
                        job.result().get_statevector(qc, decimals=16))

                    self.log.debug(
                        'The fidelity between exact and matrix:   {}'.format(
                            state_fidelity(state_out_exact, state_out_matrix)))
                    self.log.debug(
                        'The fidelity between exact and circuit:  {}'.format(
                            state_fidelity(state_out_exact,
                                           state_out_circuit)))
                    f_mc = state_fidelity(state_out_matrix, state_out_circuit)
                    self.log.debug(
                        'The fidelity between matrix and circuit: {}'.format(
                            f_mc))
                    self.assertAlmostEqual(f_mc, 1)
 def test_qubits_5_given_vector(self):
     self.custom = Custom(5, state_vector=[1.0] * 32)
     cct = self.custom.construct_circuit('vector')
     np.testing.assert_array_almost_equal(cct, [0.1767767] * 32)
 def test_qubits_2_zero_vector_wrong_cct_mode(self):
     self.custom = Custom(5, state='zero')
     with self.assertRaises(ValueError):
         cct = self.custom.construct_circuit('matrix')