Esempio n. 1
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 = Aer.get_backend('statevector_simulator')
        quantum_instance = QuantumInstance(backend, pass_manager=PassManager())
        # self.log.debug('state_out:\n\n')

        ret = eoh.run(quantum_instance)
        self.log.debug('Evaluation result: {}'.format(ret))
Esempio n. 2
0
    def test_eoh(self):
        SIZE = 2

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

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

        state_in = get_initial_state_instance('CUSTOM')
        state_in.init_args(SIZE, state='random')

        evo_time = 1
        num_time_slices = 100

        eoh = get_algorithm_instance('EOH')
        eoh.setup_quantum_backend(skip_transpiler=True)
        # self.log.debug('state_out:\n\n')

        eoh.init_args(qubitOp, 'paulis', state_in, evoOp, evo_time,
                      num_time_slices)
        ret = eoh.run()
        self.log.debug('Evaluation result: {}'.format(ret))
Esempio n. 3
0
    def test_grouped_paulis(self):
        n = 3  # number of qubits

        pg = pauli_group(n, case=1)
        self.assertTrue(pg != -1, "Error in pauli_group()")

        pg = [[1.0, x] for x in pg]  # create paulis with equal weight
        self.log.debug("Number of Paulis: {}".format(len(pg)))

        hamOpOriginal = Operator(paulis=pg, coloring=None)
        hamOpOriginal._paulis_to_grouped_paulis()
        gpOriginal = hamOpOriginal.grouped_paulis

        hamOpNew = Operator(paulis=pg, coloring="largest-degree")
        hamOpNew._paulis_to_grouped_paulis()
        gpNew = hamOpNew.grouped_paulis

        self.log.debug("#groups in original= {} #groups in new={}".format(len(gpOriginal), len(gpNew)))

        self.log.debug("------- Original --------")
        for each in gpOriginal:
            for x in each:
                self.log.debug('{} {}'.format(x[0], x[1].to_label()))
            self.log.debug('---')

        self.log.debug("-------- New ------------")
        for each in gpNew:
            for x in each:
                self.log.debug('{} {}'.format(x[0], x[1].to_label()))
            self.log.debug('---')
Esempio n. 4
0
    def __init__(self, cost_operator, p, initial_state=None):
        self._cost_operator = cost_operator
        self._p = p
        self._initial_state = initial_state
        self.num_parameters = 2 * p
        self.parameter_bounds = [(0, np.pi)] * p + [(0, 2 * np.pi)] * p
        self.preferred_init_points = [0] * p * 2

        # prepare the mixer operator
        v = np.zeros(self._cost_operator.num_qubits)
        ws = np.eye(self._cost_operator.num_qubits)
        self._mixer_operator = reduce(lambda x, y: x + y, [
            Operator([[1, Pauli(v, ws[i, :])]])
            for i in range(self._cost_operator.num_qubits)
        ])
Esempio n. 5
0
def get_portfolio_qubitops(mu, sigma, q, budget, penalty):

    # get problem dimension
    n = len(mu)
    e = np.ones(n)
    E = np.matmul(np.asmatrix(e).T, np.asmatrix(e))

    # map problem to Ising model
    offset = -np.dot(
        mu, e
    ) / 2 + penalty * budget**2 - budget * n * penalty + n**2 * penalty / 4 + q / 4 * np.dot(
        e, np.dot(sigma, e))
    mu_z = mu / 2 + budget * penalty * e - n * penalty / 2 * e - q / 2 * np.dot(
        sigma, e)
    sigma_z = penalty / 4 * E + q / 4 * sigma

    # construct operator
    pauli_list = []
    for i in range(n):
        i_ = i
        # i_ = n-i-1
        if np.abs(mu_z[i_]) > 1e-6:
            xp = np.zeros(n, dtype=np.bool)
            zp = np.zeros(n, dtype=np.bool)
            zp[i_] = True
            pauli_list.append([mu_z[i_], Pauli(zp, xp)])
        for j in range(i):
            j_ = j
            # j_ = n-j-1
            if np.abs(sigma_z[i_, j_]) > 1e-6:
                xp = np.zeros(n, dtype=np.bool)
                zp = np.zeros(n, dtype=np.bool)
                zp[i_] = True
                zp[j_] = True
                pauli_list.append([2 * sigma_z[i_, j_], Pauli(zp, xp)])
        offset += sigma_z[i_, i_]

    return Operator(paulis=pauli_list), offset
