コード例 #1
0
def convert_to_wpauli_list(term):
    if term[0] == complex(0):
        separated_ham = 0 * WeightedPauliOperator.from_list(
            paulis=[Pauli.from_label('I' * num_qubits)])
    else:
        separated_ham = WeightedPauliOperator.from_list([term[1]], [term[0]])
    return separated_ham
コード例 #2
0
def Gen_rand_1_ham(num_terms, num_qubits):
	wop = 0*WeightedPauliOperator.from_list(paulis = [Pauli.from_label('I'*num_qubits)])
	ham = wop
	for i in range(0,num_terms):
		pauli = random_pauli(num_qubits)
		wpauli = WeightedPauliOperator.from_list(paulis=[pauli], weights=[1.0])
		ham = ham + wpauli
	return ham
コード例 #3
0
def Gen_rand_rand_ham(num_terms, num_qubits):
	wop = 0*WeightedPauliOperator.from_list(paulis = [Pauli.from_label('I'*num_qubits)])
	ham = wop
	pauli_list = []
	i = 0
	while i < num_terms:
		pauli = random_pauli(num_qubits)
		if pauli_list.count(pauli) == 0:
			wpauli = WeightedPauliOperator.from_list(paulis=[pauli], weights=[np.random.uniform(0,1)])
			ham = ham + wpauli
			pauli_list.append(pauli)
			i = i+1
	return ham
コード例 #4
0
    def test_negation_operator(self):
        """ negation operator test """
        paulis = [Pauli.from_label(x) for x in ['IXYZ', 'XXZY', 'IIZZ', 'XXYY', 'ZZXX', 'YYYY']]
        coeffs = [0.2, 0.6, 0.8, -0.2, -0.6, -0.8]
        op1 = WeightedPauliOperator.from_list(paulis, coeffs)
        coeffs = [-0.2, -0.6, -0.8, 0.2, 0.6, 0.8]
        op2 = WeightedPauliOperator.from_list(paulis, coeffs)

        self.assertNotEqual(op1, op2)
        self.assertEqual(op1, -op2)
        self.assertEqual(-op1, op2)
        op1 = op1 * -1.0
        self.assertEqual(op1, op2)
コード例 #5
0
def split_into_paulis(ham):
    ham_details = ham.print_details()
    ham_list = ham_details.split('\n')
    pauli_list = [0] * (len(ham_list) - 1
                        )  #exclude last entry of ham list bc is just blank
    name_list = [0] * (len(ham_list) - 1)
    weight_list = [0] * (len(ham_list) - 1)
    for counter in range(0, len(ham_list) - 1, 1):
        pauli = Pauli.from_label(ham_list[counter][:4])
        name_list[counter] = WeightedPauliOperator.from_list(
            [pauli]).print_details()
        weight_list[counter] = complex(ham_list[counter][6:-1])
        pauli_list[counter] = WeightedPauliOperator.from_list([pauli])
    return weight_list, pauli_list, name_list
    def test_chop(self):
        """ chop test """
        paulis = [
            Pauli.from_label(x)
            for x in ['IIXX', 'ZZXX', 'ZZZZ', 'XXZZ', 'XXXX', 'IXXX']
        ]
        coeffs = [0.2, 0.3, 0.4, 0.5, 0.6, 0.7]
        op = WeightedPauliOperator.from_list(paulis, coeffs)
        grouped_op = op_converter.to_tpb_grouped_weighted_pauli_operator(
            op, TPBGroupedWeightedPauliOperator.sorted_grouping)

        original_num_basis = len(grouped_op.basis)
        chopped_grouped_op = grouped_op.chop(0.35, copy=True)
        self.assertLessEqual(len(chopped_grouped_op.basis), 3)
        self.assertLessEqual(len(chopped_grouped_op.basis), original_num_basis)
        # ZZXX group is remove
        for b, _ in chopped_grouped_op.basis:
            self.assertFalse(b.to_label() == 'ZZXX')

        chopped_grouped_op = grouped_op.chop(0.55, copy=True)
        self.assertLessEqual(len(chopped_grouped_op.basis), 1)
        self.assertLessEqual(len(chopped_grouped_op.basis), original_num_basis)

        for b, _ in chopped_grouped_op.basis:
            self.assertFalse(b.to_label() == 'ZZXX')
            self.assertFalse(b.to_label() == 'ZZZZ')
            self.assertFalse(b.to_label() == 'XXZZ')
コード例 #7
0
    def setUp(self):
        super().setUp()
        seed = 0
        np.random.seed(seed)
        aqua_globals.random_seed = seed

        self.num_qubits = 3
        paulis = [
            Pauli.from_label(pauli_label)
            for pauli_label in itertools.product('IXYZ',
                                                 repeat=self.num_qubits)
        ]
        weights = np.random.random(len(paulis))
        self.qubit_op = WeightedPauliOperator.from_list(paulis, weights)
        self.var_form = RYRZ(self.qubit_op.num_qubits, 1)

        qasm_simulator = BasicAer.get_backend('qasm_simulator')
        self.quantum_instance_qasm = QuantumInstance(qasm_simulator,
                                                     shots=65536,
                                                     seed_simulator=seed,
                                                     seed_transpiler=seed)
        statevector_simulator = BasicAer.get_backend('statevector_simulator')
        self.quantum_instance_statevector = QuantumInstance(
            statevector_simulator,
            shots=1,
            seed_simulator=seed,
            seed_transpiler=seed)
    def setUp(self):
        super().setUp()
        seed = 0
        aqua_globals.random_seed = seed

        self.num_qubits = 3
        paulis = [
            Pauli.from_label(pauli_label)
            for pauli_label in itertools.product('IXYZ',
                                                 repeat=self.num_qubits)
        ]
        weights = aqua_globals.random.random(len(paulis))
        self.qubit_op = WeightedPauliOperator.from_list(paulis, weights)
        warnings.filterwarnings('ignore', category=DeprecationWarning)
        self.var_form = RYRZ(self.qubit_op.num_qubits, 1)
        warnings.filterwarnings('always', category=DeprecationWarning)

        qasm_simulator = BasicAer.get_backend('qasm_simulator')
        self.quantum_instance_qasm = QuantumInstance(qasm_simulator,
                                                     shots=65536,
                                                     seed_simulator=seed,
                                                     seed_transpiler=seed)

        statevector_simulator = BasicAer.get_backend('statevector_simulator')
        self.quantum_instance_statevector = \
            QuantumInstance(statevector_simulator, shots=1,
                            seed_simulator=seed, seed_transpiler=seed)
コード例 #9
0
 def output_dressed_ham(self):
     i = 0
     term_sums = [0] * 4**self.num_qubits
     sum_term = self.zero_term
     other_sum_term = self.zero_term
     for term in self.ham_term_list:
         for descendant in term['descendants']:
             weight, pauli, name = split_into_paulis(descendant)
             term_sums[int(base_4_map(
                 name[0]))] = np.real(term_sums[int(base_4_map(
                     name[0]))]) + np.real(weight[0] * self.constants[i])
             other_sum_term = other_sum_term + np.real(
                 weight[0] * self.constants[i]) * pauli[0]
             i = i + 1
     for i, entry in enumerate(term_sums):
         if abs(entry) > 0.000001:
             pauli_num = quaternary(i)
             pauli_name = create_term(pauli_num, self.num_qubits)
             pauli = Pauli.from_label(pauli_name)
             wpauli = WeightedPauliOperator.from_list(paulis=[pauli])
             sum_term = entry * wpauli + sum_term
     print(sum_term.print_details())
     mat = to_matrix_operator(sum_term)
     print(mat.print_details())
     #mat_2 = to_matrix_operator(other_sum_term)
     #print(mat_2.print_details())
     print(term_sums)
    def test_sorted_grouping(self):
        """Test with color grouping approach."""
        num_qubits = 2
        paulis = [
            Pauli.from_label(pauli_label)
            for pauli_label in itertools.product('IXYZ', repeat=num_qubits)
        ]
        weights = aqua_globals.random.random(len(paulis))
        op = WeightedPauliOperator.from_list(paulis, weights)
        grouped_op = op_converter.to_tpb_grouped_weighted_pauli_operator(
            op, TPBGroupedWeightedPauliOperator.sorted_grouping)

        # check all paulis are still existed.
        for g_p in grouped_op.paulis:
            passed = False
            for pauli in op.paulis:
                if pauli[1] == g_p[1]:
                    passed = pauli[0] == g_p[0]
                    break
            self.assertTrue(
                passed, "non-existed paulis in grouped_paulis: {}".format(
                    g_p[1].to_label()))

        # check the number of basis of grouped
        # one should be less than and equal to the original one.
        self.assertGreaterEqual(len(op.basis), len(grouped_op.basis))