Esempio n. 6
0
def limit_paulis(mat, n=5, sparsity=None):
    """
    Limits the number of Pauli basis matrices of a hermitian matrix to the n
    highest magnitude ones.
    Args:
        mat (np.ndarray): Input matrix
        n (int): number of surviving Pauli matrices (default=5)
        sparsity (float < 1): sparsity of matrix

    Returns:
        scipy.sparse.csr_matrix
    """
    from qiskit_aqua.operator import Operator
    # Bringing matrix into form 2**Nx2**N
    l = mat.shape[0]
    if np.log2(l) % 1 != 0:
        k = int(2**np.ceil(np.log2(l)))
        m = np.zeros([k, k], dtype=np.complex128)
        m[:l, :l] = mat
        m[l:, l:] = np.identity(k-l)
        mat = m

    # Getting Pauli matrices
    op = Operator(matrix=mat)
    op._check_representation("paulis")
    op._simplify_paulis()
    paulis = sorted(op.paulis, key=lambda x: abs(x[0]), reverse=True)
    g = 2**op.num_qubits
    mat = scipy.sparse.csr_matrix(([], ([], [])), shape=(g, g),
                                  dtype=np.complex128)

    # Truncation
    if sparsity is None:
        for pa in paulis[:n]:
            mat += pa[0]*pa[1].to_spmatrix()
    else:
        idx = 0
        while mat[:l, :l].nnz/l**2 < sparsity:
            mat += paulis[idx][0]*paulis[idx][1].to_spmatrix()
            idx += 1
        n = idx
    mat = mat.toarray()
    return mat[:l, :l]
Esempio n. 7
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
        qubitOp = Operator(matrix=h1)
        # qubitOp_jw.chop_by_threshold(10 ** -10)

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

        for ps in qubitOp.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 = get_initial_state_instance('CUSTOM')
        state_in.init_args(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 = qubitOp.evolve(state_in.construct_circuit('vector'),
                                         evo_time, 'matrix', 0)
        # self.log.debug('exact:\n{}'.format(state_out_exact))
        qubitOp_temp = copy.deepcopy(qubitOp)
        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
                    qubitOp = copy.deepcopy(qubitOp_temp)
                    if expansion_mode == 'suzuki':
                        self.log.debug(
                            'With expansion order {}:'.format(expansion_order))
                    state_out_matrix = qubitOp.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(qubitOp.num_qubits)
                    qc = state_in.construct_circuit('circuit',
                                                    quantum_registers)
                    qc += qubitOp.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, qiskit.Aer.get_backend('statevector_simulator'))
                    state_out_circuit = np.asarray(
                        job.result().get_statevector(qc))

                    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 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
    """
Esempio n. 9
0
        "label": "XX"
    }]
}

# ======================
# setting up the circuit
# ======================

# define the initial state
init_state = Zero(num_qubits)

# get a variational ansatz
ansatz = RY(num_qubits, initial_state=init_state)

# operator from hamiltonian
qubit_op = Operator.load_from_dict(pauli_dict)

# get an optimizer
optimizer = COBYLA(maxiter=1000, disp=True)

# form the algorithm
vqe = VQE(qubit_op, ansatz, optimizer)

# get a backend
backend = get_aer_backend("statevector_simulator")

# get a quantum instance
qinstance = QuantumInstance(backend, shots=1024)

# ===================
# do the optimization