コード例 #11
0
    def test_simplify(self):
        """ simplify test """
        pauli_a = 'IXYZ'
        pauli_b = 'IXYZ'
        coeff_a = 0.5
        coeff_b = -0.5
        pauli_term_a = [coeff_a, Pauli.from_label(pauli_a)]
        pauli_term_b = [coeff_b, Pauli.from_label(pauli_b)]
        op_a = WeightedPauliOperator(paulis=[pauli_term_a])
        op_b = WeightedPauliOperator(paulis=[pauli_term_b])
        new_op = op_a + op_b
        new_op.simplify()

        self.assertEqual(0, len(new_op.paulis),
                         "{}".format(new_op.print_details()))
        self.assertTrue(new_op.is_empty())

        paulis = [
            Pauli.from_label(x)
            for x in ['IXYZ', 'XXZY', 'IIZZ', 'XXYY', 'ZZXX', 'YYYY']
        ]
        coeffs = [0.2, 0.6, 0.8, -0.2, -0.6, -0.8]
        op1 = WeightedPauliOperator.from_list(paulis, coeffs)

        for i, pauli in enumerate(paulis):
            tmp_op = WeightedPauliOperator(paulis=[[-coeffs[i], pauli]])
            op1 += tmp_op
            op1.simplify()
            self.assertEqual(len(paulis) - (i + 1), len(op1.paulis))
コード例 #12
0
    def test_chop_complex(self):
        """ chop complex test """
        paulis = [
            Pauli.from_label(x)
            for x in ['IXYZ', 'XXZY', 'IIZZ', 'XXYY', 'ZZXX', 'YYYY']
        ]
        coeffs = [
            0.2 + -0.5j, 0.6 - 0.3j, 0.8 - 0.6j, -0.5 + -0.2j, -0.3 + 0.6j,
            -0.6 + 0.8j
        ]
        op = WeightedPauliOperator.from_list(paulis, coeffs)
        ori_op = op.copy()
        for threshold, num_paulis in zip([0.4, 0.7, 0.9], [6, 2, 0]):
            op = ori_op.copy()
            op1 = op.chop(threshold=threshold, copy=True)
            self.assertEqual(len(op.paulis), 6,
                             "\n{}".format(op.print_details()))
            self.assertEqual(len(op1.paulis), num_paulis,
                             "\n{}".format(op1.print_details()))

            op1 = op.chop(threshold=threshold, copy=False)
            self.assertEqual(len(op.paulis), num_paulis,
                             "\n{}".format(op.print_details()))
            self.assertEqual(len(op1.paulis), num_paulis,
                             "\n{}".format(op1.print_details()))
コード例 #13
0
ファイル: CVQE.py プロジェクト: WBanner/Test-VQE-Repository
	def __init__(self, 
		operator, 
		optimizer, 
		var_form = None, 
		max_evals_grouped = 1, 
		aux_operators = None, 
		callback = None, 
		auto_conversion = True, 
		initial_point = None, 
		ham_list = None, 
		operator_list = None, 
		nonzero_terms = None, 
		starting_point = False,
		expecs = None,
		expec_mode = False,
		dir_to_bracket = False,
		ham_term_list = None,
		ham_energy_list = None,
		base_3_list = None):


		super().__init__(
			operator = operator,
			var_form = var_form,
			optimizer = optimizer,
			initial_point = initial_point,
			max_evals_grouped = max_evals_grouped,
			aux_operators = aux_operators,
			callback = callback,
			auto_conversion = auto_conversion
			)
		self.num_qubits = operator.num_qubits
		if expecs == None and expec_mode == True:
			expecs = pd.read_csv('{}_qubit_pauli_values.csv'.format(self.num_qubits)) #this file is required unless you pass in the expecation values (in order) manually
			expecs = expecs.to_dict()
		if expec_mode == True:
			self.expecs = expecs
		else:
			self.expecs = []
		if operator_list is not None:
			self.op_list = operator_list
		else:
			self.op_list = var_form.operator_pool.pool
		if initial_point is not None:
			self.param_list = initial_point
		else:
			self.param_list = [0]*len(self.op_list)
		self.starting_point = starting_point
		if starting_point:
			self.ham_list = ham_list
			self.nonzero_terms = nonzero_terms
		self.zero_term = 0*WeightedPauliOperator.from_list(paulis = [Pauli.from_label('I'*self.num_qubits)])
		self.empt_term = self.zero_term - self.zero_term
		self.dir_to_bracket = dir_to_bracket
		self.ham_term_list = ham_term_list
		self.ham_energy_list = ham_energy_list
		self.base_3_list = base_3_list
コード例 #14
0
    def anti_commuting_part(
            self, operator: WeightedPauliOperator) -> WeightedPauliOperator:
        result = WeightedPauliOperator([])

        for c, p in self._hamiltonian.paulis:
            part = WeightedPauliOperator.from_list(paulis=[p], weights=[c])
            if part.anticommute_with(operator):
                result += part
        return result
コード例 #15
0
 def drop_z_2_symmetry_ops(self, inplace: bool = True):
     f_op = WeightedPauliOperator.from_list(
         paulis=[Pauli.from_label('X' * self.num_qubits)], weights=[1.0])
     new_ops = list(filter(lambda op: f_op.commute_with(op), self.pool))
     if inplace:
         self._pool = new_ops
     else:
         res = ADAPTQAOAPool.from_operator_list(new_ops)
         return res
コード例 #16
0
def Generate_roto_op(op, *args, **kwargs):
    parameter = kwargs['parameter']
    ham = kwargs['ham']
    energy_step_tol = kwargs['energy_step_tol']
    Iden = WeightedPauliOperator.from_list(
        paulis=[Pauli.from_label('I' * ham.num_qubits)], weights=[1.0])
    psi = np.cos(parameter) * Iden + 1j * np.sin(parameter) * op
    psi_star = np.cos(parameter) * Iden - 1j * np.sin(parameter) * op
    return ((psi) * ham * (psi_star)).chop(threshold=energy_step_tol,
                                           copy=True)
コード例 #17
0
    def test_equal_operator(self):
        """ equal operator test """
        paulis = [Pauli.from_label(x) for x in ['IXYZ', 'XXZY', 'IIZZ', 'XXYY', 'ZZXX', 'YYYY']]
        coeffs = [0.2, 0.6, 0.8, -0.2, -0.6, -0.8]
        op1 = WeightedPauliOperator.from_list(paulis, coeffs)

        coeffs = [0.2, 0.6, 0.8, -0.2, -0.6, -0.8]
        op2 = WeightedPauliOperator.from_list(paulis, coeffs)

        coeffs = [-0.2, -0.6, -0.8, 0.2, 0.6, 0.8]
        op3 = WeightedPauliOperator.from_list(paulis, coeffs)

        coeffs = [-0.2, 0.6, 0.8, -0.2, -0.6, -0.8]
        op4 = WeightedPauliOperator.from_list(paulis, coeffs)

        self.assertEqual(op1, op2)
        self.assertNotEqual(op1, op3)
        self.assertNotEqual(op1, op4)
        self.assertNotEqual(op3, op4)
コード例 #18
0
def split_into_paulis(ham):
    """
		Used to split the given hamiltonian into lists of constituent parts:
		weight_list: list of complex floats that are the weights of terms in the hamiltonian
		pauli_list: a list of the Weighted_pauli_operator representations of the pauli strings in the hamiltonian
					(does not include weights)
		name_list: a list of strings that correspond to the names of the operators in the hamiltonian
	"""
    num_qubits = ham.num_qubits
    ham_details = ham.print_details()
    ham_list = ham_details.split('\n')
    pauli_list = [0] * (len(ham_list) - 1
                        )  #exclude last entry of ham list bc is just blank
    name_list = [0] * (len(ham_list) - 1)
    weight_list = [0] * (len(ham_list) - 1)
    if len(ham_list) > 2:
        for counter in range(0, len(ham_list), 1):
            if ham_list[counter][num_qubits + 2:] == '':
                break
            if ham_list[counter][num_qubits + 1:] == '0':
                name_list[counter] = 'I' * num_qubits
                weight_list[counter] = complex(0)
                pauli_list[counter] = 0 * WeightedPauliOperator.from_list(
                    paulis=[Pauli.from_label('I' * num_qubits)])
            else:
                pauli = Pauli.from_label(ham_list[counter][:num_qubits])
                name_list[counter] = ham_list[counter][:num_qubits]
                weight_list[counter] = complex(ham.paulis[counter][0])
                pauli_list[counter] = WeightedPauliOperator.from_list([pauli])
    else:
        if ham_list[0][num_qubits + 1:-1] == '0':
            name_list[0] = 'I' * num_qubits
            weight_list[0] = complex(0)
            pauli_list[0] = 0 * WeightedPauliOperator.from_list(
                paulis=[Pauli.from_label('I' * num_qubits)])
        else:
            pauli = Pauli.from_label(ham_list[0][:num_qubits])
            name_list[0] = ham_list[0][:num_qubits]
            weight_list[0] = complex(ham.paulis[0][0])
            pauli_list[0] = WeightedPauliOperator.from_list([pauli])
    return weight_list, pauli_list, name_list
コード例 #19
0
    def test_evolve(self, expansion_mode, evo_time, num_time_slices):
        expansion_orders = [1, 2, 3, 4] if expansion_mode == 'suzuki' else [1]
        num_qubits = 2
        paulis = [
            Pauli.from_label(pauli_label)
            for pauli_label in itertools.product('IXYZ', repeat=num_qubits)
        ]
        weights = np.random.random(len(paulis))
        pauli_op = WeightedPauliOperator.from_list(paulis, weights)
        matrix_op = op_converter.to_matrix_operator(pauli_op)
        state_in = Custom(num_qubits, state='random')

        # get the exact state_out from raw matrix multiplication
        state_out_exact = matrix_op.evolve(
            state_in=state_in.construct_circuit('vector'),
            evo_time=evo_time,
            num_time_slices=0)
        # self.log.debug('exact:\n{}'.format(state_out_exact))
        self.log.debug('Under {} expansion mode:'.format(expansion_mode))
        for expansion_order in expansion_orders:
            # assure every time the operator from the original one
            if expansion_mode == 'suzuki':
                self.log.debug(
                    'With expansion order {}:'.format(expansion_order))
            state_out_matrix = matrix_op.evolve(
                state_in=state_in.construct_circuit('vector'),
                evo_time=evo_time,
                num_time_slices=num_time_slices,
                expansion_mode=expansion_mode,
                expansion_order=expansion_order)
            quantum_registers = QuantumRegister(pauli_op.num_qubits, name='q')
            qc = QuantumCircuit(quantum_registers)
            qc += state_in.construct_circuit('circuit', quantum_registers)
            qc += pauli_op.copy().evolve(
                evo_time=evo_time,
                num_time_slices=num_time_slices,
                quantum_registers=quantum_registers,
                expansion_mode=expansion_mode,
                expansion_order=expansion_order,
            )
            state_out_circuit = self.quantum_instance_statevector.execute(
                qc).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)
コード例 #20
0
    def setUp(self):
        super().setUp()
        seed = 0
        aqua_globals.random_seed = seed

        self.num_qubits = 2
        m_size = np.power(2, self.num_qubits)
        matrix = aqua_globals.random.rand(m_size, m_size)
        self.mat_op = MatrixOperator(matrix=matrix)
        paulis = [Pauli.from_label(pauli_label)
                  for pauli_label in itertools.product('IXYZ', repeat=self.num_qubits)]
        weights = aqua_globals.random.random_sample(len(paulis))
        self.pauli_op = WeightedPauliOperator.from_list(paulis, weights)
コード例 #21
0
    def test_from_to_file(self):
        """ from to file test """
        paulis = [Pauli.from_label(x) for x in ['IXYZ', 'XXZY', 'IIZZ', 'XXYY', 'ZZXX', 'YYYY']]
        weights = [0.2 + -1j * 0.8, 0.6 + -1j * 0.6, 0.8 + -1j * 0.2,
                   -0.2 + -1j * 0.8, -0.6 - -1j * 0.6, -0.8 - -1j * 0.2]
        op = WeightedPauliOperator.from_list(paulis, weights)
        file_path = self._get_resource_path('temp_op.json')
        op.to_file(file_path)
        self.assertTrue(os.path.exists(file_path))

        load_op = WeightedPauliOperator.from_file(file_path)
        self.assertEqual(op, load_op)
        os.remove(file_path)
コード例 #22
0
def test_instruction() -> None:
    # TKET-446
    qreg = QuantumRegister(3)
    paulis = list(map(Pauli.from_label, ["XXI", "YYI", "ZZZ"]))
    weights = [0.3, 0.5 + 1j * 0.2, -0.4]
    op = WeightedPauliOperator.from_list(paulis, weights)
    evolution_circ = op.evolve(None,
                               1.2,
                               num_time_slices=1,
                               quantum_registers=qreg)
    tk_circ = qiskit_to_tk(evolution_circ)
    cmds = tk_circ.get_commands()
    assert len(cmds) == 1
    assert cmds[0].op.type == OpType.CircBox
コード例 #23
0
def retrieve_op_list(number, rev = False, num_qubits = 4):
    adapt_op_df = pd.read_csv('load_adapt_roto_2_op_df.csv')
    adapt_op_dict = adapt_op_df.to_dict()
    op_label_list = list(adapt_op_dict['Ham_{}'.format(number)])
    op_list = []
    for label in op_label_list:
        op_name = adapt_op_dict['Ham_{}'.format(number)][label]
        print(op_name)
        op = Pauli.from_label(op_name[:num_qubits])
        op = WeightedPauliOperator.from_list([op])
        op_list.append(op)
    if rev:
        return reverse(op_list)
    return op_list
コード例 #24
0
def retrieve_ham(number, num_qubits = 4):
    adapt_data_df = pd.read_csv('load_adapt_roto_2_data_df.csv')
    adapt_data_dict = adapt_data_df.to_dict()
    Ham_list = adapt_data_dict['hamiltonian']

    Ham = Ham_list[number]
    single_ham_list = Ham.split('\n')
    pauli_list = [0]*(len(single_ham_list)-1)
    weight_list = [0]*(len(single_ham_list)-1)
    for counter2 in range(0, len(single_ham_list)-1,1):
        pauli_list[counter2] = Pauli.from_label(single_ham_list[counter2][:num_qubits])
        weight_list[counter2] = complex(single_ham_list[counter2][num_qubits:])
    qubit_op = WeightedPauliOperator.from_list(pauli_list,weight_list)

    return qubit_op
コード例 #25
0
    def test_chop_real(self):
        """ chop real test """
        paulis = [Pauli(x) for x in ['IXYZ', 'XXZY', 'IIZZ', 'XXYY', 'ZZXX', 'YYYY']]
        coeffs = [0.2, 0.6, 0.8, -0.2, -0.6, -0.8]
        op = WeightedPauliOperator.from_list(paulis, coeffs)
        ori_op = op.copy()

        for threshold, num_paulis in zip([0.4, 0.7, 0.9], [4, 2, 0]):
            op = ori_op.copy()
            op1 = op.chop(threshold=threshold, copy=True)
            self.assertEqual(len(op.paulis), 6, "\n{}".format(op.print_details()))
            self.assertEqual(len(op1.paulis), num_paulis, "\n{}".format(op1.print_details()))

            op1 = op.chop(threshold=threshold, copy=False)
            self.assertEqual(len(op.paulis), num_paulis, "\n{}".format(op.print_details()))
            self.assertEqual(len(op1.paulis), num_paulis, "\n{}".format(op1.print_details()))
コード例 #26
0
    def first_vqe_kwargs(self) -> Dict:
        # This works for now, but always produces one extra parameter. -George, so we'll need to change this for rotoadapt too.
        id_op = WeightedPauliOperator.from_list(paulis=[Pauli.from_label('I' * self.operator_pool.num_qubits)],
                                                weights=[1.0])
        var_form = self.variational_form([id_op])

        self._operator_selector._quantum_instance = self.quantum_instance

        return {
            'operator': self.hamiltonian,
            'var_form': var_form,
            'optimizer': DummyOptimizer(),
            'initial_point': np.array([np.pi]),
            'max_evals_grouped': self.max_evals_grouped,
            'aux_operators': self.aux_operators,
            'callback': self.callback,
            'auto_conversion': self.auto_conversion
        }
コード例 #27
0
    def test_unsorted_grouping(self):
        """Test with normal grouping approach."""

        num_qubits = 4
        paulis = [Pauli.from_label(pauli_label)
                  for pauli_label in itertools.product('IXYZ', repeat=num_qubits)]
        weights = aqua_globals.random.random_sample(len(paulis))
        op = WeightedPauliOperator.from_list(paulis, weights)
        grouped_op = op_converter.to_tpb_grouped_weighted_pauli_operator(
            op, TPBGroupedWeightedPauliOperator.unsorted_grouping)

        for g_p in grouped_op.paulis:
            passed = False
            for pauli in op.paulis:
                if pauli[1] == g_p[1]:
                    passed = pauli[0] == g_p[0]
                    break
            self.assertTrue(passed,
                            "non-existed paulis in grouped_paulis: {}".format(g_p[1].to_label()))

        self.assertGreaterEqual(len(op.basis), len(grouped_op.basis))
コード例 #28
0
    def test_evaluate_single_pauli_statevector(self):
        """ evaluate single pauli statevector test """
        # X
        op = WeightedPauliOperator.from_list([Pauli.from_label('X')])
        qr = QuantumRegister(1, name='q')
        wave_function = QuantumCircuit(qr)
        # + 1 eigenstate
        wave_function.h(qr[0])
        circuits = op.construct_evaluation_circuit(wave_function=wave_function,
                                                   statevector_mode=True)
        result = self.quantum_instance_statevector.execute(circuits)
        actual_value = op.evaluate_with_result(result=result,
                                               statevector_mode=True)
        self.assertAlmostEqual(1.0, actual_value[0].real, places=5)
        # - 1 eigenstate
        wave_function = QuantumCircuit(qr)
        wave_function.x(qr[0])
        wave_function.h(qr[0])
        circuits = op.construct_evaluation_circuit(wave_function=wave_function,
                                                   statevector_mode=True)
        result = self.quantum_instance_statevector.execute(circuits)
        actual_value = op.evaluate_with_result(result=result,
                                               statevector_mode=True)
        self.assertAlmostEqual(-1.0, actual_value[0].real, places=5)

        # Y
        op = WeightedPauliOperator.from_list([Pauli.from_label('Y')])
        qr = QuantumRegister(1, name='q')
        wave_function = QuantumCircuit(qr)
        # + 1 eigenstate
        wave_function.h(qr[0])
        wave_function.s(qr[0])
        circuits = op.construct_evaluation_circuit(wave_function=wave_function,
                                                   statevector_mode=True)
        result = self.quantum_instance_statevector.execute(circuits)
        actual_value = op.evaluate_with_result(result=result,
                                               statevector_mode=True)
        self.assertAlmostEqual(1.0, actual_value[0].real, places=5)
        # - 1 eigenstate
        wave_function = QuantumCircuit(qr)
        wave_function.x(qr[0])
        wave_function.h(qr[0])
        wave_function.s(qr[0])
        circuits = op.construct_evaluation_circuit(wave_function=wave_function,
                                                   statevector_mode=True)
        result = self.quantum_instance_statevector.execute(circuits)
        actual_value = op.evaluate_with_result(result=result,
                                               statevector_mode=True)
        self.assertAlmostEqual(-1.0, actual_value[0].real, places=5)

        # Z
        op = WeightedPauliOperator.from_list([Pauli.from_label('Z')])
        qr = QuantumRegister(1, name='q')
        wave_function = QuantumCircuit(qr)
        # + 1 eigenstate
        circuits = op.construct_evaluation_circuit(wave_function=wave_function,
                                                   statevector_mode=True)
        result = self.quantum_instance_statevector.execute(circuits)
        actual_value = op.evaluate_with_result(result=result,
                                               statevector_mode=True)
        self.assertAlmostEqual(1.0, actual_value[0].real, places=5)
        # - 1 eigenstate
        wave_function = QuantumCircuit(qr)
        wave_function.x(qr[0])
        circuits = op.construct_evaluation_circuit(wave_function=wave_function,
                                                   statevector_mode=True)
        result = self.quantum_instance_statevector.execute(circuits)
        actual_value = op.evaluate_with_result(result=result,
                                               statevector_mode=True)
        self.assertAlmostEqual(-1.0, actual_value[0].real, places=5)
コード例 #29
0
adapt_data_df = pd.read_csv('load_adapt_data_df.csv')
adapt_data_dict = adapt_data_df.to_dict()
Ham_list = adapt_data_dict['hamiltonian']

counter = 0
counter2 = 0
num_hams = 10
pauli_meta_list = [0]*num_hams
weight_meta_list = [0]*num_hams
Exact_energy_dict = {'Ham_1':[],'Ham_2':[],'Ham_3':[],'Ham_4':[],'Ham_5':[],'Ham_6':[],'Ham_7':[],'Ham_8':[],'Ham_9':[]}

for counter in range(0,num_hams,1):
	Ham = Ham_list[counter]
	single_ham_list = Ham.split('\n')
	pauli_list = [0]*(len(single_ham_list)-1)
	weight_list = [0]*(len(single_ham_list)-1)
	for counter2 in range(0, len(single_ham_list)-1,1):
		pauli_list[counter2] = Pauli.from_label(single_ham_list[counter2][:4])
		weight_list[counter2] = complex(single_ham_list[counter2][6:-1])
	pauli_meta_list[counter] = pauli_list
	weight_meta_list[counter] = weight_list
	qubit_op = WeightedPauliOperator.from_list(pauli_list,weight_list)
	Exact_result = ExactEigensolver(qubit_op, k = 16).run()
	Exact_energy_dict['Ham_{}'.format(counter)] = Exact_result['energies']
	print('E', Exact_result)

Exact_energy_df = pd.DataFrame(Exact_energy_dict)
Exact_energy_df_file = open("exact_energy_df.csv", "w+")
Exact_energy_df.to_csv('exact_energy_df.csv')
Exact_energy_df_file.close()
コード例 #30
0
exact_dict = {'2': [], '3': [], '4': [], '5': [], '6': [], '7': [], '8': [], '9': [], '10': []}
num_qubits = 4
#test = random_diagonal_hermitian(2)
#print(test.print_details())
#mat = to_matrix_operator(test)
#print(mat.print_details())
for i in range(0,1):
    k = 0
    runtime_sum = 0
    exact_time_sum = 0
    vqeruntime_sum = 0
    print('num_qubits', num_qubits)
    while k < runs:
        initial_state = Zero(num_qubits)
        op_list = []
        wop = 0*WeightedPauliOperator.from_list(paulis=[Pauli.from_label('I'*num_qubits)], weights=[1.0])
        #mat = np.random.uniform(0, 1, size=(2**num_qubits, 2**num_qubits)) + 1j * np.random.uniform(0, 1, size=(2**num_qubits, 2**num_qubits))
        #mat = np.conjugate(np.transpose(mat)) + mat
        
        #ham = to_weighted_pauli_operator(MatrixOperator(mat)) #creates random hamiltonian from random matrix "mat"
        ham = get_h_4_hamiltonian(0.25, 2, "jw")
        #ham = retrieve_ham(0, num_qubits = num_qubits)
        print('old_ham', ham.print_details())
        #ham = get_h_4_hamiltonian(0.5,2,'jw')
        #op_list = retrieve_op_list(0, rev = True, num_qubits = num_qubits)
        #for op in op_list:
        #    print(op.print_details())
        op_list = [WeightedPauliOperator.from_list([Pauli.from_label('IIXX')]), WeightedPauliOperator.from_list([Pauli.from_label('XXXY')])]
        #op_list = [WeightedPauliOperator.from_list([Pauli.from_label('YYZZ')],[1.0]),
        # WeightedPauliOperator.from_list([Pauli.from_label('XXXY')], [1.0]),
        # WeightedPauliOperator.from_list([Pauli.from_label('IIYZ')], [1.0])]