repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.6/my_mpo.py
import numpy as np import tensornetwork as tn from tensornetwork.backends.abstract_backend import AbstractBackend tn.set_default_backend("pytorch") #tn.set_default_backend("numpy") from typing import List, Union, Text, Optional, Any, Type Tensor = Any import tequila as tq import torch EPS = 1e-12 class SubOperator: """ This is just a helper class to store coefficient, operators and positions in an intermediate format """ def __init__(self, coefficient: float, operators: List, positions: List ): self._coefficient = coefficient self._operators = operators self._positions = positions @property def coefficient(self): return self._coefficient @property def operators(self): return self._operators @property def positions(self): return self._positions class MPOContainer: """ Class that handles the MPO. Is able to set values at certain positions, update containers (wannabe-equivalent to dynamic arrays) and compress the MPO """ def __init__(self, n_qubits: int, ): self.n_qubits = n_qubits self.container = [ np.zeros((1,1,2,2), dtype=np.complex) for q in range(self.n_qubits) ] def get_dim(self): """ Returns max dimension of container """ d = 1 for q in range(len(self.container)): d = max(d, self.container[q].shape[0]) return d def set_tensor(self, qubit: int, set_at: list, add_operator: Union[np.ndarray, float]): """ set_at: where to put data """ # Set a matrix if len(set_at) == 2: self.container[qubit][set_at[0],set_at[1],:,:] = add_operator[:,:] # Set specific values elif len(set_at) == 4: self.container[qubit][set_at[0],set_at[1],set_at[2],set_at[3]] =\ add_operator else: raise Exception("set_at needs to be either of length 2 or 4") def update_container(self, qubit: int, update_dir: list, add_operator: np.ndarray): """ This should mimick a dynamic array update_dir: e.g. [1,1,0,0] -> extend dimension along where there's a 1 the last two dimensions are always 2x2 only """ old_shape = self.container[qubit].shape # print(old_shape) if not len(update_dir) == 4: if len(update_dir) == 2: update_dir += [0, 0] else: raise Exception("update_dir needs to be either of length 2 or 4") if update_dir[2] or update_dir[3]: raise Exception("Last two dims must be zero.") new_shape = tuple(update_dir[i]+old_shape[i] for i in range(len(update_dir))) new_tensor = np.zeros(new_shape, dtype=np.complex) # Copy old values new_tensor[:old_shape[0],:old_shape[1],:,:] = self.container[qubit][:,:,:,:] # Add new values new_tensor[new_shape[0]-1,new_shape[1]-1,:,:] = add_operator[:,:] # Overwrite container self.container[qubit] = new_tensor def compress_mpo(self): """ Compression of MPO via SVD """ n_qubits = len(self.container) for q in range(n_qubits): my_shape = self.container[q].shape self.container[q] =\ self.container[q].reshape((my_shape[0], my_shape[1], -1)) # Go forwards for q in range(n_qubits-1): # Apply permutation [0 1 2] -> [0 2 1] my_tensor = np.swapaxes(self.container[q], 1, 2) my_tensor = my_tensor.reshape((-1, my_tensor.shape[2])) # full_matrices flag corresponds to 'econ' -> no zero-singular values u, s, vh = np.linalg.svd(my_tensor, full_matrices=False) # Count the non-zero singular values num_nonzeros = len(np.argwhere(s>EPS)) # Construct matrix from square root of singular values s = np.diag(np.sqrt(s[:num_nonzeros])) u = u[:,:num_nonzeros] vh = vh[:num_nonzeros,:] # Distribute weights to left- and right singular vectors (@ = np.matmul) u = u @ s vh = s @ vh # Apply permutation [0 1 2] -> [0 2 1] u = u.reshape((self.container[q].shape[0],\ self.container[q].shape[2], -1)) self.container[q] = np.swapaxes(u, 1, 2) self.container[q+1] = tn.ncon([vh, self.container[q+1]], [(-1, 1),(1, -2, -3)]) # Go backwards for q in range(n_qubits-1, 0, -1): my_tensor = self.container[q] my_tensor = my_tensor.reshape((self.container[q].shape[0], -1)) # full_matrices flag corresponds to 'econ' -> no zero-singular values u, s, vh = np.linalg.svd(my_tensor, full_matrices=False) # Count the non-zero singular values num_nonzeros = len(np.argwhere(s>EPS)) # Construct matrix from square root of singular values s = np.diag(np.sqrt(s[:num_nonzeros])) u = u[:,:num_nonzeros] vh = vh[:num_nonzeros,:] # Distribute weights to left- and right singular vectors u = u @ s vh = s @ vh self.container[q] = np.reshape(vh, (num_nonzeros, self.container[q].shape[1], self.container[q].shape[2])) self.container[q-1] = tn.ncon([self.container[q-1], u], [(-1, 1, -3),(1, -2)]) for q in range(n_qubits): my_shape = self.container[q].shape self.container[q] = self.container[q].reshape((my_shape[0],\ my_shape[1],2,2)) # TODO maybe make subclass of tn.FiniteMPO if it makes sense #class my_MPO(tn.FiniteMPO): class MyMPO: """ Class building up on tensornetwork FiniteMPO to handle MPO-Hamiltonians """ def __init__(self, hamiltonian: Union[tq.QubitHamiltonian, Text], # tensors: List[Tensor], backend: Optional[Union[AbstractBackend, Text]] = None, n_qubits: Optional[int] = None, name: Optional[Text] = None, maxdim: Optional[int] = 10000) -> None: # TODO: modifiy docstring """ Initialize a finite MPO object Args: tensors: The mpo tensors. backend: An optional backend. Defaults to the defaulf backend of TensorNetwork. name: An optional name for the MPO. """ self.hamiltonian = hamiltonian self.maxdim = maxdim if n_qubits: self._n_qubits = n_qubits else: self._n_qubits = self.get_n_qubits() @property def n_qubits(self): return self._n_qubits def make_mpo_from_hamiltonian(self): intermediate = self.openfermion_to_intermediate() # for i in range(len(intermediate)): # print(intermediate[i].coefficient) # print(intermediate[i].operators) # print(intermediate[i].positions) self.mpo = self.intermediate_to_mpo(intermediate) def openfermion_to_intermediate(self): # Here, have either a QubitHamiltonian or a file with a of-operator # Start with Qubithamiltonian def get_pauli_matrix(string): pauli_matrices = { 'I': np.array([[1, 0], [0, 1]], dtype=np.complex), 'Z': np.array([[1, 0], [0, -1]], dtype=np.complex), 'X': np.array([[0, 1], [1, 0]], dtype=np.complex), 'Y': np.array([[0, -1j], [1j, 0]], dtype=np.complex) } return pauli_matrices[string.upper()] intermediate = [] first = True # Store all paulistrings in intermediate format for paulistring in self.hamiltonian.paulistrings: coefficient = paulistring.coeff # print(coefficient) operators = [] positions = [] # Only first one should be identity -> distribute over all if first and not paulistring.items(): positions += [] operators += [] first = False elif not first and not paulistring.items(): raise Exception("Only first Pauli should be identity.") # Get operators and where they act for k,v in paulistring.items(): positions += [k] operators += [get_pauli_matrix(v)] tmp_op = SubOperator(coefficient=coefficient, operators=operators, positions=positions) intermediate += [tmp_op] # print("len intermediate = num Pauli strings", len(intermediate)) return intermediate def build_single_mpo(self, intermediate, j): # Set MPO Container n_qubits = self._n_qubits mpo = MPOContainer(n_qubits=n_qubits) # *********************************************************************** # Set first entries (of which we know that they are 2x2-matrices) # Typically, this is an identity my_coefficient = intermediate[j].coefficient my_positions = intermediate[j].positions my_operators = intermediate[j].operators for q in range(n_qubits): if not q in my_positions: mpo.set_tensor(qubit=q, set_at=[0,0], add_operator=np.complex(my_coefficient)**(1/n_qubits)* np.eye(2)) elif q in my_positions: my_pos_index = my_positions.index(q) mpo.set_tensor(qubit=q, set_at=[0,0], add_operator=np.complex(my_coefficient)**(1/n_qubits)* my_operators[my_pos_index]) # *********************************************************************** # All other entries # while (j smaller than number of intermediates left) and mpo.dim() <= self.maxdim # Re-write this based on positions keyword! j += 1 while j < len(intermediate) and mpo.get_dim() < self.maxdim: # """ my_coefficient = intermediate[j].coefficient my_positions = intermediate[j].positions my_operators = intermediate[j].operators for q in range(n_qubits): # It is guaranteed that every index appears only once in positions if q == 0: update_dir = [0,1] elif q == n_qubits-1: update_dir = [1,0] else: update_dir = [1,1] # If there's an operator on my position, add that if q in my_positions: my_pos_index = my_positions.index(q) mpo.update_container(qubit=q, update_dir=update_dir, add_operator= np.complex(my_coefficient)**(1/n_qubits)* my_operators[my_pos_index]) # Else add an identity else: mpo.update_container(qubit=q, update_dir=update_dir, add_operator= np.complex(my_coefficient)**(1/n_qubits)* np.eye(2)) if not j % 100: mpo.compress_mpo() #print("\t\tAt iteration ", j, " MPO has dimension ", mpo.get_dim()) j += 1 mpo.compress_mpo() #print("\tAt final iteration ", j-1, " MPO has dimension ", mpo.get_dim()) return mpo, j def intermediate_to_mpo(self, intermediate): n_qubits = self._n_qubits # TODO Change to multiple MPOs mpo_list = [] j_global = 0 num_mpos = 0 # Start with 0, then final one is correct while j_global < len(intermediate): current_mpo, j_global = self.build_single_mpo(intermediate, j_global) mpo_list += [current_mpo] num_mpos += 1 return mpo_list def construct_matrix(self): # TODO extend to lists of MPOs ''' Recover matrix, e.g. to compare with Hamiltonian that we get from tq ''' mpo = self.mpo # Contract over all bond indices # mpo.container has indices [bond, bond, physical, physical] n_qubits = self._n_qubits d = int(2**(n_qubits/2)) first = True H = None #H = np.zeros((d,d,d,d), dtype='complex') # Define network nodes # | | | | # -O--O--...--O--O- # | | | | for m in mpo: assert(n_qubits == len(m.container)) nodes = [tn.Node(m.container[q], name=str(q)) for q in range(n_qubits)] # Connect network (along double -- above) for q in range(n_qubits-1): nodes[q][1] ^ nodes[q+1][0] # Collect dangling edges (free indices) edges = [] # Left dangling edge edges += [nodes[0].get_edge(0)] # Right dangling edge edges += [nodes[-1].get_edge(1)] # Upper dangling edges for q in range(n_qubits): edges += [nodes[q].get_edge(2)] # Lower dangling edges for q in range(n_qubits): edges += [nodes[q].get_edge(3)] # Contract between all nodes along non-dangling edges res = tn.contractors.auto(nodes, output_edge_order=edges) # Reshape to get tensor of order 4 (get rid of left- and right open indices # and combine top&bottom into one) if isinstance(res.tensor, torch.Tensor): H_m = res.tensor.numpy() if not first: H += H_m else: H = H_m first = False return H.reshape((d,d,d,d))
14,354
36.480418
99
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.6/do_annealing.py
import tequila as tq import numpy as np import pickle from pathos.multiprocessing import ProcessingPool as Pool from parallel_annealing import * #from dummy_par import * from mutation_options import * from single_thread_annealing import * def find_best_instructions(instructions_dict): """ This function finds the instruction with the best fitness args: instructions_dict: A dictionary with the "Instructions" objects the corresponding fitness values as values """ best_instructions = None best_fitness = 10000000 for key in instructions_dict: if instructions_dict[key][1] <= best_fitness: best_instructions = instructions_dict[key][0] best_fitness = instructions_dict[key][1] return best_instructions, best_fitness def simulated_annealing(num_population, num_offsprings, actions_ratio, hamiltonian, max_epochs=100, min_epochs=1, tol=1e-6, type_energy_eval="wfn", cluster_circuit=None, patience = 20, num_processors=4, T_0=1.0, alpha=0.9, max_non_cliffords=0, verbose=False, beta=0.5, starting_energy=None): """ this function tries to find the clifford circuit that best lowers the energy of the hamiltonian using simulated annealing. params: - num_population = number of members in a generation - num_offsprings = number of mutations carried on every member - num_processors = number of processors to use for parallelization - T_0 = initial temperature - alpha = temperature decay - beta = parameter to adjust temperature on resetting after running out of patience - max_epochs = max iterations for optimizing - min_epochs = min iterations for optimizing - tol = minimum change in energy required, otherwise terminate optimization - verbose = display energies/decisions at iterations of not - hamiltonian = original hamiltonian - actions_ratio = The ratio of the different actions for mutations - type_energy_eval = keyword specifying the type of optimization method to use for energy minimization - cluster_circuit = the reference circuit to which clifford gates are added - patience = the number of epochs before resetting the optimization """ if verbose: print("Starting to Optimize Cluster circuit", flush=True) num_qubits = len(hamiltonian.qubits) if verbose: print("Initializing Generation", flush=True) # restart = False if previous_instructions is None\ # else True restart = False instructions_dict = {} instructions_list = [] current_fitness_list = [] fitness, wfn = None, None # pre-initialize with None for instruction_id in range(num_population): instructions = None if restart: try: instructions = Instructions(n_qubits=num_qubits, alpha=alpha, T_0=T_0, beta=beta, patience=patience, max_non_cliffords=max_non_cliffords, reference_energy=starting_energy) instructions.gates = pickle.load(open("instruct_gates.pickle", "rb")) instructions.positions = pickle.load(open("instruct_positions.pickle", "rb")) instructions.best_reference_wfn = pickle.load(open("best_reference_wfn.pickle", "rb")) print("Added a guess from previous runs", flush=True) fitness, wfn = evaluate_fitness(instructions=instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) except Exception as e: print(e) raise Exception("Did not find a guess from previous runs") # pass restart = False #print(instructions._str()) else: failed = True while failed: instructions = Instructions(n_qubits=num_qubits, alpha=alpha, T_0=T_0, beta=beta, patience=patience, max_non_cliffords=max_non_cliffords, reference_energy=starting_energy) instructions.prune() fitness, wfn = evaluate_fitness(instructions=instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) # if fitness <= starting_energy: failed = False instructions.set_reference_wfn(wfn) current_fitness_list.append(fitness) instructions_list.append(instructions) instructions_dict[instruction_id] = (instructions, fitness) if verbose: print("First Generation details: \n", flush=True) for key in instructions_dict: print("Initial Instructions number: ", key, flush=True) instructions_dict[key][0]._str() print("Initial fitness values: ", instructions_dict[key][1], flush=True) best_instructions, best_energy = find_best_instructions(instructions_dict) if verbose: print("Best member of the Generation: \n", flush=True) print("Instructions: ", flush=True) best_instructions._str() print("fitness value: ", best_energy, flush=True) pickle.dump(best_instructions.gates, open("instruct_gates.pickle", "wb")) pickle.dump(best_instructions.positions, open("instruct_positions.pickle", "wb")) pickle.dump(best_instructions.best_reference_wfn, open("best_reference_wfn.pickle", "wb")) epoch = 0 previous_best_energy = best_energy converged = False has_improved_before = False dts = [] #pool = multiprocessing.Pool(processes=num_processors) while (epoch < max_epochs): print("Epoch: ", epoch, flush=True) import time t0 = time.time() if num_processors == 1: st_evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, type_energy_eval, cluster_circuit) else: evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, num_processors, type_energy_eval, cluster_circuit) t1 = time.time() dts += [t1-t0] best_instructions, best_energy = find_best_instructions(instructions_dict) if verbose: print("Best member of the Generation: \n", flush=True) print("Instructions: ", flush=True) best_instructions._str() print("fitness value: ", best_energy, flush=True) # A bit confusing, but: # Want that current best energy has improved something previous, is better than # some starting energy and achieves some convergence criterion has_improved_before = True if np.abs(best_energy - previous_best_energy) < 0\ else False if np.abs(best_energy - previous_best_energy) < tol and has_improved_before: if starting_energy is not None: converged = True if best_energy < starting_energy else False else: converged = True else: converged = False if best_energy < previous_best_energy: previous_best_energy = best_energy epoch += 1 pickle.dump(best_instructions.gates, open("instruct_gates.pickle", "wb")) pickle.dump(best_instructions.positions, open("instruct_positions.pickle", "wb")) pickle.dump(best_instructions.best_reference_wfn, open("best_reference_wfn.pickle", "wb")) #pool.close() if converged: print("Converged after ", epoch, " iterations.", flush=True) print("Best energy:", best_energy, flush=True) print("\t with instructions", best_instructions.gates, best_instructions.positions, flush=True) print("\t optimal parameters", best_instructions.best_reference_wfn, flush=True) print("average time: ", np.average(dts), flush=True) print("overall time: ", np.sum(dts), flush=True) # best_instructions.replace_UCCXc_with_UCC(number=max_non_cliffords) pickle.dump(best_instructions.gates, open("instruct_gates.pickle", "wb")) pickle.dump(best_instructions.positions, open("instruct_positions.pickle", "wb")) pickle.dump(best_instructions.best_reference_wfn, open("best_reference_wfn.pickle", "wb")) def replace_cliff_with_non_cliff(num_population, num_offsprings, actions_ratio, hamiltonian, max_epochs=100, min_epochs=1, tol=1e-6, type_energy_eval="wfn", cluster_circuit=None, patience = 20, num_processors=4, T_0=1.0, alpha=0.9, max_non_cliffords=0, verbose=False, beta=0.5, starting_energy=None): """ this function tries to find the clifford circuit that best lowers the energy of the hamiltonian using simulated annealing. params: - num_population = number of members in a generation - num_offsprings = number of mutations carried on every member - num_processors = number of processors to use for parallelization - T_0 = initial temperature - alpha = temperature decay - beta = parameter to adjust temperature on resetting after running out of patience - max_epochs = max iterations for optimizing - min_epochs = min iterations for optimizing - tol = minimum change in energy required, otherwise terminate optimization - verbose = display energies/decisions at iterations of not - hamiltonian = original hamiltonian - actions_ratio = The ratio of the different actions for mutations - type_energy_eval = keyword specifying the type of optimization method to use for energy minimization - cluster_circuit = the reference circuit to which clifford gates are added - patience = the number of epochs before resetting the optimization """ if verbose: print("Starting to replace clifford gates Cluster circuit with non-clifford gates one at a time", flush=True) num_qubits = len(hamiltonian.qubits) #get the best clifford object instructions = Instructions(n_qubits=num_qubits, alpha=alpha, T_0=T_0, beta=beta, patience=patience, max_non_cliffords=max_non_cliffords, reference_energy=starting_energy) instructions.gates = pickle.load(open("instruct_gates.pickle", "rb")) instructions.positions = pickle.load(open("instruct_positions.pickle", "rb")) instructions.best_reference_wfn = pickle.load(open("best_reference_wfn.pickle", "rb")) fitness, wfn = evaluate_fitness(instructions=instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) if verbose: print("Initial energy after previous Clifford optimization is",\ fitness, flush=True) print("Starting with instructions", instructions.gates, instructions.positions, flush=True) instructions_dict = {} instructions_dict[0] = (instructions, fitness) for gate_id, (gate, position) in enumerate(zip(instructions.gates, instructions.positions)): print(gate) altered_instructions = copy.deepcopy(instructions) # skip if controlled rotation if gate[0]=='C': continue altered_instructions.replace_cg_w_ncg(gate_id) # altered_instructions.max_non_cliffords = 1 # TODO why is this set to 1?? altered_instructions.max_non_cliffords = max_non_cliffords #clifford_circuit, init_angles = build_circuit(instructions) #print(clifford_circuit, init_angles) #folded_hamiltonian = perform_folding(hamiltonian, clifford_circuit) #folded_hamiltonian2 = (convert_PQH_to_tq_QH(folded_hamiltonian))() #print(folded_hamiltonian) #clifford_circuit, init_angles = build_circuit(altered_instructions) #print(clifford_circuit, init_angles) #folded_hamiltonian = perform_folding(hamiltonian, clifford_circuit) #folded_hamiltonian1 = (convert_PQH_to_tq_QH(folded_hamiltonian))(init_angles) #print(folded_hamiltonian1 - folded_hamiltonian2) #print(folded_hamiltonian) #raise Exception("teste") counter = 0 success = False while not success: counter += 1 try: fitness, wfn = evaluate_fitness(instructions=altered_instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) success = True except Exception as e: print(e) if counter > 5: print("This replacement failed more than 5 times") success = True instructions_dict[gate_id+1] = (altered_instructions, fitness) #circuit = build_circuit(altered_instructions) #tq.draw(circuit,backend="cirq") best_instructions, best_energy = find_best_instructions(instructions_dict) print("best instrucitons after the non-clifford opimizaton") print("Best energy:", best_energy, flush=True) print("\t with instructions", best_instructions.gates, best_instructions.positions, flush=True)
13,155
46.154122
187
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.6/scipy_optimizer.py
import numpy, copy, scipy, typing, numbers from tequila import BitString, BitNumbering, BitStringLSB from tequila.utils.keymap import KeyMapRegisterToSubregister from tequila.circuit.compiler import change_basis from tequila.utils import to_float import tequila as tq from tequila.objective import Objective from tequila.optimizers.optimizer_scipy import OptimizerSciPy, SciPyResults from tequila.objective.objective import assign_variable, Variable, format_variable_dictionary, format_variable_list from tequila.circuit.noise import NoiseModel #from tequila.optimizers._containers import _EvalContainer, _GradContainer, _HessContainer, _QngContainer from vqe_utils import * class _EvalContainer: """ Overwrite the call function Container Class to access scipy and keep the optimization history. This class is used by the SciPy optimizer and should not be used elsewhere. Attributes --------- objective: the objective to evaluate. param_keys: the dictionary mapping parameter keys to positions in a numpy array. samples: the number of samples to evaluate objective with. save_history: whether or not to save, in a history, information about each time __call__ occurs. print_level dictates the verbosity of printing during call. N: the length of param_keys. history: if save_history, a list of energies received from every __call__ history_angles: if save_history, a list of angles sent to __call__. """ def __init__(self, Hamiltonian, unitary, param_keys, Ham_derivatives= None, Eval=None, passive_angles=None, samples=1024, save_history=True, print_level: int = 3): self.Hamiltonian = Hamiltonian self.unitary = unitary self.samples = samples self.param_keys = param_keys self.N = len(param_keys) self.save_history = save_history self.print_level = print_level self.passive_angles = passive_angles self.Eval = Eval self.infostring = None self.Ham_derivatives = Ham_derivatives if save_history: self.history = [] self.history_angles = [] def __call__(self, p, *args, **kwargs): """ call a wrapped objective. Parameters ---------- p: numpy array: Parameters with which to call the objective. args kwargs Returns ------- numpy.array: value of self.objective with p translated into variables, as a numpy array. """ angles = {}#dict((self.param_keys[i], p[i]) for i in range(self.N)) for i in range(self.N): if self.param_keys[i] in self.unitary.extract_variables(): angles[self.param_keys[i]] = p[i] else: angles[self.param_keys[i]] = complex(p[i]) if self.passive_angles is not None: angles = {**angles, **self.passive_angles} vars = format_variable_dictionary(angles) Hamiltonian = self.Hamiltonian(vars) #print(Hamiltonian) #print(self.unitary) #print(vars) Expval = tq.ExpectationValue(H=Hamiltonian, U=self.unitary) #print(Expval) E = tq.simulate(Expval, vars, backend='qulacs', samples=self.samples) self.infostring = "{:15} : {} expectationvalues\n".format("Objective", Expval.count_expectationvalues()) if self.print_level > 2: print("E={:+2.8f}".format(E), " angles=", angles, " samples=", self.samples) elif self.print_level > 1: print("E={:+2.8f}".format(E)) if self.save_history: self.history.append(E) self.history_angles.append(angles) return complex(E) # jax types confuses optimizers class _GradContainer(_EvalContainer): """ Overwrite the call function Container Class to access scipy and keep the optimization history. This class is used by the SciPy optimizer and should not be used elsewhere. see _EvalContainer for details. """ def __call__(self, p, *args, **kwargs): """ call the wrapped qng. Parameters ---------- p: numpy array: Parameters with which to call gradient args kwargs Returns ------- numpy.array: value of self.objective with p translated into variables, as a numpy array. """ Ham_derivatives = self.Ham_derivatives Hamiltonian = self.Hamiltonian unitary = self.unitary dE_vec = numpy.zeros(self.N) memory = dict() #variables = dict((self.param_keys[i], p[i]) for i in range(len(self.param_keys))) variables = {}#dict((self.param_keys[i], p[i]) for i in range(self.N)) for i in range(len(self.param_keys)): if self.param_keys[i] in self.unitary.extract_variables(): variables[self.param_keys[i]] = p[i] else: variables[self.param_keys[i]] = complex(p[i]) if self.passive_angles is not None: variables = {**variables, **self.passive_angles} vars = format_variable_dictionary(variables) expvals = 0 for i in range(self.N): derivative = 0.0 if self.param_keys[i] in list(unitary.extract_variables()): Ham = Hamiltonian(vars) Expval = tq.ExpectationValue(H=Ham, U=unitary) temp_derivative = tq.compile(objective = tq.grad(objective = Expval, variable = self.param_keys[i]),backend='qulacs') expvals += temp_derivative.count_expectationvalues() derivative += temp_derivative if self.param_keys[i] in list(Ham_derivatives.keys()): #print(self.param_keys[i]) Ham = Ham_derivatives[self.param_keys[i]] Ham = convert_PQH_to_tq_QH(Ham) H = Ham(vars) #print(H) #raise Exception("testing") Expval = tq.ExpectationValue(H=H, U=unitary) expvals += Expval.count_expectationvalues() derivative += tq.simulate(Expval, vars, backend='qulacs', samples=self.samples) #print(derivative) #print(type(H)) if isinstance(derivative, float) or isinstance(derivative, numpy.complex64) : dE_vec[i] = derivative else: dE_vec[i] = derivative(variables=variables, samples=self.samples) memory[self.param_keys[i]] = dE_vec[i] self.infostring = "{:15} : {} expectationvalues\n".format("gradient", expvals) self.history.append(memory) return numpy.asarray(dE_vec, dtype=numpy.complex64) class optimize_scipy(OptimizerSciPy): """ overwrite the expectation and gradient container objects """ def initialize_variables(self, all_variables, initial_values, variables): """ Convenience function to format the variables of some objective recieved in calls to optimzers. Parameters ---------- objective: Objective: the objective being optimized. initial_values: dict or string: initial values for the variables of objective, as a dictionary. if string: can be `zero` or `random` if callable: custom function that initializes when keys are passed if None: random initialization between 0 and 2pi (not recommended) variables: list: the variables being optimized over. Returns ------- tuple: active_angles, a dict of those variables being optimized. passive_angles, a dict of those variables NOT being optimized. variables: formatted list of the variables being optimized. """ # bring into right format variables = format_variable_list(variables) initial_values = format_variable_dictionary(initial_values) all_variables = all_variables if variables is None: variables = all_variables if initial_values is None: initial_values = {k: numpy.random.uniform(0, 2 * numpy.pi) for k in all_variables} elif hasattr(initial_values, "lower"): if initial_values.lower() == "zero": initial_values = {k:0.0 for k in all_variables} elif initial_values.lower() == "random": initial_values = {k: numpy.random.uniform(0, 2 * numpy.pi) for k in all_variables} else: raise TequilaOptimizerException("unknown initialization instruction: {}".format(initial_values)) elif callable(initial_values): initial_values = {k: initial_values(k) for k in all_variables} elif isinstance(initial_values, numbers.Number): initial_values = {k: initial_values for k in all_variables} else: # autocomplete initial values, warn if you did detected = False for k in all_variables: if k not in initial_values: initial_values[k] = 0.0 detected = True if detected and not self.silent: warnings.warn("initial_variables given but not complete: Autocompleted with zeroes", TequilaWarning) active_angles = {} for v in variables: active_angles[v] = initial_values[v] passive_angles = {} for k, v in initial_values.items(): if k not in active_angles.keys(): passive_angles[k] = v return active_angles, passive_angles, variables def __call__(self, Hamiltonian, unitary, variables: typing.List[Variable] = None, initial_values: typing.Dict[Variable, numbers.Real] = None, gradient: typing.Dict[Variable, Objective] = None, hessian: typing.Dict[typing.Tuple[Variable, Variable], Objective] = None, reset_history: bool = True, *args, **kwargs) -> SciPyResults: """ Perform optimization using scipy optimizers. Parameters ---------- objective: Objective: the objective to optimize. variables: list, optional: the variables of objective to optimize. If None: optimize all. initial_values: dict, optional: a starting point from which to begin optimization. Will be generated if None. gradient: optional: Information or object used to calculate the gradient of objective. Defaults to None: get analytically. hessian: optional: Information or object used to calculate the hessian of objective. Defaults to None: get analytically. reset_history: bool: Default = True: whether or not to reset all history before optimizing. args kwargs Returns ------- ScipyReturnType: the results of optimization. """ H = convert_PQH_to_tq_QH(Hamiltonian) Ham_variables, Ham_derivatives = H._construct_derivatives() #print("hamvars",Ham_variables) all_variables = copy.deepcopy(Ham_variables) #print(all_variables) for var in unitary.extract_variables(): all_variables.append(var) #print(all_variables) infostring = "{:15} : {}\n".format("Method", self.method) #infostring += "{:15} : {} expectationvalues\n".format("Objective", objective.count_expectationvalues()) if self.save_history and reset_history: self.reset_history() active_angles, passive_angles, variables = self.initialize_variables(all_variables, initial_values, variables) #print(active_angles, passive_angles, variables) # Transform the initial value directory into (ordered) arrays param_keys, param_values = zip(*active_angles.items()) param_values = numpy.array(param_values) # process and initialize scipy bounds bounds = None if self.method_bounds is not None: bounds = {k: None for k in active_angles} for k, v in self.method_bounds.items(): if k in bounds: bounds[k] = v infostring += "{:15} : {}\n".format("bounds", self.method_bounds) names, bounds = zip(*bounds.items()) assert (names == param_keys) # make sure the bounds are not shuffled #print(param_keys, param_values) # do the compilation here to avoid costly recompilation during the optimization #compiled_objective = self.compile_objective(objective=objective, *args, **kwargs) E = _EvalContainer(Hamiltonian = H, unitary = unitary, Eval=None, param_keys=param_keys, samples=self.samples, passive_angles=passive_angles, save_history=self.save_history, print_level=self.print_level) E.print_level = 0 (E(param_values)) E.print_level = self.print_level infostring += E.infostring if gradient is not None: infostring += "{:15} : {}\n".format("grad instr", gradient) if hessian is not None: infostring += "{:15} : {}\n".format("hess_instr", hessian) compile_gradient = self.method in (self.gradient_based_methods + self.hessian_based_methods) compile_hessian = self.method in self.hessian_based_methods dE = None ddE = None # detect if numerical gradients shall be used # switch off compiling if so if isinstance(gradient, str): if gradient.lower() == 'qng': compile_gradient = False if compile_hessian: raise TequilaException('Sorry, QNG and hessian not yet tested together.') combos = get_qng_combos(objective, initial_values=initial_values, backend=self.backend, samples=self.samples, noise=self.noise) dE = _QngContainer(combos=combos, param_keys=param_keys, passive_angles=passive_angles) infostring += "{:15} : QNG {}\n".format("gradient", dE) else: dE = gradient compile_gradient = False if compile_hessian: compile_hessian = False if hessian is None: hessian = gradient infostring += "{:15} : scipy numerical {}\n".format("gradient", dE) infostring += "{:15} : scipy numerical {}\n".format("hessian", ddE) if isinstance(gradient,dict): if gradient['method'] == 'qng': func = gradient['function'] compile_gradient = False if compile_hessian: raise TequilaException('Sorry, QNG and hessian not yet tested together.') combos = get_qng_combos(objective,func=func, initial_values=initial_values, backend=self.backend, samples=self.samples, noise=self.noise) dE = _QngContainer(combos=combos, param_keys=param_keys, passive_angles=passive_angles) infostring += "{:15} : QNG {}\n".format("gradient", dE) if isinstance(hessian, str): ddE = hessian compile_hessian = False if compile_gradient: dE =_GradContainer(Ham_derivatives = Ham_derivatives, unitary = unitary, Hamiltonian = H, Eval= E, param_keys=param_keys, samples=self.samples, passive_angles=passive_angles, save_history=self.save_history, print_level=self.print_level) dE.print_level = 0 (dE(param_values)) dE.print_level = self.print_level infostring += dE.infostring if self.print_level > 0: print(self) print(infostring) print("{:15} : {}\n".format("active variables", len(active_angles))) Es = [] optimizer_instance = self class SciPyCallback: energies = [] gradients = [] hessians = [] angles = [] real_iterations = 0 def __call__(self, *args, **kwargs): self.energies.append(E.history[-1]) self.angles.append(E.history_angles[-1]) if dE is not None and not isinstance(dE, str): self.gradients.append(dE.history[-1]) if ddE is not None and not isinstance(ddE, str): self.hessians.append(ddE.history[-1]) self.real_iterations += 1 if 'callback' in optimizer_instance.kwargs: optimizer_instance.kwargs['callback'](E.history_angles[-1]) callback = SciPyCallback() res = scipy.optimize.minimize(E, x0=param_values, jac=dE, hess=ddE, args=(Es,), method=self.method, tol=self.tol, bounds=bounds, constraints=self.method_constraints, options=self.method_options, callback=callback) # failsafe since callback is not implemented everywhere if callback.real_iterations == 0: real_iterations = range(len(E.history)) if self.save_history: self.history.energies = callback.energies self.history.energy_evaluations = E.history self.history.angles = callback.angles self.history.angles_evaluations = E.history_angles self.history.gradients = callback.gradients self.history.hessians = callback.hessians if dE is not None and not isinstance(dE, str): self.history.gradients_evaluations = dE.history if ddE is not None and not isinstance(ddE, str): self.history.hessians_evaluations = ddE.history # some methods like "cobyla" do not support callback functions if len(self.history.energies) == 0: self.history.energies = E.history self.history.angles = E.history_angles # some scipy methods always give back the last value and not the minimum (e.g. cobyla) ea = sorted(zip(E.history, E.history_angles), key=lambda x: x[0]) E_final = ea[0][0] angles_final = ea[0][1] #dict((param_keys[i], res.x[i]) for i in range(len(param_keys))) angles_final = {**angles_final, **passive_angles} return SciPyResults(energy=E_final, history=self.history, variables=format_variable_dictionary(angles_final), scipy_result=res) def minimize(Hamiltonian, unitary, gradient: typing.Union[str, typing.Dict[Variable, Objective]] = None, hessian: typing.Union[str, typing.Dict[typing.Tuple[Variable, Variable], Objective]] = None, initial_values: typing.Dict[typing.Hashable, numbers.Real] = None, variables: typing.List[typing.Hashable] = None, samples: int = None, maxiter: int = 100, backend: str = None, backend_options: dict = None, noise: NoiseModel = None, device: str = None, method: str = "BFGS", tol: float = 1.e-3, method_options: dict = None, method_bounds: typing.Dict[typing.Hashable, numbers.Real] = None, method_constraints=None, silent: bool = False, save_history: bool = True, *args, **kwargs) -> SciPyResults: """ calls the local optimize_scipy scipy funtion instead and pass down the objective construction down Parameters ---------- objective: Objective : The tequila objective to optimize gradient: typing.Union[str, typing.Dict[Variable, Objective], None] : Default value = None): '2-point', 'cs' or '3-point' for numerical gradient evaluation (does not work in combination with all optimizers), dictionary of variables and tequila objective to define own gradient, None for automatic construction (default) Other options include 'qng' to use the quantum natural gradient. hessian: typing.Union[str, typing.Dict[Variable, Objective], None], optional: '2-point', 'cs' or '3-point' for numerical gradient evaluation (does not work in combination with all optimizers), dictionary (keys:tuple of variables, values:tequila objective) to define own gradient, None for automatic construction (default) initial_values: typing.Dict[typing.Hashable, numbers.Real], optional: Initial values as dictionary of Hashable types (variable keys) and floating point numbers. If given None they will all be set to zero variables: typing.List[typing.Hashable], optional: List of Variables to optimize samples: int, optional: samples/shots to take in every run of the quantum circuits (None activates full wavefunction simulation) maxiter: int : (Default value = 100): max iters to use. backend: str, optional: Simulator backend, will be automatically chosen if set to None backend_options: dict, optional: Additional options for the backend Will be unpacked and passed to the compiled objective in every call noise: NoiseModel, optional: a NoiseModel to apply to all expectation values in the objective. method: str : (Default = "BFGS"): Optimization method (see scipy documentation, or 'available methods') tol: float : (Default = 1.e-3): Convergence tolerance for optimization (see scipy documentation) method_options: dict, optional: Dictionary of options (see scipy documentation) method_bounds: typing.Dict[typing.Hashable, typing.Tuple[float, float]], optional: bounds for the variables (see scipy documentation) method_constraints: optional: (see scipy documentation silent: bool : No printout if True save_history: bool: Save the history throughout the optimization Returns ------- SciPyReturnType: the results of optimization """ if isinstance(gradient, dict) or hasattr(gradient, "items"): if all([isinstance(x, Objective) for x in gradient.values()]): gradient = format_variable_dictionary(gradient) if isinstance(hessian, dict) or hasattr(hessian, "items"): if all([isinstance(x, Objective) for x in hessian.values()]): hessian = {(assign_variable(k[0]), assign_variable([k[1]])): v for k, v in hessian.items()} method_bounds = format_variable_dictionary(method_bounds) # set defaults optimizer = optimize_scipy(save_history=save_history, maxiter=maxiter, method=method, method_options=method_options, method_bounds=method_bounds, method_constraints=method_constraints, silent=silent, backend=backend, backend_options=backend_options, device=device, samples=samples, noise_model=noise, tol=tol, *args, **kwargs) if initial_values is not None: initial_values = {assign_variable(k): v for k, v in initial_values.items()} return optimizer(Hamiltonian, unitary, gradient=gradient, hessian=hessian, initial_values=initial_values, variables=variables, *args, **kwargs)
24,489
42.732143
144
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.6/energy_optimization.py
import tequila as tq import numpy as np from tequila.objective.objective import Variable import openfermion from hacked_openfermion_qubit_operator import ParamQubitHamiltonian from typing import Union from vqe_utils import convert_PQH_to_tq_QH, convert_tq_QH_to_PQH,\ fold_unitary_into_hamiltonian from grad_hacked import grad from scipy_optimizer import minimize import scipy import random # guess we could substitute that with numpy.random #TODO import argparse import pickle as pk import sys sys.path.insert(0, '../../../') #sys.path.insert(0, '../') # This needs to be properly integrated somewhere else at some point # from tn_update.qq import contract_energy, optimize_wavefunctions from tn_update.my_mpo import * from tn_update.wfn_optimization import contract_energy_mpo, optimize_wavefunctions_mpo, initialize_wfns_randomly def energy_from_wfn_opti(hamiltonian: tq.QubitHamiltonian, n_qubits: int, guess_wfns=None, TOL=1e-4) -> tuple: ''' Get energy using a tensornetwork based method ~ power method (here as blackbox) ''' d = int(2**(n_qubits/2)) # Build MPO h_mpo = MyMPO(hamiltonian=hamiltonian, n_qubits=n_qubits, maxdim=500) h_mpo.make_mpo_from_hamiltonian() # Optimize wavefunctions based on random guess out = None it = 0 while out is None: # Set up random initial guesses for subsystems it += 1 if guess_wfns is None: psiL_rand = initialize_wfns_randomly(d, n_qubits//2) psiR_rand = initialize_wfns_randomly(d, n_qubits//2) else: psiL_rand = guess_wfns[0] psiR_rand = guess_wfns[1] out = optimize_wavefunctions_mpo(h_mpo, psiL_rand, psiR_rand, TOL=TOL, silent=True) energy_rand = out[0] optimal_wfns = [out[1], out[2]] return energy_rand, optimal_wfns def combine_two_clusters(H: tq.QubitHamiltonian, subsystems: list, circ_list: list) -> float: ''' E = nuc_rep + \sum_j c_j <0_A | U_A+ sigma_j|A U_A | 0_A><0_B | U_B+ sigma_j|B U_B | 0_B> i ) Split up Hamiltonian into vector c = [c_j], all sigmas of system A and system B ii ) Two vectors of ExpectationValues E_A=[E(U_A, sigma_j|A)], E_B=[E(U_B, sigma_j|B)] iii) Minimize vectors from ii) iv ) Perform weighted sum \sum_j c_[j] E_A[j] E_B[j] result = nuc_rep + iv) Finishing touch inspired by private tequila-repo / pair-separated objective This is still rather inefficient/unoptimized Can still prune out near-zero coefficients c_j ''' objective = 0.0 n_subsystems = len(subsystems) # Over all Paulistrings in the Hamiltonian for p_index, pauli in enumerate(H.paulistrings): # Gather coefficient coeff = pauli.coeff.real # Empty dictionary for operations: # to be filled with another dictionary per subsystem, where then # e.g. X(0)Z(1)Y(2)X(4) and subsystems=[[0,1,2],[3,4,5]] # -> ops={ 0: {0: 'X', 1: 'Z', 2: 'Y'}, 1: {4: 'X'} } ops = {} for s_index, sys in enumerate(subsystems): for k, v in pauli.items(): if k in sys: if s_index in ops: ops[s_index][k] = v else: ops[s_index] = {k: v} # If no ops gathered -> identity -> nuclear repulsion if len(ops) == 0: #print ("this should only happen ONCE") objective += coeff # If not just identity: # add objective += c_j * prod_subsys( < Paulistring_j_subsys >_{U_subsys} ) elif len(ops) > 0: obj_tmp = coeff for s_index, sys_pauli in ops.items(): #print (s_index, sys_pauli) H_tmp = QubitHamiltonian.from_paulistrings(PauliString(data=sys_pauli)) E_tmp = ExpectationValue(U=circ_list[s_index], H=H_tmp) obj_tmp *= E_tmp objective += obj_tmp initial_values = {k: 0.0 for k in objective.extract_variables()} random_initial_values = {k: 1e-2*np.random.uniform(-1, 1) for k in objective.extract_variables()} method = 'bfgs' # 'bfgs' # 'l-bfgs-b' # 'cobyla' # 'slsqp' curr_res = tq.minimize(method=method, objective=objective, initial_values=initial_values, gradient='two-point', backend='qulacs', method_options={"finite_diff_rel_step": 1e-3}) return curr_res.energy def energy_from_tq_qcircuit(hamiltonian: Union[tq.QubitHamiltonian, ParamQubitHamiltonian], n_qubits: int, circuit = Union[list, tq.QCircuit], subsystems: list = [[0,1,2,3,4,5]], initial_guess = None)-> tuple: ''' Get minimal energy using tequila ''' result = None # If only one circuit handed over, just run simple VQE if isinstance(circuit, list) and len(circuit) == 1: circuit = circuit[0] if isinstance(circuit, tq.QCircuit): if isinstance(hamiltonian, tq.QubitHamiltonian): E = tq.ExpectationValue(H=hamiltonian, U=circuit) if initial_guess is None: initial_angles = {k: 0.0 for k in E.extract_variables()} else: initial_angles = initial_guess #print ("optimizing non-param...") result = tq.minimize(objective=E, method='l-bfgs-b', silent=True, backend='qulacs', initial_values=initial_angles) #gradient='two-point', backend='qulacs', #method_options={"finite_diff_rel_step": 1e-4}) elif isinstance(hamiltonian, ParamQubitHamiltonian): if initial_guess is None: raise Exception("Need to provide initial guess for this to work.") initial_angles = None else: initial_angles = initial_guess #print ("optimizing param...") result = minimize(hamiltonian, circuit, method='bfgs', initial_values=initial_angles, backend="qulacs", silent=True) # If more circuits handed over, assume subsystems else: # TODO!! implement initial guess for the combine_two_clusters thing #print ("Should not happen for now...") result = combine_two_clusters(hamiltonian, subsystems, circuit) return result.energy, result.angles def mixed_optimization(hamiltonian: ParamQubitHamiltonian, n_qubits: int, initial_guess: Union[dict, list]=None, init_angles: list=None): ''' Minimizes energy using wfn opti and a parametrized Hamiltonian min_{psi, theta fixed} <psi | H(theta) | psi> --> min_{t, p fixed} <p | H(t) | p> ^---------------------------------------------------^ until convergence ''' energy, optimal_state = None, None H_qh = convert_PQH_to_tq_QH(hamiltonian) var_keys, H_derivs = H_qh._construct_derivatives() print("var keys", var_keys, flush=True) print('var dict', init_angles, flush=True) # if not init_angles: # var_vals = [0. for i in range(len(var_keys))] # initialize with 0 # else: # var_vals = init_angles def build_variable_dict(keys, values): assert(len(keys)==len(values)) out = dict() for idx, key in enumerate(keys): out[key] = complex(values[idx]) return out var_dict = init_angles var_vals = [*init_angles.values()] assert(build_variable_dict(var_keys, var_vals) == var_dict) def wrap_energy_eval(psi): ''' like energy_from_wfn_opti but instead of optimize get inner product ''' def energy_eval_fn(x): var_dict = build_variable_dict(var_keys, x) H_qh_fix = H_qh(var_dict) H_mpo = MyMPO(hamiltonian=H_qh_fix, n_qubits=n_qubits, maxdim=500) H_mpo.make_mpo_from_hamiltonian() return contract_energy_mpo(H_mpo, psi[0], psi[1]) return energy_eval_fn def wrap_gradient_eval(psi): ''' call derivatives with updated variable list ''' def gradient_eval_fn(x): variables = build_variable_dict(var_keys, x) deriv_expectations = H_derivs.values() # list of ParamQubitHamiltonian's deriv_qhs = [convert_PQH_to_tq_QH(d) for d in deriv_expectations] deriv_qhs = [d(variables) for d in deriv_qhs] # list of tq.QubitHamiltonian's # print(deriv_qhs) deriv_mpos = [MyMPO(hamiltonian=d, n_qubits=n_qubits, maxdim=500)\ for d in deriv_qhs] # print(deriv_mpos[0].n_qubits) for d in deriv_mpos: d.make_mpo_from_hamiltonian() # deriv_mpos = [d.make_mpo_from_hamiltonian() for d in deriv_mpos] return np.asarray([contract_energy_mpo(d, psi[0], psi[1]) for d in deriv_mpos]) return gradient_eval_fn def do_wfn_opti(values, guess_wfns, TOL): # H_qh = H_qh(H_vars) var_dict = build_variable_dict(var_keys, values) en, psi = energy_from_wfn_opti(H_qh(var_dict), n_qubits=n_qubits, guess_wfns=guess_wfns, TOL=TOL) return en, psi def do_param_opti(psi, x0): result = scipy.optimize.minimize(fun=wrap_energy_eval(psi), jac=wrap_gradient_eval(psi), method='bfgs', x0=x0, options={'maxiter': 4}) # print(result) return result e_prev, psi_prev = 123., None # print("iguess", initial_guess) e_curr, psi_curr = do_wfn_opti(var_vals, initial_guess, 1e-5) print('first eval', e_curr, flush=True) def converged(e_prev, e_curr, TOL=1e-4): return True if np.abs(e_prev-e_curr) < TOL else False it = 0 var_prev = var_vals print("vars before comp", var_prev, flush=True) while not converged(e_prev, e_curr) and it < 50: e_prev, psi_prev = e_curr, psi_curr # print('before param opti') res = do_param_opti(psi_curr, var_prev) var_curr = res['x'] print('curr vars', var_curr, flush=True) e_curr = res['fun'] print('en before wfn opti', e_curr, flush=True) # print("iiiiiguess", psi_prev) e_curr, psi_curr = do_wfn_opti(var_curr, psi_prev, 1e-3) print('en after wfn opti', e_curr, flush=True) it += 1 print('at iteration', it, flush=True) return e_curr, psi_curr # optimize parameters with fixed wavefunction # define/wrap energy function - given |p>, evaluate <p|H(t)|p> ''' def wrap_gradient(objective: typing.Union[Objective, QTensor], no_compile=False, *args, **kwargs): def gradient_fn(variable: Variable = None): return grad(objective: typing.Union[Objective, QTensor], variable: Variable = None, no_compile=False, *args, **kwargs) return grad_fn ''' def minimize_energy(hamiltonian: Union[ParamQubitHamiltonian, tq.QubitHamiltonian], n_qubits: int, type_energy_eval: str='wfn', cluster_circuit: tq.QCircuit=None, initial_guess=None, initial_mixed_angles: dict=None) -> float: ''' Minimizes energy functional either according a power-method inspired shortcut ('wfn') or using a unitary circuit ('qc') ''' if type_energy_eval == 'wfn': if isinstance(hamiltonian, tq.QubitHamiltonian): energy, optimal_state = energy_from_wfn_opti(hamiltonian, n_qubits, initial_guess) elif isinstance(hamiltonian, ParamQubitHamiltonian): init_angles = initial_mixed_angles energy, optimal_state = mixed_optimization(hamiltonian=hamiltonian, n_qubits=n_qubits, initial_guess=initial_guess, init_angles=init_angles) elif type_energy_eval == 'qc': if cluster_circuit is None: raise Exception("Need to hand over circuit!") energy, optimal_state = energy_from_tq_qcircuit(hamiltonian, n_qubits, cluster_circuit, [[0,1,2,3],[4,5,6,7]], initial_guess) else: raise Exception("Option not implemented!") return energy, optimal_state
12,457
43.021201
225
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.6/parallel_annealing.py
import tequila as tq import multiprocessing import copy from time import sleep from mutation_options import * from pathos.multiprocessing import ProcessingPool as Pool def evolve_population(hamiltonian, type_energy_eval, cluster_circuit, process_id, num_offsprings, actions_ratio, tasks, results): """ This function carries a single step of the simulated annealing on a single member of the generation args: process_id: A unique identifier for each process num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for mutations tasks: multiprocessing queue to pass family_id, instructions and current_fitness family_id: A unique identifier for each family instructions: An object consisting of the instructions in the quantum circuit current_fitness: Current fitness value of the circuit results: multiprocessing queue to pass results back """ #print('[%s] evaluation routine starts' % process_id) while True: try: #getting parameters for mutation and carrying it family_id, instructions, current_fitness = tasks.get() #check if patience has been exhausted if instructions.patience == 0: instructions.reset_to_best() best_child = 0 best_energy = current_fitness new_generations = {} for off_id in range(1, num_offsprings+1): scheduled_ratio = schedule_actions_ratio(epoch=0, steady_ratio=actions_ratio) action = get_action(scheduled_ratio) updated_instructions = copy.deepcopy(instructions) updated_instructions.update_by_action(action) new_fitness, wfn = evaluate_fitness(updated_instructions, hamiltonian, type_energy_eval, cluster_circuit) updated_instructions.set_reference_wfn(wfn) prob_acceptance = get_prob_acceptance(current_fitness, new_fitness, updated_instructions.T, updated_instructions.reference_energy) # need to figure out in case we have two equals new_generations[str(off_id)] = updated_instructions if best_energy > new_fitness: # now two equals -> "first one" is picked best_child = off_id best_energy = new_fitness # decision = np.random.binomial(1, prob_acceptance) # if decision == 0: if best_child == 0: # Add result to the queue instructions.patience -= 1 #print('Reduced patience -- now ' + str(updated_instructions.patience)) if instructions.patience == 0: if instructions.best_previous_instructions: instructions.reset_to_best() else: instructions.update_T() results.put((family_id, instructions, current_fitness)) else: # Add result to the queue if (best_energy < current_fitness): new_generations[str(best_child)].update_best_previous_instructions() new_generations[str(best_child)].update_T() results.put((family_id, new_generations[str(best_child)], best_energy)) except Exception as eeee: #print('[%s] evaluation routine quits' % process_id) #print(eeee) # Indicate finished results.put(-1) break return def evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, num_processors=4, type_energy_eval='wfn', cluster_circuit=None): """ This function does parallel mutation on all the members of the generation and updates the generation args: num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for sampling instructions_dict: A dictionary with the "Instructions" objects the corresponding fitness values as values num_processors: Number of processors to use for parallel run """ # Define IPC manager manager = multiprocessing.Manager() # Define a list (queue) for tasks and computation results tasks = manager.Queue() results = manager.Queue() processes = [] pool = Pool(processes=num_processors) for i in range(num_processors): process_id = 'P%i' % i # Create the process, and connect it to the worker function new_process = multiprocessing.Process(target=evolve_population, args=(hamiltonian, type_energy_eval, cluster_circuit, process_id, num_offsprings, actions_ratio, tasks, results)) # Add new process to the list of processes processes.append(new_process) # Start the process new_process.start() #print("putting tasks") for family_id in instructions_dict: single_task = (family_id, instructions_dict[family_id][0], instructions_dict[family_id][1]) tasks.put(single_task) # Wait while the workers process - change it to something for our case later # sleep(5) multiprocessing.Barrier(num_processors) #print("after barrier") # Quit the worker processes by sending them -1 for i in range(num_processors): tasks.put(-1) # Read calculation results num_finished_processes = 0 while True: # Read result #print("num fin", num_finished_processes) try: family_id, updated_instructions, new_fitness = results.get() instructions_dict[family_id] = (updated_instructions, new_fitness) except: # Process has finished num_finished_processes += 1 if num_finished_processes == num_processors: break for process in processes: process.join() pool.close()
6,456
38.371951
146
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.6/single_thread_annealing.py
import tequila as tq import copy from mutation_options import * def st_evolve_population(hamiltonian, type_energy_eval, cluster_circuit, num_offsprings, actions_ratio, tasks): """ This function carries a single step of the simulated annealing on a single member of the generation args: num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for mutations tasks: a tuple of (family_id, instructions and current_fitness) family_id: A unique identifier for each family instructions: An object consisting of the instructions in the quantum circuit current_fitness: Current fitness value of the circuit """ family_id, instructions, current_fitness = tasks #check if patience has been exhausted if instructions.patience == 0: if instructions.best_previous_instructions: instructions.reset_to_best() best_child = 0 best_energy = current_fitness new_generations = {} for off_id in range(1, num_offsprings+1): scheduled_ratio = schedule_actions_ratio(epoch=0, steady_ratio=actions_ratio) action = get_action(scheduled_ratio) updated_instructions = copy.deepcopy(instructions) updated_instructions.update_by_action(action) new_fitness, wfn = evaluate_fitness(updated_instructions, hamiltonian, type_energy_eval, cluster_circuit) updated_instructions.set_reference_wfn(wfn) prob_acceptance = get_prob_acceptance(current_fitness, new_fitness, updated_instructions.T, updated_instructions.reference_energy) # need to figure out in case we have two equals new_generations[str(off_id)] = updated_instructions if best_energy > new_fitness: # now two equals -> "first one" is picked best_child = off_id best_energy = new_fitness # decision = np.random.binomial(1, prob_acceptance) # if decision == 0: if best_child == 0: # Add result to the queue instructions.patience -= 1 #print('Reduced patience -- now ' + str(updated_instructions.patience)) if instructions.patience == 0: if instructions.best_previous_instructions: instructions.reset_to_best() else: instructions.update_T() results = ((family_id, instructions, current_fitness)) else: # Add result to the queue if (best_energy < current_fitness): new_generations[str(best_child)].update_best_previous_instructions() new_generations[str(best_child)].update_T() results = ((family_id, new_generations[str(best_child)], best_energy)) return results def st_evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, type_energy_eval='wfn', cluster_circuit=None): """ This function does a single threas mutation on all the members of the generation and updates the generation args: num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for sampling instructions_dict: A dictionary with the "Instructions" objects the corresponding fitness values as values """ for family_id in instructions_dict: task = (family_id, instructions_dict[family_id][0], instructions_dict[family_id][1]) results = st_evolve_population(hamiltonian, type_energy_eval, cluster_circuit, num_offsprings, actions_ratio, task) family_id, updated_instructions, new_fitness = results instructions_dict[family_id] = (updated_instructions, new_fitness)
4,005
40.298969
138
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.6/mutation_options.py
import argparse import numpy as np import random import copy import tequila as tq from typing import Union from collections import Counter from time import time from vqe_utils import convert_PQH_to_tq_QH, convert_tq_QH_to_PQH,\ fold_unitary_into_hamiltonian from energy_optimization import minimize_energy global_seed = 1 class Instructions: ''' TODO need to put some documentation here ''' def __init__(self, n_qubits, mu=2.0, sigma=0.4, alpha=0.9, T_0=1.0, beta=0.5, patience=10, max_non_cliffords=0, reference_energy=0., number=None): # hardcoded values for now self.num_non_cliffords = 0 self.max_non_cliffords = max_non_cliffords # ------------------------ self.starting_patience = patience self.patience = patience self.mu = mu self.sigma = sigma self.alpha = alpha self.beta = beta self.T_0 = T_0 self.T = T_0 self.gates = self.get_random_gates(number=number) self.n_qubits = n_qubits self.positions = self.get_random_positions() self.best_previous_instructions = {} self.reference_energy = reference_energy self.best_reference_wfn = None self.noncliff_replacements = {} def _str(self): print(self.gates) print(self.positions) def set_reference_wfn(self, reference_wfn): self.best_reference_wfn = reference_wfn def update_T(self, update_type: str = 'regular', best_temp=None): # Regular update if update_type.lower() == 'regular': self.T = self.alpha * self.T # Temperature update if patience ran out elif update_type.lower() == 'patience': self.T = self.beta*best_temp + (1-self.beta)*self.T_0 def get_random_gates(self, number=None): ''' Randomly generates a list of gates. number indicates the number of gates to generate otherwise, number will be drawn from a log normal distribution ''' mu, sigma = self.mu, self.sigma full_options = ['X','Y','Z','S','H','CX', 'CY', 'CZ','SWAP', 'UCC2c', 'UCC4c', 'UCC2', 'UCC4'] clifford_options = ['X','Y','Z','S','H','CX', 'CY', 'CZ','SWAP', 'UCC2c', 'UCC4c'] #non_clifford_options = ['UCC2', 'UCC4'] # Gate distribution, selecting number of gates to add k = np.random.lognormal(mu, sigma) k = np.int(k) if number is not None: k = number # Selecting gate types gates = None if self.num_non_cliffords < self.max_non_cliffords: gates = random.choices(full_options, k=k) # with replacement else: gates = random.choices(clifford_options, k=k) new_num_non_cliffords = 0 if "UCC2" in gates: new_num_non_cliffords += Counter(gates)["UCC2"] if "UCC4" in gates: new_num_non_cliffords += Counter(gates)["UCC4"] if (new_num_non_cliffords+self.num_non_cliffords) <= self.max_non_cliffords: self.num_non_cliffords += new_num_non_cliffords else: extra_cliffords = (new_num_non_cliffords+self.num_non_cliffords) - self.max_non_cliffords assert(extra_cliffords >= 0) new_gates = random.choices(clifford_options, k=extra_cliffords) for g in new_gates: try: gates[gates.index("UCC4")] = g except: gates[gates.index("UCC2")] = g self.num_non_cliffords = self.max_non_cliffords if k == 1: if gates == "UCC2c" or gates == "UCC4c": gates = get_string_Cliff_ucc(gates) if gates == "UCC2" or gates == "UCC4": gates = get_string_ucc(gates) else: for ind, gate in enumerate(gates): if gate == "UCC2c" or gate == "UCC4c": gates[ind] = get_string_Cliff_ucc(gate) if gate == "UCC2" or gate == "UCC4": gates[ind] = get_string_ucc(gate) return gates def get_random_positions(self, gates=None): ''' Randomly assign gates to qubits. ''' if gates is None: gates = self.gates n_qubits = self.n_qubits single_qubit = ['X','Y','Z','S','H'] # two_qubit = ['CX','CY','CZ', 'SWAP'] two_qubit = ['CX', 'CY', 'CZ', 'SWAP', 'UCC2c', 'UCC2'] four_qubit = ['UCC4c', 'UCC4'] qubits = list(range(0, n_qubits)) q_positions = [] for gate in gates: if gate in four_qubit: p = random.sample(qubits, k=4) if gate in two_qubit: p = random.sample(qubits, k=2) if gate in single_qubit: p = random.sample(qubits, k=1) if "UCC2" in gate: p = random.sample(qubits, k=2) if "UCC4" in gate: p = random.sample(qubits, k=4) q_positions.append(p) return q_positions def delete(self, number=None): ''' Randomly drops some gates from a clifford instruction set if not specified, the number of gates to drop is sampled from a uniform distribution over all the gates ''' gates = copy.deepcopy(self.gates) positions = copy.deepcopy(self.positions) n_qubits = self.n_qubits if number is not None: num_to_drop = number else: num_to_drop = random.sample(range(1,len(gates)-1), k=1)[0] action_indices = random.sample(range(0,len(gates)-1), k=num_to_drop) for index in sorted(action_indices, reverse=True): if "UCC2_" in str(gates[index]) or "UCC4_" in str(gates[index]): self.num_non_cliffords -= 1 del gates[index] del positions[index] self.gates = gates self.positions = positions #print ('deleted {} gates'.format(num_to_drop)) def add(self, number=None): ''' adds a random selection of clifford gates to the end of a clifford instruction set if number is not specified, the number of gates to add will be drawn from a log normal distribution ''' gates = copy.deepcopy(self.gates) positions = copy.deepcopy(self.positions) n_qubits = self.n_qubits added_instructions = self.get_new_instructions(number=number) gates.extend(added_instructions['gates']) positions.extend(added_instructions['positions']) self.gates = gates self.positions = positions #print ('added {} gates'.format(len(added_instructions['gates']))) def change(self, number=None): ''' change a random number of gates and qubit positions in a clifford instruction set if not specified, the number of gates to change is sampled from a uniform distribution over all the gates ''' gates = copy.deepcopy(self.gates) positions = copy.deepcopy(self.positions) n_qubits = self.n_qubits if number is not None: num_to_change = number else: num_to_change = random.sample(range(1,len(gates)), k=1)[0] action_indices = random.sample(range(0,len(gates)-1), k=num_to_change) added_instructions = self.get_new_instructions(number=num_to_change) for i in range(num_to_change): gates[action_indices[i]] = added_instructions['gates'][i] positions[action_indices[i]] = added_instructions['positions'][i] self.gates = gates self.positions = positions #print ('changed {} gates'.format(len(added_instructions['gates']))) # TODO to be debugged! def prune(self): ''' Prune instructions to remove redundant operations: --> first gate should go beyond subsystems (this assumes expressible enough subsystem-ciruits #TODO later -> this needs subsystem information in here! --> 2 subsequent gates that are their respective inverse can be removed #TODO this might change the number of qubits acted on in theory? ''' pass #print ("DEBUG PRUNE FUNCTION!") # gates = copy.deepcopy(self.gates) # positions = copy.deepcopy(self.positions) # for g_index in range(len(gates)-1): # if (gates[g_index] == gates[g_index+1] and not 'S' in gates[g_index])\ # or (gates[g_index] == 'S' and gates[g_index+1] == 'S-dag')\ # or (gates[g_index] == 'S-dag' and gates[g_index+1] == 'S'): # print(len(gates)) # if positions[g_index] == positions[g_index+1]: # self.gates.pop(g_index) # self.positions.pop(g_index) def update_by_action(self, action: str): ''' Updates instruction dictionary -> Either adds, deletes or changes gates ''' if action == 'delete': try: self.delete() # In case there are too few gates to delete except: pass elif action == 'add': self.add() elif action == 'change': self.change() else: raise Exception("Unknown action type " + action + ".") self.prune() def update_best_previous_instructions(self): ''' Overwrites the best previous instructions with the current ones. ''' self.best_previous_instructions['gates'] = copy.deepcopy(self.gates) self.best_previous_instructions['positions'] = copy.deepcopy(self.positions) self.best_previous_instructions['T'] = copy.deepcopy(self.T) def reset_to_best(self): ''' Overwrites the current instructions with best previous ones. ''' #print ('Patience ran out... resetting to best previous instructions.') self.gates = copy.deepcopy(self.best_previous_instructions['gates']) self.positions = copy.deepcopy(self.best_previous_instructions['positions']) self.patience = copy.deepcopy(self.starting_patience) self.update_T(update_type='patience', best_temp=copy.deepcopy(self.best_previous_instructions['T'])) def get_new_instructions(self, number=None): ''' Returns a a clifford instruction set, a dictionary of gates and qubit positions for building a clifford circuit ''' mu = self.mu sigma = self.sigma n_qubits = self.n_qubits instruction = {} gates = self.get_random_gates(number=number) q_positions = self.get_random_positions(gates) assert(len(q_positions) == len(gates)) instruction['gates'] = gates instruction['positions'] = q_positions # instruction['n_qubits'] = n_qubits # instruction['patience'] = patience # instruction['best_previous_options'] = {} return instruction def replace_cg_w_ncg(self, gate_id): ''' replaces a set of Clifford gates with corresponding non-Cliffords ''' print("gates before", self.gates, flush=True) gate = self.gates[gate_id] if gate == 'X': gate = "Rx" elif gate == 'Y': gate = "Ry" elif gate == 'Z': gate = "Rz" elif gate == 'S': gate = "S_nc" #gate = "Rz" elif gate == 'H': gate = "H_nc" # this does not work??????? # gate = "Ry" elif gate == 'CX': gate = "CRx" elif gate == 'CY': gate = "CRy" elif gate == 'CZ': gate = "CRz" elif gate == 'SWAP':#find a way to change this as well pass # gate = "SWAP" elif "UCC2c" in str(gate): pre_gate = gate.split("_")[0] mid_gate = gate.split("_")[-1] gate = pre_gate + "_" + "UCC2" + "_" +mid_gate elif "UCC4c" in str(gate): pre_gate = gate.split("_")[0] mid_gate = gate.split("_")[-1] gate = pre_gate + "_" + "UCC4" + "_" + mid_gate self.gates[gate_id] = gate print("gates after", self.gates, flush=True) def build_circuit(instructions): ''' constructs a tequila circuit from a clifford instruction set ''' gates = instructions.gates q_positions = instructions.positions init_angles = {} clifford_circuit = tq.QCircuit() # for i in range(1, len(gates)): # TODO len(q_positions) not == len(gates) for i in range(len(gates)): if len(q_positions[i]) == 2: q1, q2 = q_positions[i] elif len(q_positions[i]) == 1: q1 = q_positions[i] q2 = None elif not len(q_positions[i]) == 4: raise Exception("q_positions[i] must have length 1, 2 or 4...") if gates[i] == 'X': clifford_circuit += tq.gates.X(q1) if gates[i] == 'Y': clifford_circuit += tq.gates.Y(q1) if gates[i] == 'Z': clifford_circuit += tq.gates.Z(q1) if gates[i] == 'S': clifford_circuit += tq.gates.S(q1) if gates[i] == 'H': clifford_circuit += tq.gates.H(q1) if gates[i] == 'CX': clifford_circuit += tq.gates.CX(q1, q2) if gates[i] == 'CY': #using generators clifford_circuit += tq.gates.S(q2) clifford_circuit += tq.gates.CX(q1, q2) clifford_circuit += tq.gates.S(q2).dagger() if gates[i] == 'CZ': #using generators clifford_circuit += tq.gates.H(q2) clifford_circuit += tq.gates.CX(q1, q2) clifford_circuit += tq.gates.H(q2) if gates[i] == 'SWAP': clifford_circuit += tq.gates.CX(q1, q2) clifford_circuit += tq.gates.CX(q2, q1) clifford_circuit += tq.gates.CX(q1, q2) if "UCC2c" in str(gates[i]) or "UCC4c" in str(gates[i]): clifford_circuit += get_clifford_UCC_circuit(gates[i], q_positions[i]) # NON-CLIFFORD STUFF FROM HERE ON global global_seed if gates[i] == "S_nc": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.S(q1) clifford_circuit += tq.gates.Rz(angle=var_name, target=q1) if gates[i] == "H_nc": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.H(q1) clifford_circuit += tq.gates.Ry(angle=var_name, target=q1) if gates[i] == "Rx": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.X(q1) clifford_circuit += tq.gates.Rx(angle=var_name, target=q1) if gates[i] == "Ry": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.Y(q1) clifford_circuit += tq.gates.Ry(angle=var_name, target=q1) if gates[i] == "Rz": global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0 clifford_circuit += tq.gates.Z(q1) clifford_circuit += tq.gates.Rz(angle=var_name, target=q1) if gates[i] == "CRx": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = np.pi clifford_circuit += tq.gates.Rx(angle=var_name, target=q2, control=q1) if gates[i] == "CRy": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = np.pi clifford_circuit += tq.gates.Ry(angle=var_name, target=q2, control=q1) if gates[i] == "CRz": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = np.pi clifford_circuit += tq.gates.Rz(angle=var_name, target=q2, control=q1) def get_ucc_init_angles(gate): angle = None pre_gate = gate.split("_")[0] mid_gate = gate.split("_")[-1] if mid_gate == 'Z': angle = 0. elif mid_gate == 'S': angle = 0. elif mid_gate == 'S-dag': angle = 0. else: raise Exception("This should not happen -- center/mid gate should be Z,S,S_dag.") return angle if "UCC2_" in str(gates[i]) or "UCC4_" in str(gates[i]): uccc_circuit = get_non_clifford_UCC_circuit(gates[i], q_positions[i]) clifford_circuit += uccc_circuit try: var_name = uccc_circuit.extract_variables()[0] init_angles[var_name]= get_ucc_init_angles(gates[i]) except: init_angles = {} return clifford_circuit, init_angles def get_non_clifford_UCC_circuit(gate, positions): """ """ pre_cir_dic = {"X":tq.gates.X, "Y":tq.gates.Y, "H":tq.gates.H, "I":None} pre_gate = gate.split("_")[0] pre_gates = pre_gate.split(*"#") pre_circuit = tq.QCircuit() for i, pos in enumerate(positions): try: pre_circuit += pre_cir_dic[pre_gates[i]](pos) except: pass for i, pos in enumerate(positions[:-1]): pre_circuit += tq.gates.CX(pos, positions[i+1]) global global_seed mid_gate = gate.split("_")[-1] mid_circuit = tq.QCircuit() if mid_gate == "S": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit += tq.gates.S(positions[-1]) mid_circuit += tq.gates.Rz(angle=tq.Variable(var_name), target=positions[-1]) elif mid_gate == "S-dag": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit += tq.gates.S(positions[-1]).dagger() mid_circuit += tq.gates.Rz(angle=tq.Variable(var_name), target=positions[-1]) elif mid_gate == "Z": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit += tq.gates.Z(positions[-1]) mid_circuit += tq.gates.Rz(angle=tq.Variable(var_name), target=positions[-1]) return pre_circuit + mid_circuit + pre_circuit.dagger() def get_string_Cliff_ucc(gate): """ this function randomly sample basis change and mid circuit elements for a ucc-type clifford circuit and adds it to the gate """ pre_circ_comp = ["X", "Y", "H", "I"] mid_circ_comp = ["S", "S-dag", "Z"] p = None if "UCC2c" in gate: p = random.sample(pre_circ_comp, k=2) elif "UCC4c" in gate: p = random.sample(pre_circ_comp, k=4) pre_gate = "#".join([str(item) for item in p]) mid_gate = random.sample(mid_circ_comp, k=1)[0] return str(pre_gate + "_" + gate + "_" + mid_gate) def get_string_ucc(gate): """ this function randomly sample basis change and mid circuit elements for a ucc-type clifford circuit and adds it to the gate """ pre_circ_comp = ["X", "Y", "H", "I"] p = None if "UCC2" in gate: p = random.sample(pre_circ_comp, k=2) elif "UCC4" in gate: p = random.sample(pre_circ_comp, k=4) pre_gate = "#".join([str(item) for item in p]) mid_gate = str(random.random() * 2 * np.pi) return str(pre_gate + "_" + gate + "_" + mid_gate) def get_clifford_UCC_circuit(gate, positions): """ This function creates an approximate UCC excitation circuit using only clifford Gates """ #pre_circ_comp = ["X", "Y", "H", "I"] pre_cir_dic = {"X":tq.gates.X, "Y":tq.gates.Y, "H":tq.gates.H, "I":None} pre_gate = gate.split("_")[0] pre_gates = pre_gate.split(*"#") #pre_gates = [] #if gate == "UCC2": # pre_gates = random.choices(pre_circ_comp, k=2) #if gate == "UCC4": # pre_gates = random.choices(pre_circ_comp, k=4) pre_circuit = tq.QCircuit() for i, pos in enumerate(positions): try: pre_circuit += pre_cir_dic[pre_gates[i]](pos) except: pass for i, pos in enumerate(positions[:-1]): pre_circuit += tq.gates.CX(pos, positions[i+1]) #mid_circ_comp = ["S", "S-dag", "Z"] #mid_gate = random.sample(mid_circ_comp, k=1)[0] mid_gate = gate.split("_")[-1] mid_circuit = tq.QCircuit() if mid_gate == "S": mid_circuit += tq.gates.S(positions[-1]) elif mid_gate == "S-dag": mid_circuit += tq.gates.S(positions[-1]).dagger() elif mid_gate == "Z": mid_circuit += tq.gates.Z(positions[-1]) return pre_circuit + mid_circuit + pre_circuit.dagger() def get_UCC_circuit(gate, positions): """ This function creates an UCC excitation circuit """ #pre_circ_comp = ["X", "Y", "H", "I"] pre_cir_dic = {"X":tq.gates.X, "Y":tq.gates.Y, "H":tq.gates.H, "I":None} pre_gate = gate.split("_")[0] pre_gates = pre_gate.split(*"#") pre_circuit = tq.QCircuit() for i, pos in enumerate(positions): try: pre_circuit += pre_cir_dic[pre_gates[i]](pos) except: pass for i, pos in enumerate(positions[:-1]): pre_circuit += tq.gates.CX(pos, positions[i+1]) mid_gate_val = gate.split("_")[-1] global global_seed np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit = tq.gates.Rz(target=positions[-1], angle=tq.Variable(var_name)) # mid_circ_comp = ["S", "S-dag", "Z"] # mid_gate = random.sample(mid_circ_comp, k=1)[0] # mid_circuit = tq.QCircuit() # if mid_gate == "S": # mid_circuit += tq.gates.S(positions[-1]) # elif mid_gate == "S-dag": # mid_circuit += tq.gates.S(positions[-1]).dagger() # elif mid_gate == "Z": # mid_circuit += tq.gates.Z(positions[-1]) return pre_circuit + mid_circuit + pre_circuit.dagger() def schedule_actions_ratio(epoch: int, action_options: list = ['delete', 'change', 'add'], decay: int = 30, steady_ratio: Union[tuple, list] = [0.2, 0.6, 0.2]) -> list: delete, change, add = tuple(steady_ratio) actions_ratio = [] for action in action_options: if action == 'delete': actions_ratio += [ delete*(1-np.exp(-1*epoch / decay)) ] elif action == 'change': actions_ratio += [ change*(1-np.exp(-1*epoch / decay)) ] elif action == 'add': actions_ratio += [ (1-add)*np.exp(-1*epoch / decay) + add ] else: print('Action type ', action, ' not defined!') # unnecessary for current schedule # if not np.isclose(np.sum(actions_ratio), 1.0): # actions_ratio /= np.sum(actions_ratio) return actions_ratio def get_action(ratio: list = [0.20,0.60,0.20]): ''' randomly chooses an action from delete, change, add ratio denotes the multinomial probabilities ''' choice = np.random.multinomial(n=1, pvals = ratio, size = 1) index = np.where(choice[0] == 1) action_options = ['delete', 'change', 'add'] action = action_options[index[0].item()] return action def get_prob_acceptance(E_curr, E_prev, T, reference_energy): ''' Computes acceptance probability of a certain action based on change in energy ''' delta_E = E_curr - E_prev prob = 0 if delta_E < 0 and E_curr < reference_energy: prob = 1 else: if E_curr < reference_energy: prob = np.exp(-delta_E/T) else: prob = 0 return prob def perform_folding(hamiltonian, circuit): # QubitHamiltonian -> ParamQubitHamiltonian param_hamiltonian = convert_tq_QH_to_PQH(hamiltonian) gates = circuit.gates # Go backwards gates.reverse() for gate in gates: # print("\t folding", gate) param_hamiltonian = (fold_unitary_into_hamiltonian(gate, param_hamiltonian)) # hamiltonian = convert_PQH_to_tq_QH(param_hamiltonian)() hamiltonian = param_hamiltonian return hamiltonian def evaluate_fitness(instructions, hamiltonian: tq.QubitHamiltonian, type_energy_eval: str, cluster_circuit: tq.QCircuit=None) -> tuple: ''' Evaluates fitness=objective=energy given a system for a set of instructions ''' #print ("evaluating fitness") n_qubits = instructions.n_qubits clifford_circuit, init_angles = build_circuit(instructions) # tq.draw(clifford_circuit, backend="cirq") ## TODO check if cluster_circuit is parametrized t0 = time() t1 = None folded_hamiltonian = perform_folding(hamiltonian, clifford_circuit) t1 = time() #print ("\tfolding took ", t1-t0) parametrized = len(clifford_circuit.extract_variables()) > 0 initial_guess = None if not parametrized: folded_hamiltonian = (convert_PQH_to_tq_QH(folded_hamiltonian))() elif parametrized: # TODO clifford_circuit is both ref + rest; so nomenclature is shit here variables = [gate.extract_variables() for gate in clifford_circuit.gates\ if gate.extract_variables()] variables = np.array(variables).flatten().tolist() # TODO this initial_guess is absolutely useless rn and is just causing problems if called initial_guess = { k: 0.1 for k in variables } if instructions.best_reference_wfn is not None: initial_guess = instructions.best_reference_wfn E_new, optimal_state = minimize_energy(hamiltonian=folded_hamiltonian, n_qubits=n_qubits, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit, initial_guess=initial_guess,\ initial_mixed_angles=init_angles) t2 = time() #print ("evaluated fitness; comp was ", t2-t1) #print ("current fitness: ", E_new) return E_new, optimal_state
26,497
34.096689
191
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.6/hacked_openfermion_qubit_operator.py
import tequila as tq import sympy import copy #from param_hamiltonian import get_geometry, generate_ucc_ansatz from hacked_openfermion_symbolic_operator import SymbolicOperator # Define products of all Pauli operators for symbolic multiplication. _PAULI_OPERATOR_PRODUCTS = { ('I', 'I'): (1., 'I'), ('I', 'X'): (1., 'X'), ('X', 'I'): (1., 'X'), ('I', 'Y'): (1., 'Y'), ('Y', 'I'): (1., 'Y'), ('I', 'Z'): (1., 'Z'), ('Z', 'I'): (1., 'Z'), ('X', 'X'): (1., 'I'), ('Y', 'Y'): (1., 'I'), ('Z', 'Z'): (1., 'I'), ('X', 'Y'): (1.j, 'Z'), ('X', 'Z'): (-1.j, 'Y'), ('Y', 'X'): (-1.j, 'Z'), ('Y', 'Z'): (1.j, 'X'), ('Z', 'X'): (1.j, 'Y'), ('Z', 'Y'): (-1.j, 'X') } _clifford_h_products = { ('I') : (1., 'I'), ('X') : (1., 'Z'), ('Y') : (-1., 'Y'), ('Z') : (1., 'X') } _clifford_s_products = { ('I') : (1., 'I'), ('X') : (-1., 'Y'), ('Y') : (1., 'X'), ('Z') : (1., 'Z') } _clifford_s_dag_products = { ('I') : (1., 'I'), ('X') : (1., 'Y'), ('Y') : (-1., 'X'), ('Z') : (1., 'Z') } _clifford_cx_products = { ('I', 'I'): (1., 'I', 'I'), ('I', 'X'): (1., 'I', 'X'), ('I', 'Y'): (1., 'Z', 'Y'), ('I', 'Z'): (1., 'Z', 'Z'), ('X', 'I'): (1., 'X', 'X'), ('X', 'X'): (1., 'X', 'I'), ('X', 'Y'): (1., 'Y', 'Z'), ('X', 'Z'): (-1., 'Y', 'Y'), ('Y', 'I'): (1., 'Y', 'X'), ('Y', 'X'): (1., 'Y', 'I'), ('Y', 'Y'): (-1., 'X', 'Z'), ('Y', 'Z'): (1., 'X', 'Y'), ('Z', 'I'): (1., 'Z', 'I'), ('Z', 'X'): (1., 'Z', 'X'), ('Z', 'Y'): (1., 'I', 'Y'), ('Z', 'Z'): (1., 'I', 'Z'), } _clifford_cy_products = { ('I', 'I'): (1., 'I', 'I'), ('I', 'X'): (1., 'Z', 'X'), ('I', 'Y'): (1., 'I', 'Y'), ('I', 'Z'): (1., 'Z', 'Z'), ('X', 'I'): (1., 'X', 'Y'), ('X', 'X'): (-1., 'Y', 'Z'), ('X', 'Y'): (1., 'X', 'I'), ('X', 'Z'): (-1., 'Y', 'X'), ('Y', 'I'): (1., 'Y', 'Y'), ('Y', 'X'): (1., 'X', 'Z'), ('Y', 'Y'): (1., 'Y', 'I'), ('Y', 'Z'): (-1., 'X', 'X'), ('Z', 'I'): (1., 'Z', 'I'), ('Z', 'X'): (1., 'I', 'X'), ('Z', 'Y'): (1., 'Z', 'Y'), ('Z', 'Z'): (1., 'I', 'Z'), } _clifford_cz_products = { ('I', 'I'): (1., 'I', 'I'), ('I', 'X'): (1., 'Z', 'X'), ('I', 'Y'): (1., 'Z', 'Y'), ('I', 'Z'): (1., 'I', 'Z'), ('X', 'I'): (1., 'X', 'Z'), ('X', 'X'): (-1., 'Y', 'Y'), ('X', 'Y'): (-1., 'Y', 'X'), ('X', 'Z'): (1., 'X', 'I'), ('Y', 'I'): (1., 'Y', 'Z'), ('Y', 'X'): (-1., 'X', 'Y'), ('Y', 'Y'): (1., 'X', 'X'), ('Y', 'Z'): (1., 'Y', 'I'), ('Z', 'I'): (1., 'Z', 'I'), ('Z', 'X'): (1., 'I', 'X'), ('Z', 'Y'): (1., 'I', 'Y'), ('Z', 'Z'): (1., 'Z', 'Z'), } COEFFICIENT_TYPES = (int, float, complex, sympy.Expr, tq.Variable) class ParamQubitHamiltonian(SymbolicOperator): @property def actions(self): """The allowed actions.""" return ('X', 'Y', 'Z') @property def action_strings(self): """The string representations of the allowed actions.""" return ('X', 'Y', 'Z') @property def action_before_index(self): """Whether action comes before index in string representations.""" return True @property def different_indices_commute(self): """Whether factors acting on different indices commute.""" return True def renormalize(self): """Fix the trace norm of an operator to 1""" norm = self.induced_norm(2) if numpy.isclose(norm, 0.0): raise ZeroDivisionError('Cannot renormalize empty or zero operator') else: self /= norm def _simplify(self, term, coefficient=1.0): """Simplify a term using commutator and anti-commutator relations.""" if not term: return coefficient, term term = sorted(term, key=lambda factor: factor[0]) new_term = [] left_factor = term[0] for right_factor in term[1:]: left_index, left_action = left_factor right_index, right_action = right_factor # Still on the same qubit, keep simplifying. if left_index == right_index: new_coefficient, new_action = _PAULI_OPERATOR_PRODUCTS[ left_action, right_action] left_factor = (left_index, new_action) coefficient *= new_coefficient # Reached different qubit, save result and re-initialize. else: if left_action != 'I': new_term.append(left_factor) left_factor = right_factor # Save result of final iteration. if left_factor[1] != 'I': new_term.append(left_factor) return coefficient, tuple(new_term) def _clifford_simplify_h(self, qubit): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 for left, right in term: if left == qubit: coeff, new_pauli = _clifford_h_products[right] new_term.append(tuple((left, new_pauli))) else: new_term.append(tuple((left,right))) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self def _clifford_simplify_s(self, qubit): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 for left, right in term: if left == qubit: coeff, new_pauli = _clifford_s_products[right] new_term.append(tuple((left, new_pauli))) else: new_term.append(tuple((left,right))) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self def _clifford_simplify_s_dag(self, qubit): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 for left, right in term: if left == qubit: coeff, new_pauli = _clifford_s_dag_products[right] new_term.append(tuple((left, new_pauli))) else: new_term.append(tuple((left,right))) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self def _clifford_simplify_control_g(self, axis, control_q, target_q): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 target = "I" control = "I" for left, right in term: if left == control_q: control = right elif left == target_q: target = right else: new_term.append(tuple((left,right))) new_c = "I" new_t = "I" if not (target == "I" and control == "I"): if axis == "X": coeff, new_c, new_t = _clifford_cx_products[control, target] if axis == "Y": coeff, new_c, new_t = _clifford_cy_products[control, target] if axis == "Z": coeff, new_c, new_t = _clifford_cz_products[control, target] if new_c != "I": new_term.append(tuple((control_q, new_c))) if new_t != "I": new_term.append(tuple((target_q, new_t))) new_term = sorted(new_term, key=lambda factor: factor[0]) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self if __name__ == "__main__": """geometry = get_geometry("H2", 0.714) print(geometry) basis_set = 'sto-3g' ref_anz, uccsd_anz, ham = generate_ucc_ansatz(geometry, basis_set) print(ham) b_ham = tq.grouping.binary_rep.BinaryHamiltonian.init_from_qubit_hamiltonian(ham) c_ham = tq.grouping.binary_rep.BinaryHamiltonian.init_from_qubit_hamiltonian(ham) print(b_ham) print(b_ham.get_binary()) print(b_ham.get_coeff()) param = uccsd_anz.extract_variables() print(param) for term in b_ham.binary_terms: print(term.coeff) term.set_coeff(param[0]) print(term.coeff) print(b_ham.get_coeff()) d_ham = c_ham.to_qubit_hamiltonian() + b_ham.to_qubit_hamiltonian() """ term = [(2,'X'), (0,'Y'), (3, 'Z')] coeff = tq.Variable("a") coeff = coeff *2.j print(coeff) print(type(coeff)) print(coeff({"a":1})) ham = ParamQubitHamiltonian(term= term, coefficient=coeff) print(ham.terms) print(str(ham)) for term in ham.terms: print(ham.terms[term]({"a":1,"b":2})) term = [(2,'X'), (0,'Z'), (3, 'Z')] coeff = tq.Variable("b") print(coeff({"b":1})) b_ham = ParamQubitHamiltonian(term= term, coefficient=coeff) print(b_ham.terms) print(str(b_ham)) for term in b_ham.terms: print(b_ham.terms[term]({"a":1,"b":2})) coeff = tq.Variable("a")*tq.Variable("b") print(coeff) print(coeff({"a":1,"b":2})) ham *= b_ham print(ham.terms) print(str(ham)) for term in ham.terms: coeff = (ham.terms[term]) print(coeff) print(coeff({"a":1,"b":2})) ham = ham*2. print(ham.terms) print(str(ham))
9,918
29.614198
85
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.6/HEA.py
import tequila as tq import numpy as np from tequila import gates as tq_g from tequila.objective.objective import Variable def generate_HEA(num_qubits, circuit_id=11, num_layers=1): """ This function generates different types of hardware efficient circuits as in this paper https://onlinelibrary.wiley.com/doi/full/10.1002/qute.201900070 param: num_qubits (int) -> the number of qubits in the circuit param: circuit_id (int) -> the type of hardware efficient circuit param: num_layers (int) -> the number of layers of the HEA input: num_qubits -> 4 circuit_id -> 11 num_layers -> 1 returns: ansatz (tq.QCircuit()) -> a circuit as shown below 0: ───Ry(0.318309886183791*pi*f((y0,))_0)───Rz(0.318309886183791*pi*f((z0,))_1)───@───────────────────────────────────────────────────────────────────────────────────── │ 1: ───Ry(0.318309886183791*pi*f((y1,))_2)───Rz(0.318309886183791*pi*f((z1,))_3)───X───Ry(0.318309886183791*pi*f((y4,))_8)────Rz(0.318309886183791*pi*f((z4,))_9)────@─── │ 2: ───Ry(0.318309886183791*pi*f((y2,))_4)───Rz(0.318309886183791*pi*f((z2,))_5)───@───Ry(0.318309886183791*pi*f((y5,))_10)───Rz(0.318309886183791*pi*f((z5,))_11)───X─── │ 3: ───Ry(0.318309886183791*pi*f((y3,))_6)───Rz(0.318309886183791*pi*f((z3,))_7)───X───────────────────────────────────────────────────────────────────────────────────── """ circuit = tq.QCircuit() qubits = [i for i in range(num_qubits)] if circuit_id == 1: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 2: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.CNOT(target=qubit, control=qubits[ind]) return circuit elif circuit_id == 3: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=qubit, control=qubits[ind]) count += 1 return circuit elif circuit_id == 4: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=qubit, control=qubits[ind]) count += 1 return circuit elif circuit_id == 5: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): for target in qubits: if control != target: variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=target, control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 6: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=qubits[ind+1], control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=qubits[ind+1], control=control) count += 1 return circuit elif circuit_id == 7: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): for target in qubits: if control != target: variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=target, control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 8: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=qubits[ind+1], control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=qubits[ind+1], control=control) count += 1 return circuit elif circuit_id == 9: count = 0 for _ in range(num_layers): for qubit in qubits: circuit += tq_g.H(qubit) for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.Z(target=qubit, control=qubits[ind]) for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 10: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.Z(target=qubit, control=qubits[ind]) circuit += tq_g.Z(target=qubits[0], control=qubits[-1]) for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 11: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: circuit += tq_g.X(target=qubits[ind+1], control=control) for ind, qubit in enumerate(qubits[1:-1]): variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: circuit += tq_g.X(target=qubits[ind+1], control=control) return circuit elif circuit_id == 12: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: circuit += tq_g.Z(target=qubits[ind+1], control=control) for ind, control in enumerate(qubits[1:-1]): variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = control) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = control) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: circuit += tq_g.Z(target=qubits[ind+1], control=control) return circuit elif circuit_id == 13: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubit, control=qubits[ind]) count += 1 variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubits[0], control=qubits[-1]) count += 1 for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=qubit, target=qubits[ind]) count += 1 variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=qubits[0], target=qubits[-1]) count += 1 return circuit elif circuit_id == 14: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubit, control=qubits[ind]) count += 1 variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubits[0], control=qubits[-1]) count += 1 for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=qubit, target=qubits[ind]) count += 1 variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=qubits[0], target=qubits[-1]) count += 1 return circuit elif circuit_id == 15: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.X(target=qubit, control=qubits[ind]) circuit += tq_g.X(control=qubits[-1], target=qubits[0]) for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.X(control=qubit, target=qubits[ind]) circuit += tq_g.X(target=qubits[-1], control=qubits[0]) return circuit elif circuit_id == 16: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=control, target=qubits[ind+1]) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=control, target=qubits[ind+1]) count += 1 return circuit elif circuit_id == 17: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=control, target=qubits[ind+1]) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=control, target=qubits[ind+1]) count += 1 return circuit elif circuit_id == 18: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[:-1]): variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubit, control=qubits[ind+1]) count += 1 variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubits[-1], control=qubits[0]) count += 1 return circuit elif circuit_id == 19: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[:-1]): variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubit, control=qubits[ind+1]) count += 1 variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubits[-1], control=qubits[0]) count += 1 return circuit
18,425
45.530303
172
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.6/grad_hacked.py
from tequila.circuit.compiler import CircuitCompiler from tequila.objective.objective import Objective, ExpectationValueImpl, Variable, \ assign_variable, identity, FixedVariable from tequila import TequilaException from tequila.objective import QTensor from tequila.simulators.simulator_api import compile import typing from numpy import vectorize from tequila.autograd_imports import jax, __AUTOGRAD__BACKEND__ def grad(objective: typing.Union[Objective, QTensor], variable: Variable = None, no_compile=False, *args, **kwargs): ''' wrapper function for getting the gradients of Objectives,ExpectationValues, Unitaries (including single gates), and Transforms. :param obj (QCircuit,ParametrizedGateImpl,Objective,ExpectationValue,Transform,Variable): structure to be differentiated :param variables (list of Variable): parameter with respect to which obj should be differentiated. default None: total gradient. return: dictionary of Objectives, if called on gate, circuit, exp.value, or objective; if Variable or Transform, returns number. ''' if variable is None: # None means that all components are created variables = objective.extract_variables() result = {} if len(variables) == 0: raise TequilaException("Error in gradient: Objective has no variables") for k in variables: assert (k is not None) result[k] = grad(objective, k, no_compile=no_compile) return result else: variable = assign_variable(variable) if isinstance(objective, QTensor): f = lambda x: grad(objective=x, variable=variable, *args, **kwargs) ff = vectorize(f) return ff(objective) if variable not in objective.extract_variables(): return Objective() if no_compile: compiled = objective else: compiler = CircuitCompiler(multitarget=True, trotterized=True, hadamard_power=True, power=True, controlled_phase=True, controlled_rotation=True, gradient_mode=True) compiled = compiler(objective, variables=[variable]) if variable not in compiled.extract_variables(): raise TequilaException("Error in taking gradient. Objective does not depend on variable {} ".format(variable)) if isinstance(objective, ExpectationValueImpl): return __grad_expectationvalue(E=objective, variable=variable) elif objective.is_expectationvalue(): return __grad_expectationvalue(E=compiled.args[-1], variable=variable) elif isinstance(compiled, Objective) or (hasattr(compiled, "args") and hasattr(compiled, "transformation")): return __grad_objective(objective=compiled, variable=variable) else: raise TequilaException("Gradient not implemented for other types than ExpectationValue and Objective.") def __grad_objective(objective: Objective, variable: Variable): args = objective.args transformation = objective.transformation dO = None processed_expectationvalues = {} for i, arg in enumerate(args): if __AUTOGRAD__BACKEND__ == "jax": df = jax.grad(transformation, argnums=i, holomorphic=True) elif __AUTOGRAD__BACKEND__ == "autograd": df = jax.grad(transformation, argnum=i) else: raise TequilaException("Can't differentiate without autograd or jax") # We can detect one simple case where the outer derivative is const=1 if transformation is None or transformation == identity: outer = 1.0 else: outer = Objective(args=args, transformation=df) if hasattr(arg, "U"): # save redundancies if arg in processed_expectationvalues: inner = processed_expectationvalues[arg] else: inner = __grad_inner(arg=arg, variable=variable) processed_expectationvalues[arg] = inner else: # this means this inner derivative is purely variable dependent inner = __grad_inner(arg=arg, variable=variable) if inner == 0.0: # don't pile up zero expectationvalues continue if dO is None: dO = outer * inner else: dO = dO + outer * inner if dO is None: raise TequilaException("caught None in __grad_objective") return dO # def __grad_vector_objective(objective: Objective, variable: Variable): # argsets = objective.argsets # transformations = objective._transformations # outputs = [] # for pos in range(len(objective)): # args = argsets[pos] # transformation = transformations[pos] # dO = None # # processed_expectationvalues = {} # for i, arg in enumerate(args): # if __AUTOGRAD__BACKEND__ == "jax": # df = jax.grad(transformation, argnums=i) # elif __AUTOGRAD__BACKEND__ == "autograd": # df = jax.grad(transformation, argnum=i) # else: # raise TequilaException("Can't differentiate without autograd or jax") # # # We can detect one simple case where the outer derivative is const=1 # if transformation is None or transformation == identity: # outer = 1.0 # else: # outer = Objective(args=args, transformation=df) # # if hasattr(arg, "U"): # # save redundancies # if arg in processed_expectationvalues: # inner = processed_expectationvalues[arg] # else: # inner = __grad_inner(arg=arg, variable=variable) # processed_expectationvalues[arg] = inner # else: # # this means this inner derivative is purely variable dependent # inner = __grad_inner(arg=arg, variable=variable) # # if inner == 0.0: # # don't pile up zero expectationvalues # continue # # if dO is None: # dO = outer * inner # else: # dO = dO + outer * inner # # if dO is None: # dO = Objective() # outputs.append(dO) # if len(outputs) == 1: # return outputs[0] # return outputs def __grad_inner(arg, variable): ''' a modified loop over __grad_objective, which gets derivatives all the way down to variables, return 1 or 0 when a variable is (isnt) identical to var. :param arg: a transform or variable object, to be differentiated :param variable: the Variable with respect to which par should be differentiated. :ivar var: the string representation of variable ''' assert (isinstance(variable, Variable)) if isinstance(arg, Variable): if arg == variable: return 1.0 else: return 0.0 elif isinstance(arg, FixedVariable): return 0.0 elif isinstance(arg, ExpectationValueImpl): return __grad_expectationvalue(arg, variable=variable) elif hasattr(arg, "abstract_expectationvalue"): E = arg.abstract_expectationvalue dE = __grad_expectationvalue(E, variable=variable) return compile(dE, **arg._input_args) else: return __grad_objective(objective=arg, variable=variable) def __grad_expectationvalue(E: ExpectationValueImpl, variable: Variable): ''' implements the analytic partial derivative of a unitary as it would appear in an expectation value. See the paper. :param unitary: the unitary whose gradient should be obtained :param variables (list, dict, str): the variables with respect to which differentiation should be performed. :return: vector (as dict) of dU/dpi as Objective (without hamiltonian) ''' hamiltonian = E.H unitary = E.U if not (unitary.verify()): raise TequilaException("error in grad_expectationvalue unitary is {}".format(unitary)) # fast return if possible if variable not in unitary.extract_variables(): return 0.0 param_gates = unitary._parameter_map[variable] dO = Objective() for idx_g in param_gates: idx, g = idx_g dOinc = __grad_shift_rule(unitary, g, idx, variable, hamiltonian) dO += dOinc assert dO is not None return dO def __grad_shift_rule(unitary, g, i, variable, hamiltonian): ''' function for getting the gradients of directly differentiable gates. Expects precompiled circuits. :param unitary: QCircuit: the QCircuit object containing the gate to be differentiated :param g: a parametrized: the gate being differentiated :param i: Int: the position in unitary at which g appears :param variable: Variable or String: the variable with respect to which gate g is being differentiated :param hamiltonian: the hamiltonian with respect to which unitary is to be measured, in the case that unitary is contained within an ExpectationValue :return: an Objective, whose calculation yields the gradient of g w.r.t variable ''' # possibility for overwride in custom gate construction if hasattr(g, "shifted_gates"): inner_grad = __grad_inner(g.parameter, variable) shifted = g.shifted_gates() dOinc = Objective() for x in shifted: w, g = x Ux = unitary.replace_gates(positions=[i], circuits=[g]) wx = w * inner_grad Ex = Objective.ExpectationValue(U=Ux, H=hamiltonian) dOinc += wx * Ex return dOinc else: raise TequilaException('No shift found for gate {}\nWas the compiler called?'.format(g))
9,886
38.548
132
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.6/vqe_utils.py
import tequila as tq import numpy as np from hacked_openfermion_qubit_operator import ParamQubitHamiltonian from openfermion import QubitOperator from HEA import * def get_ansatz_circuit(ansatz_type, geometry, basis_set=None, trotter_steps = 1, name=None, circuit_id=None,num_layers=1): """ This function generates the ansatz for the molecule and the Hamiltonian param: ansatz_type (str) -> the type of the ansatz ('UCCSD, UpCCGSD, SPA, HEA') param: geometry (str) -> the geometry of the molecule param: basis_set (str) -> the basis set for wchich the ansatz has to generated param: trotter_steps (int) -> the number of trotter step to be used in the trotter decomposition param: name (str) -> the name for the madness molecule param: circuit_id (int) -> the type of hardware efficient ansatz param: num_layers (int) -> the number of layers of the HEA e.g.: input: ansatz_type -> "UCCSD" geometry -> "H 0.0 0.0 0.0\nH 0.0 0.0 0.714" basis_set -> 'sto-3g' trotter_steps -> 1 name -> None circuit_id -> None num_layers -> 1 returns: ucc_ansatz (tq.QCircuit()) -> a circuit printed below: circuit: FermionicExcitation(target=(0, 1, 2, 3), control=(), parameter=Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = []) FermionicExcitation(target=(0, 1, 2, 3), control=(), parameter=Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = []) Hamiltonian (tq.QubitHamiltonian()) -> -0.0621+0.1755Z(0)+0.1755Z(1)-0.2358Z(2)-0.2358Z(3)+0.1699Z(0)Z(1) +0.0449Y(0)X(1)X(2)Y(3)-0.0449Y(0)Y(1)X(2)X(3)-0.0449X(0)X(1)Y(2)Y(3) +0.0449X(0)Y(1)Y(2)X(3)+0.1221Z(0)Z(2)+0.1671Z(0)Z(3)+0.1671Z(1)Z(2) +0.1221Z(1)Z(3)+0.1756Z(2)Z(3) fci_ener (float) -> """ ham = tq.QubitHamiltonian() fci_ener = 0.0 ansatz = tq.QCircuit() if ansatz_type == "UCCSD": molecule = tq.Molecule(geometry=geometry, basis_set=basis_set) ansatz = molecule.make_uccsd_ansatz(trotter_steps) ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy(method="fci") elif ansatz_type == "UCCS": molecule = tq.Molecule(geometry=geometry, basis_set=basis_set, backend='psi4') ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy("fci") indices = molecule.make_upccgsd_indices(key='UCCS') print("indices are:", indices) ansatz = molecule.make_upccgsd_layer(indices=indices, include_singles=True, include_doubles=False) elif ansatz_type == "UpCCGSD": molecule = tq.Molecule(name=name, geometry=geometry, n_pno=None) ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy("fci") ansatz = molecule.make_upccgsd_ansatz() elif ansatz_type == "SPA": molecule = tq.Molecule(name=name, geometry=geometry, n_pno=None) ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy("fci") ansatz = molecule.make_upccgsd_ansatz(name="SPA") elif ansatz_type == "HEA": molecule = tq.Molecule(geometry=geometry, basis_set=basis_set) ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy(method="fci") ansatz = generate_HEA(molecule.n_orbitals * 2, circuit_id) else: raise Exception("not implemented any other ansatz, please choose from 'UCCSD, UpCCGSD, SPA, HEA'") return ansatz, ham, fci_ener def get_generator_for_gates(unitary): """ This function takes a unitary gate and returns the generator of the the gate so that it can be padded to the Hamiltonian param: unitary (tq.QGateImpl()) -> the unitary circuit element that has to be converted to a paulistring e.g.: input: unitary -> a FermionicGateImpl object as the one printed below FermionicExcitation(target=(0, 1, 2, 3), control=(), parameter=Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = []) returns: parameter (tq.Variable()) -> (1, 0, 1, 0) generator (tq.QubitHamiltonian()) -> -0.1250Y(0)Y(1)Y(2)X(3)+0.1250Y(0)X(1)Y(2)Y(3) +0.1250X(0)X(1)Y(2)X(3)+0.1250X(0)Y(1)Y(2)Y(3) -0.1250Y(0)X(1)X(2)X(3)-0.1250Y(0)Y(1)X(2)Y(3) -0.1250X(0)Y(1)X(2)X(3)+0.1250X(0)X(1)X(2)Y(3) null_proj (tq.QubitHamiltonian()) -> -0.1250Z(0)Z(1)+0.1250Z(1)Z(3)+0.1250Z(0)Z(3) +0.1250Z(1)Z(2)+0.1250Z(0)Z(2)-0.1250Z(2)Z(3) -0.1250Z(0)Z(1)Z(2)Z(3) """ try: parameter = None generator = None null_proj = None if isinstance(unitary, tq.quantumchemistry.qc_base.FermionicGateImpl): parameter = unitary.extract_variables() generator = unitary.generator null_proj = unitary.p0 else: #getting parameter if unitary.is_parametrized(): parameter = unitary.extract_variables() else: parameter = [None] try: generator = unitary.make_generator(include_controls=True) except: generator = unitary.generator() """if len(parameter) == 0: parameter = [tq.objective.objective.assign_variable(unitary.parameter)]""" return parameter[0], generator, null_proj except Exception as e: print("An Exception happened, details :",e) pass def fold_unitary_into_hamiltonian(unitary, Hamiltonian): """ This function return a list of the resulting Hamiltonian terms after folding the paulistring correspondig to the unitary into the Hamiltonian param: unitary (tq.QGateImpl()) -> the unitary to be folded into the Hamiltonian param: Hamiltonian (ParamQubitHamiltonian()) -> the Hamiltonian of the system e.g.: input: unitary -> a FermionicGateImpl object as the one printed below FermionicExcitation(target=(0, 1, 2, 3), control=(), parameter=Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = []) Hamiltonian -> -0.06214952615456104 [] + -0.044941923860490916 [X0 X1 Y2 Y3] + 0.044941923860490916 [X0 Y1 Y2 X3] + 0.044941923860490916 [Y0 X1 X2 Y3] + -0.044941923860490916 [Y0 Y1 X2 X3] + 0.17547360045040505 [Z0] + 0.16992958569230643 [Z0 Z1] + 0.12212314332112947 [Z0 Z2] + 0.1670650671816204 [Z0 Z3] + 0.17547360045040508 [Z1] + 0.1670650671816204 [Z1 Z2] + 0.12212314332112947 [Z1 Z3] + -0.23578915712819945 [Z2] + 0.17561918557144712 [Z2 Z3] + -0.23578915712819945 [Z3] returns: folded_hamiltonian (ParamQubitHamiltonian()) -> Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [X0 X1 X2 X3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [X0 X1 Y2 Y3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [X0 Y1 X2 Y3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [X0 Y1 Y2 X3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Y0 X1 X2 Y3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Y0 X1 Y2 X3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Y0 Y1 X2 X3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Y0 Y1 Y2 Y3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z1] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z1 Z2] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z1 Z2 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z1 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z2] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z2 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z1] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z1 Z2] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z1 Z2 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z1 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z2] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z2 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z3] """ folded_hamiltonian = ParamQubitHamiltonian() if isinstance(unitary, tq.circuit._gates_impl.DifferentiableGateImpl) and not isinstance(unitary, tq.circuit._gates_impl.PhaseGateImpl): variable, generator, null_proj = get_generator_for_gates(unitary) # print(generator) # print(null_proj) #converting into ParamQubitHamiltonian() c_generator = convert_tq_QH_to_PQH(generator) """c_null_proj = convert_tq_QH_to_PQH(null_proj) print(variable) prod1 = (null_proj*ham*generator - generator*ham*null_proj) print(prod1) #print((Hamiltonian*c_generator)) prod2 = convert_PQH_to_tq_QH(c_null_proj*Hamiltonian*c_generator - c_generator*Hamiltonian*c_null_proj)({var:0.1 for var in variable.extract_variables()}) print(prod2) assert prod1 ==prod2 raise Exception("testing")""" #print("starting", flush=True) #handling the parameterize gates if variable is not None: #print("folding generator") # adding the term: cos^2(\theta)*H temp_ham = ParamQubitHamiltonian().identity() temp_ham *= Hamiltonian temp_ham *= (variable.apply(tq.numpy.cos)**2) #print(convert_PQH_to_tq_QH(temp_ham)({var:1. for var in variable.extract_variables()})) folded_hamiltonian += temp_ham #print("step1 done", flush=True) # adding the term: sin^2(\theta)*G*H*G temp_ham = ParamQubitHamiltonian().identity() temp_ham *= c_generator temp_ham *= Hamiltonian temp_ham *= c_generator temp_ham *= (variable.apply(tq.numpy.sin)**2) #print(convert_PQH_to_tq_QH(temp_ham)({var:1. for var in variable.extract_variables()})) folded_hamiltonian += temp_ham #print("step2 done", flush=True) # adding the term: i*cos^2(\theta)8sin^2(\theta)*(G*H -H*G) temp_ham1 = ParamQubitHamiltonian().identity() temp_ham1 *= c_generator temp_ham1 *= Hamiltonian temp_ham2 = ParamQubitHamiltonian().identity() temp_ham2 *= Hamiltonian temp_ham2 *= c_generator temp_ham = temp_ham1 - temp_ham2 temp_ham *= 1.0j temp_ham *= variable.apply(tq.numpy.sin) * variable.apply(tq.numpy.cos) #print(convert_PQH_to_tq_QH(temp_ham)({var:1. for var in variable.extract_variables()})) folded_hamiltonian += temp_ham #print("step3 done", flush=True) #handling the non-paramterized gates else: raise Exception("This function is not implemented yet") # adding the term: G*H*G folded_hamiltonian += c_generator*Hamiltonian*c_generator #print("Halfway there", flush=True) #handle the FermionicGateImpl gates if null_proj is not None: print("folding null projector") c_null_proj = convert_tq_QH_to_PQH(null_proj) #print("step4 done", flush=True) # adding the term: (1-cos(\theta))^2*P0*H*P0 temp_ham = ParamQubitHamiltonian().identity() temp_ham *= c_null_proj temp_ham *= Hamiltonian temp_ham *= c_null_proj temp_ham *= ((1-variable.apply(tq.numpy.cos))**2) folded_hamiltonian += temp_ham #print("step5 done", flush=True) # adding the term: 2*cos(\theta)*(1-cos(\theta))*(P0*H +H*P0) temp_ham1 = ParamQubitHamiltonian().identity() temp_ham1 *= c_null_proj temp_ham1 *= Hamiltonian temp_ham2 = ParamQubitHamiltonian().identity() temp_ham2 *= Hamiltonian temp_ham2 *= c_null_proj temp_ham = temp_ham1 + temp_ham2 temp_ham *= (variable.apply(tq.numpy.cos)*(1-variable.apply(tq.numpy.cos))) folded_hamiltonian += temp_ham #print("step6 done", flush=True) # adding the term: i*sin(\theta)*(1-cos(\theta))*(G*H*P0 - P0*H*G) temp_ham1 = ParamQubitHamiltonian().identity() temp_ham1 *= c_generator temp_ham1 *= Hamiltonian temp_ham1 *= c_null_proj temp_ham2 = ParamQubitHamiltonian().identity() temp_ham2 *= c_null_proj temp_ham2 *= Hamiltonian temp_ham2 *= c_generator temp_ham = temp_ham1 - temp_ham2 temp_ham *= 1.0j temp_ham *= (variable.apply(tq.numpy.sin)*(1-variable.apply(tq.numpy.cos))) folded_hamiltonian += temp_ham #print("step7 done", flush=True) elif isinstance(unitary, tq.circuit._gates_impl.PhaseGateImpl): if np.isclose(unitary.parameter, np.pi/2.0): return Hamiltonian._clifford_simplify_s(unitary.qubits[0]) elif np.isclose(unitary.parameter, -1.*np.pi/2.0): return Hamiltonian._clifford_simplify_s_dag(unitary.qubits[0]) else: raise Exception("Only DifferentiableGateImpl, PhaseGateImpl(S), Pauligate(X,Y,Z), Controlled(X,Y,Z) and Hadamrd(H) implemented yet") elif isinstance(unitary, tq.circuit._gates_impl.QGateImpl): if unitary.is_controlled(): if unitary.name == "X": return Hamiltonian._clifford_simplify_control_g("X", unitary.control[0], unitary.target[0]) elif unitary.name == "Y": return Hamiltonian._clifford_simplify_control_g("Y", unitary.control[0], unitary.target[0]) elif unitary.name == "Z": return Hamiltonian._clifford_simplify_control_g("Z", unitary.control[0], unitary.target[0]) else: raise Exception("Only DifferentiableGateImpl, PhaseGateImpl(S), Pauligate(X,Y,Z), Controlled(X,Y,Z) and Hadamrd(H) implemented yet") else: if unitary.name == "X": gate = convert_tq_QH_to_PQH(tq.paulis.X(unitary.qubits[0])) return gate*Hamiltonian*gate elif unitary.name == "Y": gate = convert_tq_QH_to_PQH(tq.paulis.Y(unitary.qubits[0])) return gate*Hamiltonian*gate elif unitary.name == "Z": gate = convert_tq_QH_to_PQH(tq.paulis.Z(unitary.qubits[0])) return gate*Hamiltonian*gate elif unitary.name == "H": return Hamiltonian._clifford_simplify_h(unitary.qubits[0]) else: raise Exception("Only DifferentiableGateImpl, PhaseGateImpl(S), Pauligate(X,Y,Z), Controlled(X,Y,Z) and Hadamrd(H) implemented yet") else: raise Exception("Only DifferentiableGateImpl, PhaseGateImpl(S), Pauligate(X,Y,Z), Controlled(X,Y,Z) and Hadamrd(H) implemented yet") return folded_hamiltonian def convert_tq_QH_to_PQH(Hamiltonian): """ This function takes the tequila QubitHamiltonian object and converts into a ParamQubitHamiltonian object. param: Hamiltonian (tq.QubitHamiltonian()) -> the Hamiltonian to be converted e.g: input: Hamiltonian -> -0.0621+0.1755Z(0)+0.1755Z(1)-0.2358Z(2)-0.2358Z(3)+0.1699Z(0)Z(1) +0.0449Y(0)X(1)X(2)Y(3)-0.0449Y(0)Y(1)X(2)X(3)-0.0449X(0)X(1)Y(2)Y(3) +0.0449X(0)Y(1)Y(2)X(3)+0.1221Z(0)Z(2)+0.1671Z(0)Z(3)+0.1671Z(1)Z(2) +0.1221Z(1)Z(3)+0.1756Z(2)Z(3) returns: param_hamiltonian (ParamQubitHamiltonian()) -> -0.06214952615456104 [] + -0.044941923860490916 [X0 X1 Y2 Y3] + 0.044941923860490916 [X0 Y1 Y2 X3] + 0.044941923860490916 [Y0 X1 X2 Y3] + -0.044941923860490916 [Y0 Y1 X2 X3] + 0.17547360045040505 [Z0] + 0.16992958569230643 [Z0 Z1] + 0.12212314332112947 [Z0 Z2] + 0.1670650671816204 [Z0 Z3] + 0.17547360045040508 [Z1] + 0.1670650671816204 [Z1 Z2] + 0.12212314332112947 [Z1 Z3] + -0.23578915712819945 [Z2] + 0.17561918557144712 [Z2 Z3] + -0.23578915712819945 [Z3] """ param_hamiltonian = ParamQubitHamiltonian() Hamiltonian = Hamiltonian.to_openfermion() for term in Hamiltonian.terms: param_hamiltonian += ParamQubitHamiltonian(term = term, coefficient = Hamiltonian.terms[term]) return param_hamiltonian class convert_PQH_to_tq_QH: def __init__(self, Hamiltonian): self.param_hamiltonian = Hamiltonian def __call__(self,variables=None): """ This function takes the ParamQubitHamiltonian object and converts into a tequila QubitHamiltonian object. param: param_hamiltonian (ParamQubitHamiltonian()) -> the Hamiltonian to be converted param: variables (dict) -> a dictionary with the values of the variables in the Hamiltonian coefficient e.g: input: param_hamiltonian -> a [Y0 X2 Z3] + b [Z0 X2 Z3] variables -> {"a":1,"b":2} returns: Hamiltonian (tq.QubitHamiltonian()) -> +1.0000Y(0)X(2)Z(3)+2.0000Z(0)X(2)Z(3) """ Hamiltonian = tq.QubitHamiltonian() for term in self.param_hamiltonian.terms: val = self.param_hamiltonian.terms[term]# + self.param_hamiltonian.imag_terms[term]*1.0j if isinstance(val, tq.Variable) or isinstance(val, tq.objective.objective.Objective): try: for key in variables.keys(): variables[key] = variables[key] #print(variables) val = val(variables) #print(val) except Exception as e: print(e) raise Exception("You forgot to pass the dictionary with the values of the variables") Hamiltonian += tq.QubitHamiltonian(QubitOperator(term=term, coefficient=val)) return Hamiltonian def _construct_derivatives(self, variables=None): """ """ derivatives = {} variable_names = [] for term in self.param_hamiltonian.terms: val = self.param_hamiltonian.terms[term]# + self.param_hamiltonian.imag_terms[term]*1.0j #print(val) if isinstance(val, tq.Variable) or isinstance(val, tq.objective.objective.Objective): variable = val.extract_variables() for var in list(variable): from grad_hacked import grad derivative = ParamQubitHamiltonian(term = term, coefficient = grad(val, var)) if var not in variable_names: variable_names.append(var) if var not in list(derivatives.keys()): derivatives[var] = derivative else: derivatives[var] += derivative return variable_names, derivatives def get_geometry(name, b_l): """ This is utility fucntion that generates tehe geometry string of a Molecule param: name (str) -> name of the molecule param: b_l (float) -> the bond length of the molecule e.g.: input: name -> "H2" b_l -> 0.714 returns: geo_str (str) -> "H 0.0 0.0 0.0\nH 0.0 0.0 0.714" """ geo_str = None if name == "LiH": geo_str = "H 0.0 0.0 0.0\nLi 0.0 0.0 {0}".format(b_l) elif name == "H2": geo_str = "H 0.0 0.0 0.0\nH 0.0 0.0 {0}".format(b_l) elif name == "BeH2": geo_str = "H 0.0 0.0 {0}\nH 0.0 0.0 {1}\nBe 0.0 0.0 0.0".format(b_l,-1*b_l) elif name == "N2": geo_str = "N 0.0 0.0 0.0\nN 0.0 0.0 {0}".format(b_l) elif name == "H4": geo_str = "H 0.0 0.0 0.0\nH 0.0 0.0 {0}\nH 0.0 0.0 {1}\nH 0.0 0.0 {2}".format(b_l,-1*b_l,2*b_l) return geo_str
27,934
51.807183
162
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.6/hacked_openfermion_symbolic_operator.py
import abc import copy import itertools import re import warnings import sympy import tequila as tq from tequila.objective.objective import Objective, Variable from openfermion.config import EQ_TOLERANCE COEFFICIENT_TYPES = (int, float, complex, sympy.Expr, Variable, Objective) class SymbolicOperator(metaclass=abc.ABCMeta): """Base class for FermionOperator and QubitOperator. A SymbolicOperator stores an object which represents a weighted sum of terms; each term is a product of individual factors of the form (`index`, `action`), where `index` is a nonnegative integer and the possible values for `action` are determined by the subclass. For instance, for the subclass FermionOperator, `action` can be 1 or 0, indicating raising or lowering, and for QubitOperator, `action` is from the set {'X', 'Y', 'Z'}. The coefficients of the terms are stored in a dictionary whose keys are the terms. SymbolicOperators of the same type can be added or multiplied together. Note: Adding SymbolicOperators is faster using += (as this is done by in-place addition). Specifying the coefficient during initialization is faster than multiplying a SymbolicOperator with a scalar. Attributes: actions (tuple): A tuple of objects representing the possible actions. e.g. for FermionOperator, this is (1, 0). action_strings (tuple): A tuple of string representations of actions. These should be in one-to-one correspondence with actions and listed in the same order. e.g. for FermionOperator, this is ('^', ''). action_before_index (bool): A boolean indicating whether in string representations, the action should come before the index. different_indices_commute (bool): A boolean indicating whether factors acting on different indices commute. terms (dict): **key** (tuple of tuples): A dictionary storing the coefficients of the terms in the operator. The keys are the terms. A term is a product of individual factors; each factor is represented by a tuple of the form (`index`, `action`), and these tuples are collected into a larger tuple which represents the term as the product of its factors. """ @staticmethod def _issmall(val, tol=EQ_TOLERANCE): '''Checks whether a value is near-zero Parses the allowed coefficients above for near-zero tests. Args: val (COEFFICIENT_TYPES) -- the value to be tested tol (float) -- tolerance for inequality ''' if isinstance(val, sympy.Expr): if sympy.simplify(abs(val) < tol) == True: return True return False if isinstance(val, tq.Variable) or isinstance(val, tq.objective.objective.Objective): return False if abs(val) < tol: return True return False @abc.abstractproperty def actions(self): """The allowed actions. Returns a tuple of objects representing the possible actions. """ pass @abc.abstractproperty def action_strings(self): """The string representations of the allowed actions. Returns a tuple containing string representations of the possible actions, in the same order as the `actions` property. """ pass @abc.abstractproperty def action_before_index(self): """Whether action comes before index in string representations. Example: For QubitOperator, the actions are ('X', 'Y', 'Z') and the string representations look something like 'X0 Z2 Y3'. So the action comes before the index, and this function should return True. For FermionOperator, the string representations look like '0^ 1 2^ 3'. The action comes after the index, so this function should return False. """ pass @abc.abstractproperty def different_indices_commute(self): """Whether factors acting on different indices commute.""" pass __hash__ = None def __init__(self, term=None, coefficient=1.): if not isinstance(coefficient, COEFFICIENT_TYPES): raise ValueError('Coefficient must be a numeric type.') # Initialize the terms dictionary self.terms = {} # Detect if the input is the string representation of a sum of terms; # if so, initialization needs to be handled differently if isinstance(term, str) and '[' in term: self._long_string_init(term, coefficient) return # Zero operator: leave the terms dictionary empty if term is None: return # Parse the term # Sequence input if isinstance(term, (list, tuple)): term = self._parse_sequence(term) # String input elif isinstance(term, str): term = self._parse_string(term) # Invalid input type else: raise ValueError('term specified incorrectly.') # Simplify the term coefficient, term = self._simplify(term, coefficient=coefficient) # Add the term to the dictionary self.terms[term] = coefficient def _long_string_init(self, long_string, coefficient): r""" Initialization from a long string representation. e.g. For FermionOperator: '1.5 [2^ 3] + 1.4 [3^ 0]' """ pattern = r'(.*?)\[(.*?)\]' # regex for a term for match in re.findall(pattern, long_string, flags=re.DOTALL): # Determine the coefficient for this term coef_string = re.sub(r"\s+", "", match[0]) if coef_string and coef_string[0] == '+': coef_string = coef_string[1:].strip() if coef_string == '': coef = 1.0 elif coef_string == '-': coef = -1.0 else: try: if 'j' in coef_string: if coef_string[0] == '-': coef = -complex(coef_string[1:]) else: coef = complex(coef_string) else: coef = float(coef_string) except ValueError: raise ValueError( 'Invalid coefficient {}.'.format(coef_string)) coef *= coefficient # Parse the term, simpify it and add to the dict term = self._parse_string(match[1]) coef, term = self._simplify(term, coefficient=coef) if term not in self.terms: self.terms[term] = coef else: self.terms[term] += coef def _validate_factor(self, factor): """Check that a factor of a term is valid.""" if len(factor) != 2: raise ValueError('Invalid factor {}.'.format(factor)) index, action = factor if action not in self.actions: raise ValueError('Invalid action in factor {}. ' 'Valid actions are: {}'.format( factor, self.actions)) if not isinstance(index, int) or index < 0: raise ValueError('Invalid index in factor {}. ' 'The index should be a non-negative ' 'integer.'.format(factor)) def _simplify(self, term, coefficient=1.0): """Simplifies a term.""" if self.different_indices_commute: term = sorted(term, key=lambda factor: factor[0]) return coefficient, tuple(term) def _parse_sequence(self, term): """Parse a term given as a sequence type (i.e., list, tuple, etc.). e.g. For QubitOperator: [('X', 2), ('Y', 0), ('Z', 3)] -> (('Y', 0), ('X', 2), ('Z', 3)) """ if not term: # Empty sequence return () elif isinstance(term[0], int): # Single factor self._validate_factor(term) return (tuple(term),) else: # Check that all factors in the term are valid for factor in term: self._validate_factor(factor) # Return a tuple return tuple(term) def _parse_string(self, term): """Parse a term given as a string. e.g. For FermionOperator: "2^ 3" -> ((2, 1), (3, 0)) """ factors = term.split() # Convert the string representations of the factors to tuples processed_term = [] for factor in factors: # Get the index and action string if self.action_before_index: # The index is at the end of the string; find where it starts. if not factor[-1].isdigit(): raise ValueError('Invalid factor {}.'.format(factor)) index_start = len(factor) - 1 while index_start > 0 and factor[index_start - 1].isdigit(): index_start -= 1 if factor[index_start - 1] == '-': raise ValueError('Invalid index in factor {}. ' 'The index should be a non-negative ' 'integer.'.format(factor)) index = int(factor[index_start:]) action_string = factor[:index_start] else: # The index is at the beginning of the string; find where # it ends if factor[0] == '-': raise ValueError('Invalid index in factor {}. ' 'The index should be a non-negative ' 'integer.'.format(factor)) if not factor[0].isdigit(): raise ValueError('Invalid factor {}.'.format(factor)) index_end = 1 while (index_end <= len(factor) - 1 and factor[index_end].isdigit()): index_end += 1 index = int(factor[:index_end]) action_string = factor[index_end:] # Convert the action string to an action if action_string in self.action_strings: action = self.actions[self.action_strings.index(action_string)] else: raise ValueError('Invalid action in factor {}. ' 'Valid actions are: {}'.format( factor, self.action_strings)) # Add the factor to the list as a tuple processed_term.append((index, action)) # Return a tuple return tuple(processed_term) @property def constant(self): """The value of the constant term.""" return self.terms.get((), 0.0) @constant.setter def constant(self, value): self.terms[()] = value @classmethod def zero(cls): """ Returns: additive_identity (SymbolicOperator): A symbolic operator o with the property that o+x = x+o = x for all operators x of the same class. """ return cls(term=None) @classmethod def identity(cls): """ Returns: multiplicative_identity (SymbolicOperator): A symbolic operator u with the property that u*x = x*u = x for all operators x of the same class. """ return cls(term=()) def __str__(self): """Return an easy-to-read string representation.""" if not self.terms: return '0' string_rep = '' for term, coeff in sorted(self.terms.items()): if self._issmall(coeff): continue tmp_string = '{} ['.format(coeff) for factor in term: index, action = factor action_string = self.action_strings[self.actions.index(action)] if self.action_before_index: tmp_string += '{}{} '.format(action_string, index) else: tmp_string += '{}{} '.format(index, action_string) string_rep += '{}] +\n'.format(tmp_string.strip()) return string_rep[:-3] def __repr__(self): return str(self) def __imul__(self, multiplier): """In-place multiply (*=) with scalar or operator of the same type. Default implementation is to multiply coefficients and concatenate terms. Args: multiplier(complex float, or SymbolicOperator): multiplier Returns: product (SymbolicOperator): Mutated self. """ # Handle scalars. if isinstance(multiplier, COEFFICIENT_TYPES): for term in self.terms: self.terms[term] *= multiplier return self # Handle operator of the same type elif isinstance(multiplier, self.__class__): result_terms = dict() for left_term in self.terms: for right_term in multiplier.terms: left_coefficient = self.terms[left_term] right_coefficient = multiplier.terms[right_term] new_coefficient = left_coefficient * right_coefficient new_term = left_term + right_term new_coefficient, new_term = self._simplify( new_term, coefficient=new_coefficient) # Update result dict. if new_term in result_terms: result_terms[new_term] += new_coefficient else: result_terms[new_term] = new_coefficient self.terms = result_terms return self # Invalid multiplier type else: raise TypeError('Cannot multiply {} with {}'.format( self.__class__.__name__, multiplier.__class__.__name__)) def __mul__(self, multiplier): """Return self * multiplier for a scalar, or a SymbolicOperator. Args: multiplier: A scalar, or a SymbolicOperator. Returns: product (SymbolicOperator) Raises: TypeError: Invalid type cannot be multiply with SymbolicOperator. """ if isinstance(multiplier, COEFFICIENT_TYPES + (type(self),)): product = copy.deepcopy(self) product *= multiplier return product else: raise TypeError('Object of invalid type cannot multiply with ' + type(self) + '.') def __iadd__(self, addend): """In-place method for += addition of SymbolicOperator. Args: addend (SymbolicOperator, or scalar): The operator to add. If scalar, adds to the constant term Returns: sum (SymbolicOperator): Mutated self. Raises: TypeError: Cannot add invalid type. """ if isinstance(addend, type(self)): for term in addend.terms: self.terms[term] = (self.terms.get(term, 0.0) + addend.terms[term]) if self._issmall(self.terms[term]): del self.terms[term] elif isinstance(addend, COEFFICIENT_TYPES): self.constant += addend else: raise TypeError('Cannot add invalid type to {}.'.format(type(self))) return self def __add__(self, addend): """ Args: addend (SymbolicOperator): The operator to add. Returns: sum (SymbolicOperator) """ summand = copy.deepcopy(self) summand += addend return summand def __radd__(self, addend): """ Args: addend (SymbolicOperator): The operator to add. Returns: sum (SymbolicOperator) """ return self + addend def __isub__(self, subtrahend): """In-place method for -= subtraction of SymbolicOperator. Args: subtrahend (A SymbolicOperator, or scalar): The operator to subtract if scalar, subtracts from the constant term. Returns: difference (SymbolicOperator): Mutated self. Raises: TypeError: Cannot subtract invalid type. """ if isinstance(subtrahend, type(self)): for term in subtrahend.terms: self.terms[term] = (self.terms.get(term, 0.0) - subtrahend.terms[term]) if self._issmall(self.terms[term]): del self.terms[term] elif isinstance(subtrahend, COEFFICIENT_TYPES): self.constant -= subtrahend else: raise TypeError('Cannot subtract invalid type from {}.'.format( type(self))) return self def __sub__(self, subtrahend): """ Args: subtrahend (SymbolicOperator): The operator to subtract. Returns: difference (SymbolicOperator) """ minuend = copy.deepcopy(self) minuend -= subtrahend return minuend def __rsub__(self, subtrahend): """ Args: subtrahend (SymbolicOperator): The operator to subtract. Returns: difference (SymbolicOperator) """ return -1 * self + subtrahend def __rmul__(self, multiplier): """ Return multiplier * self for a scalar. We only define __rmul__ for scalars because the left multiply exist for SymbolicOperator and left multiply is also queried as the default behavior. Args: multiplier: A scalar to multiply by. Returns: product: A new instance of SymbolicOperator. Raises: TypeError: Object of invalid type cannot multiply SymbolicOperator. """ if not isinstance(multiplier, COEFFICIENT_TYPES): raise TypeError('Object of invalid type cannot multiply with ' + type(self) + '.') return self * multiplier def __truediv__(self, divisor): """ Return self / divisor for a scalar. Note: This is always floating point division. Args: divisor: A scalar to divide by. Returns: A new instance of SymbolicOperator. Raises: TypeError: Cannot divide local operator by non-scalar type. """ if not isinstance(divisor, COEFFICIENT_TYPES): raise TypeError('Cannot divide ' + type(self) + ' by non-scalar type.') return self * (1.0 / divisor) def __div__(self, divisor): """ For compatibility with Python 2. """ return self.__truediv__(divisor) def __itruediv__(self, divisor): if not isinstance(divisor, COEFFICIENT_TYPES): raise TypeError('Cannot divide ' + type(self) + ' by non-scalar type.') self *= (1.0 / divisor) return self def __idiv__(self, divisor): """ For compatibility with Python 2. """ return self.__itruediv__(divisor) def __neg__(self): """ Returns: negation (SymbolicOperator) """ return -1 * self def __pow__(self, exponent): """Exponentiate the SymbolicOperator. Args: exponent (int): The exponent with which to raise the operator. Returns: exponentiated (SymbolicOperator) Raises: ValueError: Can only raise SymbolicOperator to non-negative integer powers. """ # Handle invalid exponents. if not isinstance(exponent, int) or exponent < 0: raise ValueError( 'exponent must be a non-negative int, but was {} {}'.format( type(exponent), repr(exponent))) # Initialized identity. exponentiated = self.__class__(()) # Handle non-zero exponents. for _ in range(exponent): exponentiated *= self return exponentiated def __eq__(self, other): """Approximate numerical equality (not true equality).""" return self.isclose(other) def __ne__(self, other): return not (self == other) def __iter__(self): self._iter = iter(self.terms.items()) return self def __next__(self): term, coefficient = next(self._iter) return self.__class__(term=term, coefficient=coefficient) def isclose(self, other, tol=EQ_TOLERANCE): """Check if other (SymbolicOperator) is close to self. Comparison is done for each term individually. Return True if the difference between each term in self and other is less than EQ_TOLERANCE Args: other(SymbolicOperator): SymbolicOperator to compare against. """ if not isinstance(self, type(other)): return NotImplemented # terms which are in both: for term in set(self.terms).intersection(set(other.terms)): a = self.terms[term] b = other.terms[term] if not (isinstance(a, sympy.Expr) or isinstance(b, sympy.Expr)): tol *= max(1, abs(a), abs(b)) if self._issmall(a - b, tol) is False: return False # terms only in one (compare to 0.0 so only abs_tol) for term in set(self.terms).symmetric_difference(set(other.terms)): if term in self.terms: if self._issmall(self.terms[term], tol) is False: return False else: if self._issmall(other.terms[term], tol) is False: return False return True def compress(self, abs_tol=EQ_TOLERANCE): """ Eliminates all terms with coefficients close to zero and removes small imaginary and real parts. Args: abs_tol(float): Absolute tolerance, must be at least 0.0 """ new_terms = {} for term in self.terms: coeff = self.terms[term] if isinstance(coeff, sympy.Expr): if sympy.simplify(sympy.im(coeff) <= abs_tol) == True: coeff = sympy.re(coeff) if sympy.simplify(sympy.re(coeff) <= abs_tol) == True: coeff = 1j * sympy.im(coeff) if (sympy.simplify(abs(coeff) <= abs_tol) != True): new_terms[term] = coeff continue if isinstance(val, tq.Variable) or isinstance(val, tq.objective.objective.Objective): continue # Remove small imaginary and real parts if abs(coeff.imag) <= abs_tol: coeff = coeff.real if abs(coeff.real) <= abs_tol: coeff = 1.j * coeff.imag # Add the term if the coefficient is large enough if abs(coeff) > abs_tol: new_terms[term] = coeff self.terms = new_terms def induced_norm(self, order=1): r""" Compute the induced p-norm of the operator. If we represent an operator as :math: `\sum_{j} w_j H_j` where :math: `w_j` are scalar coefficients then this norm is :math: `\left(\sum_{j} \| w_j \|^p \right)^{\frac{1}{p}} where :math: `p` is the order of the induced norm Args: order(int): the order of the induced norm. """ norm = 0. for coefficient in self.terms.values(): norm += abs(coefficient)**order return norm**(1. / order) def many_body_order(self): """Compute the many-body order of a SymbolicOperator. The many-body order of a SymbolicOperator is the maximum length of a term with nonzero coefficient. Returns: int """ if not self.terms: # Zero operator return 0 else: return max( len(term) for term, coeff in self.terms.items() if (self._issmall(coeff) is False)) @classmethod def accumulate(cls, operators, start=None): """Sums over SymbolicOperators.""" total = copy.deepcopy(start or cls.zero()) for operator in operators: total += operator return total def get_operators(self): """Gets a list of operators with a single term. Returns: operators([self.__class__]): A generator of the operators in self. """ for term, coefficient in self.terms.items(): yield self.__class__(term, coefficient) def get_operator_groups(self, num_groups): """Gets a list of operators with a few terms. Args: num_groups(int): How many operators to get in the end. Returns: operators([self.__class__]): A list of operators summing up to self. """ if num_groups < 1: warnings.warn('Invalid num_groups {} < 1.'.format(num_groups), RuntimeWarning) num_groups = 1 operators = self.get_operators() num_groups = min(num_groups, len(self.terms)) for i in range(num_groups): yield self.accumulate( itertools.islice(operators, len(range(i, len(self.terms), num_groups))))
25,797
35.697013
97
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_2.5/main.py
import tequila as tq import numpy as np from tequila.objective.objective import Variable import openfermion from typing import Union from vqe_utils import convert_PQH_to_tq_QH, convert_tq_QH_to_PQH,\ fold_unitary_into_hamiltonian from energy_optimization import * from do_annealing import * import random # guess we could substitute that with numpy.random #TODO import argparse import pickle as pk import matplotlib.pyplot as plt # Main hyperparameters mu = 2.0 # lognormal dist mean sigma = 0.4 # lognormal dist std T_0 = 1.0 # T_0, initial starting temperature # max_epochs = 25 # num_epochs, max number of iterations max_epochs = 20 # num_epochs, max number of iterations min_epochs = 2 # num_epochs, max number of iterations5 # min_epochs = 20 # num_epochs, max number of iterations tol = 1e-6 # minimum change in energy required, otherwise terminate optimization actions_ratio = [.15, .6, .25] patience = 100 beta = 0.5 max_non_cliffords = 0 type_energy_eval='wfn' num_population = 24 num_offsprings = 20 num_processors = 8 #tuning, input as lists. # parser.add_argument('--alphas', type = float, nargs = '+', help='alpha, temperature decay', required=True) alphas = [0.9] # alpha, temperature decay' #Required be = False h2 = True n2 = False name_prefix = '../../data/' # Construct qubit-Hamiltonian #num_active = 3 #active_orbitals = list(range(num_active)) if be: R1 = rrrr R2 = 2.5 geometry = "be 0.0 0.0 0.0\nh 0.0 0.0 {R1}\nh 0.0 0.0 -{R2}" name = "/h/292/philipps/software/moldata/beh2/beh2_{R1:2.2f}_{R2:2.2f}_180" # adapt of you move data mol = tq.Molecule(name=name.format(R1=R1, R2=R2), geometry=geometry.format(R1=R1,R2=R2), n_pno=None) lqm = mol.local_qubit_map(hcb=False) H = mol.make_hamiltonian().map_qubits(lqm).simplify() #print("FCI ENERGY: ", mol.compute_energy(method="fci")) U_spa = mol.make_upccgsd_ansatz(name="SPA").map_qubits(lqm) U = U_spa elif n2: R1 = rrrr geometry = "N 0.0 0.0 0.0\nN 0.0 0.0 {R1}" # name = "/home/abhinav/matter_lab/moldata/n2/n2_{R1:2.2f}" # adapt of you move data name = "/h/292/philipps/software/moldata/n2/n2_{R1:2.2f}" # adapt of you move data mol = tq.Molecule(name=name.format(R1=R1), geometry=geometry.format(R1=R1), n_pno=None) lqm = mol.local_qubit_map(hcb=False) H = mol.make_hamiltonian().map_qubits(lqm).simplify() # print("FCI ENERGY: ", mol.compute_energy(method="fci")) print("Skip FCI calculation, take old data...") U_spa = mol.make_upccgsd_ansatz(name="SPA").map_qubits(lqm) U = U_spa elif h2: active_orbitals = list(range(3)) mol = tq.Molecule(geometry='H 0.0 0.0 0.0\n H 0.0 0.0 2.5', basis_set='6-31g', active_orbitals=active_orbitals, backend='psi4') H = mol.make_hamiltonian().simplify() print("FCI ENERGY: ", mol.compute_energy(method="fci")) U = mol.make_uccsd_ansatz(trotter_steps=1) # Alternatively, get qubit-Hamiltonian from openfermion/externally # with open("ham_6qubits.txt") as hamstring_file: """if be: with open("ham_beh2_3_3.txt") as hamstring_file: hamstring = hamstring_file.read() #print(hamstring) H = tq.QubitHamiltonian().from_string(string=hamstring, openfermion_format=True) elif h2: with open("ham_6qubits.txt") as hamstring_file: hamstring = hamstring_file.read() #print(hamstring) H = tq.QubitHamiltonian().from_string(string=hamstring, openfermion_format=True)""" n_qubits = len(H.qubits) ''' Option 'wfn': "Shortcut" via wavefunction-optimization using MPO-rep of Hamiltonian Option 'qc': Need to input a proper quantum circuit ''' # Clifford optimization in the context of reduced-size quantum circuits starting_E = 123.456 reference = True if reference: if type_energy_eval.lower() == 'wfn': starting_E, _ = minimize_energy(hamiltonian=H, n_qubits=n_qubits, type_energy_eval='wfn') print('starting energy wfn: {:.5f}'.format(starting_E), flush=True) elif type_energy_eval.lower() == 'qc': starting_E, _ = minimize_energy(hamiltonian=H, n_qubits=n_qubits, type_energy_eval='qc', cluster_circuit=U) print('starting energy spa: {:.5f}'.format(starting_E)) else: raise Exception("type_energy_eval must be either 'wfn' or 'qc', but is", type_energy_eval) starting_E, _ = minimize_energy(hamiltonian=H, n_qubits=n_qubits, type_energy_eval='wfn') """for alpha in alphas: print('Starting optimization, alpha = {:3f}'.format(alpha)) # print('Energy to beat', minimize_energy(H, n_qubits, 'wfn')[0]) simulated_annealing(hamiltonian=H, num_population=num_population, num_offsprings=num_offsprings, num_processors=num_processors, tol=tol, max_epochs=max_epochs, min_epochs=min_epochs, T_0=T_0, alpha=alpha, actions_ratio=actions_ratio, max_non_cliffords=max_non_cliffords, verbose=True, patience=patience, beta=beta, type_energy_eval=type_energy_eval.lower(), cluster_circuit=U, starting_energy=starting_E)""" alter_cliffords = True if alter_cliffords: print("starting to replace cliffords with non-clifford gates to see if that improves the current fitness") replace_cliff_with_non_cliff(hamiltonian=H, num_population=num_population, num_offsprings=num_offsprings, num_processors=num_processors, tol=tol, max_epochs=max_epochs, min_epochs=min_epochs, T_0=T_0, alpha=alphas[0], actions_ratio=actions_ratio, max_non_cliffords=max_non_cliffords, verbose=True, patience=patience, beta=beta, type_energy_eval=type_energy_eval.lower(), cluster_circuit=U, starting_energy=starting_E) # accepted_E, tested_E, decisions, instructions_list, best_instructions, temp, best_E = simulated_annealing(hamiltonian=H, # population=4, # num_mutations=2, # num_processors=1, # tol=opt.tol, max_epochs=opt.max_epochs, # min_epochs=opt.min_epochs, T_0=opt.T_0, alpha=alpha, # mu=opt.mu, sigma=opt.sigma, verbose=True, prev_E = starting_E, patience = 10, beta = 0.5, # energy_eval='qc', # eval_circuit=U # print(best_E) # print(best_instructions) # print(len(accepted_E)) # plt.plot(accepted_E) # plt.show() # #pickling data # data = {'accepted_energies': accepted_E, 'tested_energies': tested_E, # 'decisions': decisions, 'instructions': instructions_list, # 'best_instructions': best_instructions, 'temperature': temp, # 'best_energy': best_E} # f_name = '{}{}_alpha_{:.2f}.pk'.format(opt.name_prefix, r, alpha) # pk.dump(data, open(f_name, 'wb')) # print('Finished optimization, data saved in {}'.format(f_name))
7,368
40.869318
129
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_2.5/my_mpo.py
import numpy as np import tensornetwork as tn from tensornetwork.backends.abstract_backend import AbstractBackend tn.set_default_backend("pytorch") #tn.set_default_backend("numpy") from typing import List, Union, Text, Optional, Any, Type Tensor = Any import tequila as tq import torch EPS = 1e-12 class SubOperator: """ This is just a helper class to store coefficient, operators and positions in an intermediate format """ def __init__(self, coefficient: float, operators: List, positions: List ): self._coefficient = coefficient self._operators = operators self._positions = positions @property def coefficient(self): return self._coefficient @property def operators(self): return self._operators @property def positions(self): return self._positions class MPOContainer: """ Class that handles the MPO. Is able to set values at certain positions, update containers (wannabe-equivalent to dynamic arrays) and compress the MPO """ def __init__(self, n_qubits: int, ): self.n_qubits = n_qubits self.container = [ np.zeros((1,1,2,2), dtype=np.complex) for q in range(self.n_qubits) ] def get_dim(self): """ Returns max dimension of container """ d = 1 for q in range(len(self.container)): d = max(d, self.container[q].shape[0]) return d def set_tensor(self, qubit: int, set_at: list, add_operator: Union[np.ndarray, float]): """ set_at: where to put data """ # Set a matrix if len(set_at) == 2: self.container[qubit][set_at[0],set_at[1],:,:] = add_operator[:,:] # Set specific values elif len(set_at) == 4: self.container[qubit][set_at[0],set_at[1],set_at[2],set_at[3]] =\ add_operator else: raise Exception("set_at needs to be either of length 2 or 4") def update_container(self, qubit: int, update_dir: list, add_operator: np.ndarray): """ This should mimick a dynamic array update_dir: e.g. [1,1,0,0] -> extend dimension along where there's a 1 the last two dimensions are always 2x2 only """ old_shape = self.container[qubit].shape # print(old_shape) if not len(update_dir) == 4: if len(update_dir) == 2: update_dir += [0, 0] else: raise Exception("update_dir needs to be either of length 2 or 4") if update_dir[2] or update_dir[3]: raise Exception("Last two dims must be zero.") new_shape = tuple(update_dir[i]+old_shape[i] for i in range(len(update_dir))) new_tensor = np.zeros(new_shape, dtype=np.complex) # Copy old values new_tensor[:old_shape[0],:old_shape[1],:,:] = self.container[qubit][:,:,:,:] # Add new values new_tensor[new_shape[0]-1,new_shape[1]-1,:,:] = add_operator[:,:] # Overwrite container self.container[qubit] = new_tensor def compress_mpo(self): """ Compression of MPO via SVD """ n_qubits = len(self.container) for q in range(n_qubits): my_shape = self.container[q].shape self.container[q] =\ self.container[q].reshape((my_shape[0], my_shape[1], -1)) # Go forwards for q in range(n_qubits-1): # Apply permutation [0 1 2] -> [0 2 1] my_tensor = np.swapaxes(self.container[q], 1, 2) my_tensor = my_tensor.reshape((-1, my_tensor.shape[2])) # full_matrices flag corresponds to 'econ' -> no zero-singular values u, s, vh = np.linalg.svd(my_tensor, full_matrices=False) # Count the non-zero singular values num_nonzeros = len(np.argwhere(s>EPS)) # Construct matrix from square root of singular values s = np.diag(np.sqrt(s[:num_nonzeros])) u = u[:,:num_nonzeros] vh = vh[:num_nonzeros,:] # Distribute weights to left- and right singular vectors (@ = np.matmul) u = u @ s vh = s @ vh # Apply permutation [0 1 2] -> [0 2 1] u = u.reshape((self.container[q].shape[0],\ self.container[q].shape[2], -1)) self.container[q] = np.swapaxes(u, 1, 2) self.container[q+1] = tn.ncon([vh, self.container[q+1]], [(-1, 1),(1, -2, -3)]) # Go backwards for q in range(n_qubits-1, 0, -1): my_tensor = self.container[q] my_tensor = my_tensor.reshape((self.container[q].shape[0], -1)) # full_matrices flag corresponds to 'econ' -> no zero-singular values u, s, vh = np.linalg.svd(my_tensor, full_matrices=False) # Count the non-zero singular values num_nonzeros = len(np.argwhere(s>EPS)) # Construct matrix from square root of singular values s = np.diag(np.sqrt(s[:num_nonzeros])) u = u[:,:num_nonzeros] vh = vh[:num_nonzeros,:] # Distribute weights to left- and right singular vectors u = u @ s vh = s @ vh self.container[q] = np.reshape(vh, (num_nonzeros, self.container[q].shape[1], self.container[q].shape[2])) self.container[q-1] = tn.ncon([self.container[q-1], u], [(-1, 1, -3),(1, -2)]) for q in range(n_qubits): my_shape = self.container[q].shape self.container[q] = self.container[q].reshape((my_shape[0],\ my_shape[1],2,2)) # TODO maybe make subclass of tn.FiniteMPO if it makes sense #class my_MPO(tn.FiniteMPO): class MyMPO: """ Class building up on tensornetwork FiniteMPO to handle MPO-Hamiltonians """ def __init__(self, hamiltonian: Union[tq.QubitHamiltonian, Text], # tensors: List[Tensor], backend: Optional[Union[AbstractBackend, Text]] = None, n_qubits: Optional[int] = None, name: Optional[Text] = None, maxdim: Optional[int] = 10000) -> None: # TODO: modifiy docstring """ Initialize a finite MPO object Args: tensors: The mpo tensors. backend: An optional backend. Defaults to the defaulf backend of TensorNetwork. name: An optional name for the MPO. """ self.hamiltonian = hamiltonian self.maxdim = maxdim if n_qubits: self._n_qubits = n_qubits else: self._n_qubits = self.get_n_qubits() @property def n_qubits(self): return self._n_qubits def make_mpo_from_hamiltonian(self): intermediate = self.openfermion_to_intermediate() # for i in range(len(intermediate)): # print(intermediate[i].coefficient) # print(intermediate[i].operators) # print(intermediate[i].positions) self.mpo = self.intermediate_to_mpo(intermediate) def openfermion_to_intermediate(self): # Here, have either a QubitHamiltonian or a file with a of-operator # Start with Qubithamiltonian def get_pauli_matrix(string): pauli_matrices = { 'I': np.array([[1, 0], [0, 1]], dtype=np.complex), 'Z': np.array([[1, 0], [0, -1]], dtype=np.complex), 'X': np.array([[0, 1], [1, 0]], dtype=np.complex), 'Y': np.array([[0, -1j], [1j, 0]], dtype=np.complex) } return pauli_matrices[string.upper()] intermediate = [] first = True # Store all paulistrings in intermediate format for paulistring in self.hamiltonian.paulistrings: coefficient = paulistring.coeff # print(coefficient) operators = [] positions = [] # Only first one should be identity -> distribute over all if first and not paulistring.items(): positions += [] operators += [] first = False elif not first and not paulistring.items(): raise Exception("Only first Pauli should be identity.") # Get operators and where they act for k,v in paulistring.items(): positions += [k] operators += [get_pauli_matrix(v)] tmp_op = SubOperator(coefficient=coefficient, operators=operators, positions=positions) intermediate += [tmp_op] # print("len intermediate = num Pauli strings", len(intermediate)) return intermediate def build_single_mpo(self, intermediate, j): # Set MPO Container n_qubits = self._n_qubits mpo = MPOContainer(n_qubits=n_qubits) # *********************************************************************** # Set first entries (of which we know that they are 2x2-matrices) # Typically, this is an identity my_coefficient = intermediate[j].coefficient my_positions = intermediate[j].positions my_operators = intermediate[j].operators for q in range(n_qubits): if not q in my_positions: mpo.set_tensor(qubit=q, set_at=[0,0], add_operator=np.complex(my_coefficient)**(1/n_qubits)* np.eye(2)) elif q in my_positions: my_pos_index = my_positions.index(q) mpo.set_tensor(qubit=q, set_at=[0,0], add_operator=np.complex(my_coefficient)**(1/n_qubits)* my_operators[my_pos_index]) # *********************************************************************** # All other entries # while (j smaller than number of intermediates left) and mpo.dim() <= self.maxdim # Re-write this based on positions keyword! j += 1 while j < len(intermediate) and mpo.get_dim() < self.maxdim: # """ my_coefficient = intermediate[j].coefficient my_positions = intermediate[j].positions my_operators = intermediate[j].operators for q in range(n_qubits): # It is guaranteed that every index appears only once in positions if q == 0: update_dir = [0,1] elif q == n_qubits-1: update_dir = [1,0] else: update_dir = [1,1] # If there's an operator on my position, add that if q in my_positions: my_pos_index = my_positions.index(q) mpo.update_container(qubit=q, update_dir=update_dir, add_operator= np.complex(my_coefficient)**(1/n_qubits)* my_operators[my_pos_index]) # Else add an identity else: mpo.update_container(qubit=q, update_dir=update_dir, add_operator= np.complex(my_coefficient)**(1/n_qubits)* np.eye(2)) if not j % 100: mpo.compress_mpo() #print("\t\tAt iteration ", j, " MPO has dimension ", mpo.get_dim()) j += 1 mpo.compress_mpo() #print("\tAt final iteration ", j-1, " MPO has dimension ", mpo.get_dim()) return mpo, j def intermediate_to_mpo(self, intermediate): n_qubits = self._n_qubits # TODO Change to multiple MPOs mpo_list = [] j_global = 0 num_mpos = 0 # Start with 0, then final one is correct while j_global < len(intermediate): current_mpo, j_global = self.build_single_mpo(intermediate, j_global) mpo_list += [current_mpo] num_mpos += 1 return mpo_list def construct_matrix(self): # TODO extend to lists of MPOs ''' Recover matrix, e.g. to compare with Hamiltonian that we get from tq ''' mpo = self.mpo # Contract over all bond indices # mpo.container has indices [bond, bond, physical, physical] n_qubits = self._n_qubits d = int(2**(n_qubits/2)) first = True H = None #H = np.zeros((d,d,d,d), dtype='complex') # Define network nodes # | | | | # -O--O--...--O--O- # | | | | for m in mpo: assert(n_qubits == len(m.container)) nodes = [tn.Node(m.container[q], name=str(q)) for q in range(n_qubits)] # Connect network (along double -- above) for q in range(n_qubits-1): nodes[q][1] ^ nodes[q+1][0] # Collect dangling edges (free indices) edges = [] # Left dangling edge edges += [nodes[0].get_edge(0)] # Right dangling edge edges += [nodes[-1].get_edge(1)] # Upper dangling edges for q in range(n_qubits): edges += [nodes[q].get_edge(2)] # Lower dangling edges for q in range(n_qubits): edges += [nodes[q].get_edge(3)] # Contract between all nodes along non-dangling edges res = tn.contractors.auto(nodes, output_edge_order=edges) # Reshape to get tensor of order 4 (get rid of left- and right open indices # and combine top&bottom into one) if isinstance(res.tensor, torch.Tensor): H_m = res.tensor.numpy() if not first: H += H_m else: H = H_m first = False return H.reshape((d,d,d,d))
14,354
36.480418
99
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_2.5/do_annealing.py
import tequila as tq import numpy as np import pickle from pathos.multiprocessing import ProcessingPool as Pool from parallel_annealing import * #from dummy_par import * from mutation_options import * from single_thread_annealing import * def find_best_instructions(instructions_dict): """ This function finds the instruction with the best fitness args: instructions_dict: A dictionary with the "Instructions" objects the corresponding fitness values as values """ best_instructions = None best_fitness = 10000000 for key in instructions_dict: if instructions_dict[key][1] <= best_fitness: best_instructions = instructions_dict[key][0] best_fitness = instructions_dict[key][1] return best_instructions, best_fitness def simulated_annealing(num_population, num_offsprings, actions_ratio, hamiltonian, max_epochs=100, min_epochs=1, tol=1e-6, type_energy_eval="wfn", cluster_circuit=None, patience = 20, num_processors=4, T_0=1.0, alpha=0.9, max_non_cliffords=0, verbose=False, beta=0.5, starting_energy=None): """ this function tries to find the clifford circuit that best lowers the energy of the hamiltonian using simulated annealing. params: - num_population = number of members in a generation - num_offsprings = number of mutations carried on every member - num_processors = number of processors to use for parallelization - T_0 = initial temperature - alpha = temperature decay - beta = parameter to adjust temperature on resetting after running out of patience - max_epochs = max iterations for optimizing - min_epochs = min iterations for optimizing - tol = minimum change in energy required, otherwise terminate optimization - verbose = display energies/decisions at iterations of not - hamiltonian = original hamiltonian - actions_ratio = The ratio of the different actions for mutations - type_energy_eval = keyword specifying the type of optimization method to use for energy minimization - cluster_circuit = the reference circuit to which clifford gates are added - patience = the number of epochs before resetting the optimization """ if verbose: print("Starting to Optimize Cluster circuit", flush=True) num_qubits = len(hamiltonian.qubits) if verbose: print("Initializing Generation", flush=True) # restart = False if previous_instructions is None\ # else True restart = False instructions_dict = {} instructions_list = [] current_fitness_list = [] fitness, wfn = None, None # pre-initialize with None for instruction_id in range(num_population): instructions = None if restart: try: instructions = Instructions(n_qubits=num_qubits, alpha=alpha, T_0=T_0, beta=beta, patience=patience, max_non_cliffords=max_non_cliffords, reference_energy=starting_energy) instructions.gates = pickle.load(open("instruct_gates.pickle", "rb")) instructions.positions = pickle.load(open("instruct_positions.pickle", "rb")) instructions.best_reference_wfn = pickle.load(open("best_reference_wfn.pickle", "rb")) print("Added a guess from previous runs", flush=True) fitness, wfn = evaluate_fitness(instructions=instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) except Exception as e: print(e) raise Exception("Did not find a guess from previous runs") # pass restart = False #print(instructions._str()) else: failed = True while failed: instructions = Instructions(n_qubits=num_qubits, alpha=alpha, T_0=T_0, beta=beta, patience=patience, max_non_cliffords=max_non_cliffords, reference_energy=starting_energy) instructions.prune() fitness, wfn = evaluate_fitness(instructions=instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) # if fitness <= starting_energy: failed = False instructions.set_reference_wfn(wfn) current_fitness_list.append(fitness) instructions_list.append(instructions) instructions_dict[instruction_id] = (instructions, fitness) if verbose: print("First Generation details: \n", flush=True) for key in instructions_dict: print("Initial Instructions number: ", key, flush=True) instructions_dict[key][0]._str() print("Initial fitness values: ", instructions_dict[key][1], flush=True) best_instructions, best_energy = find_best_instructions(instructions_dict) if verbose: print("Best member of the Generation: \n", flush=True) print("Instructions: ", flush=True) best_instructions._str() print("fitness value: ", best_energy, flush=True) pickle.dump(best_instructions.gates, open("instruct_gates.pickle", "wb")) pickle.dump(best_instructions.positions, open("instruct_positions.pickle", "wb")) pickle.dump(best_instructions.best_reference_wfn, open("best_reference_wfn.pickle", "wb")) epoch = 0 previous_best_energy = best_energy converged = False has_improved_before = False dts = [] #pool = multiprocessing.Pool(processes=num_processors) while (epoch < max_epochs): print("Epoch: ", epoch, flush=True) import time t0 = time.time() if num_processors == 1: st_evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, type_energy_eval, cluster_circuit) else: evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, num_processors, type_energy_eval, cluster_circuit) t1 = time.time() dts += [t1-t0] best_instructions, best_energy = find_best_instructions(instructions_dict) if verbose: print("Best member of the Generation: \n", flush=True) print("Instructions: ", flush=True) best_instructions._str() print("fitness value: ", best_energy, flush=True) # A bit confusing, but: # Want that current best energy has improved something previous, is better than # some starting energy and achieves some convergence criterion has_improved_before = True if np.abs(best_energy - previous_best_energy) < 0\ else False if np.abs(best_energy - previous_best_energy) < tol and has_improved_before: if starting_energy is not None: converged = True if best_energy < starting_energy else False else: converged = True else: converged = False if best_energy < previous_best_energy: previous_best_energy = best_energy epoch += 1 pickle.dump(best_instructions.gates, open("instruct_gates.pickle", "wb")) pickle.dump(best_instructions.positions, open("instruct_positions.pickle", "wb")) pickle.dump(best_instructions.best_reference_wfn, open("best_reference_wfn.pickle", "wb")) #pool.close() if converged: print("Converged after ", epoch, " iterations.", flush=True) print("Best energy:", best_energy, flush=True) print("\t with instructions", best_instructions.gates, best_instructions.positions, flush=True) print("\t optimal parameters", best_instructions.best_reference_wfn, flush=True) print("average time: ", np.average(dts), flush=True) print("overall time: ", np.sum(dts), flush=True) # best_instructions.replace_UCCXc_with_UCC(number=max_non_cliffords) pickle.dump(best_instructions.gates, open("instruct_gates.pickle", "wb")) pickle.dump(best_instructions.positions, open("instruct_positions.pickle", "wb")) pickle.dump(best_instructions.best_reference_wfn, open("best_reference_wfn.pickle", "wb")) def replace_cliff_with_non_cliff(num_population, num_offsprings, actions_ratio, hamiltonian, max_epochs=100, min_epochs=1, tol=1e-6, type_energy_eval="wfn", cluster_circuit=None, patience = 20, num_processors=4, T_0=1.0, alpha=0.9, max_non_cliffords=0, verbose=False, beta=0.5, starting_energy=None): """ this function tries to find the clifford circuit that best lowers the energy of the hamiltonian using simulated annealing. params: - num_population = number of members in a generation - num_offsprings = number of mutations carried on every member - num_processors = number of processors to use for parallelization - T_0 = initial temperature - alpha = temperature decay - beta = parameter to adjust temperature on resetting after running out of patience - max_epochs = max iterations for optimizing - min_epochs = min iterations for optimizing - tol = minimum change in energy required, otherwise terminate optimization - verbose = display energies/decisions at iterations of not - hamiltonian = original hamiltonian - actions_ratio = The ratio of the different actions for mutations - type_energy_eval = keyword specifying the type of optimization method to use for energy minimization - cluster_circuit = the reference circuit to which clifford gates are added - patience = the number of epochs before resetting the optimization """ if verbose: print("Starting to replace clifford gates Cluster circuit with non-clifford gates one at a time", flush=True) num_qubits = len(hamiltonian.qubits) #get the best clifford object instructions = Instructions(n_qubits=num_qubits, alpha=alpha, T_0=T_0, beta=beta, patience=patience, max_non_cliffords=max_non_cliffords, reference_energy=starting_energy) instructions.gates = pickle.load(open("instruct_gates.pickle", "rb")) instructions.positions = pickle.load(open("instruct_positions.pickle", "rb")) instructions.best_reference_wfn = pickle.load(open("best_reference_wfn.pickle", "rb")) fitness, wfn = evaluate_fitness(instructions=instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) if verbose: print("Initial energy after previous Clifford optimization is",\ fitness, flush=True) print("Starting with instructions", instructions.gates, instructions.positions, flush=True) instructions_dict = {} instructions_dict[0] = (instructions, fitness) for gate_id, (gate, position) in enumerate(zip(instructions.gates, instructions.positions)): print(gate) altered_instructions = copy.deepcopy(instructions) # skip if controlled rotation if gate[0]=='C': continue altered_instructions.replace_cg_w_ncg(gate_id) # altered_instructions.max_non_cliffords = 1 # TODO why is this set to 1?? altered_instructions.max_non_cliffords = max_non_cliffords #clifford_circuit, init_angles = build_circuit(instructions) #print(clifford_circuit, init_angles) #folded_hamiltonian = perform_folding(hamiltonian, clifford_circuit) #folded_hamiltonian2 = (convert_PQH_to_tq_QH(folded_hamiltonian))() #print(folded_hamiltonian) #clifford_circuit, init_angles = build_circuit(altered_instructions) #print(clifford_circuit, init_angles) #folded_hamiltonian = perform_folding(hamiltonian, clifford_circuit) #folded_hamiltonian1 = (convert_PQH_to_tq_QH(folded_hamiltonian))(init_angles) #print(folded_hamiltonian1 - folded_hamiltonian2) #print(folded_hamiltonian) #raise Exception("teste") counter = 0 success = False while not success: counter += 1 try: fitness, wfn = evaluate_fitness(instructions=altered_instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) success = True except Exception as e: print(e) if counter > 5: print("This replacement failed more than 5 times") success = True instructions_dict[gate_id+1] = (altered_instructions, fitness) #circuit = build_circuit(altered_instructions) #tq.draw(circuit,backend="cirq") best_instructions, best_energy = find_best_instructions(instructions_dict) print("best instrucitons after the non-clifford opimizaton") print("Best energy:", best_energy, flush=True) print("\t with instructions", best_instructions.gates, best_instructions.positions, flush=True)
13,155
46.154122
187
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_2.5/scipy_optimizer.py
import numpy, copy, scipy, typing, numbers from tequila import BitString, BitNumbering, BitStringLSB from tequila.utils.keymap import KeyMapRegisterToSubregister from tequila.circuit.compiler import change_basis from tequila.utils import to_float import tequila as tq from tequila.objective import Objective from tequila.optimizers.optimizer_scipy import OptimizerSciPy, SciPyResults from tequila.objective.objective import assign_variable, Variable, format_variable_dictionary, format_variable_list from tequila.circuit.noise import NoiseModel #from tequila.optimizers._containers import _EvalContainer, _GradContainer, _HessContainer, _QngContainer from vqe_utils import * class _EvalContainer: """ Overwrite the call function Container Class to access scipy and keep the optimization history. This class is used by the SciPy optimizer and should not be used elsewhere. Attributes --------- objective: the objective to evaluate. param_keys: the dictionary mapping parameter keys to positions in a numpy array. samples: the number of samples to evaluate objective with. save_history: whether or not to save, in a history, information about each time __call__ occurs. print_level dictates the verbosity of printing during call. N: the length of param_keys. history: if save_history, a list of energies received from every __call__ history_angles: if save_history, a list of angles sent to __call__. """ def __init__(self, Hamiltonian, unitary, param_keys, Ham_derivatives= None, Eval=None, passive_angles=None, samples=1024, save_history=True, print_level: int = 3): self.Hamiltonian = Hamiltonian self.unitary = unitary self.samples = samples self.param_keys = param_keys self.N = len(param_keys) self.save_history = save_history self.print_level = print_level self.passive_angles = passive_angles self.Eval = Eval self.infostring = None self.Ham_derivatives = Ham_derivatives if save_history: self.history = [] self.history_angles = [] def __call__(self, p, *args, **kwargs): """ call a wrapped objective. Parameters ---------- p: numpy array: Parameters with which to call the objective. args kwargs Returns ------- numpy.array: value of self.objective with p translated into variables, as a numpy array. """ angles = {}#dict((self.param_keys[i], p[i]) for i in range(self.N)) for i in range(self.N): if self.param_keys[i] in self.unitary.extract_variables(): angles[self.param_keys[i]] = p[i] else: angles[self.param_keys[i]] = complex(p[i]) if self.passive_angles is not None: angles = {**angles, **self.passive_angles} vars = format_variable_dictionary(angles) Hamiltonian = self.Hamiltonian(vars) #print(Hamiltonian) #print(self.unitary) #print(vars) Expval = tq.ExpectationValue(H=Hamiltonian, U=self.unitary) #print(Expval) E = tq.simulate(Expval, vars, backend='qulacs', samples=self.samples) self.infostring = "{:15} : {} expectationvalues\n".format("Objective", Expval.count_expectationvalues()) if self.print_level > 2: print("E={:+2.8f}".format(E), " angles=", angles, " samples=", self.samples) elif self.print_level > 1: print("E={:+2.8f}".format(E)) if self.save_history: self.history.append(E) self.history_angles.append(angles) return complex(E) # jax types confuses optimizers class _GradContainer(_EvalContainer): """ Overwrite the call function Container Class to access scipy and keep the optimization history. This class is used by the SciPy optimizer and should not be used elsewhere. see _EvalContainer for details. """ def __call__(self, p, *args, **kwargs): """ call the wrapped qng. Parameters ---------- p: numpy array: Parameters with which to call gradient args kwargs Returns ------- numpy.array: value of self.objective with p translated into variables, as a numpy array. """ Ham_derivatives = self.Ham_derivatives Hamiltonian = self.Hamiltonian unitary = self.unitary dE_vec = numpy.zeros(self.N) memory = dict() #variables = dict((self.param_keys[i], p[i]) for i in range(len(self.param_keys))) variables = {}#dict((self.param_keys[i], p[i]) for i in range(self.N)) for i in range(len(self.param_keys)): if self.param_keys[i] in self.unitary.extract_variables(): variables[self.param_keys[i]] = p[i] else: variables[self.param_keys[i]] = complex(p[i]) if self.passive_angles is not None: variables = {**variables, **self.passive_angles} vars = format_variable_dictionary(variables) expvals = 0 for i in range(self.N): derivative = 0.0 if self.param_keys[i] in list(unitary.extract_variables()): Ham = Hamiltonian(vars) Expval = tq.ExpectationValue(H=Ham, U=unitary) temp_derivative = tq.compile(objective = tq.grad(objective = Expval, variable = self.param_keys[i]),backend='qulacs') expvals += temp_derivative.count_expectationvalues() derivative += temp_derivative if self.param_keys[i] in list(Ham_derivatives.keys()): #print(self.param_keys[i]) Ham = Ham_derivatives[self.param_keys[i]] Ham = convert_PQH_to_tq_QH(Ham) H = Ham(vars) #print(H) #raise Exception("testing") Expval = tq.ExpectationValue(H=H, U=unitary) expvals += Expval.count_expectationvalues() derivative += tq.simulate(Expval, vars, backend='qulacs', samples=self.samples) #print(derivative) #print(type(H)) if isinstance(derivative, float) or isinstance(derivative, numpy.complex64) : dE_vec[i] = derivative else: dE_vec[i] = derivative(variables=variables, samples=self.samples) memory[self.param_keys[i]] = dE_vec[i] self.infostring = "{:15} : {} expectationvalues\n".format("gradient", expvals) self.history.append(memory) return numpy.asarray(dE_vec, dtype=numpy.complex64) class optimize_scipy(OptimizerSciPy): """ overwrite the expectation and gradient container objects """ def initialize_variables(self, all_variables, initial_values, variables): """ Convenience function to format the variables of some objective recieved in calls to optimzers. Parameters ---------- objective: Objective: the objective being optimized. initial_values: dict or string: initial values for the variables of objective, as a dictionary. if string: can be `zero` or `random` if callable: custom function that initializes when keys are passed if None: random initialization between 0 and 2pi (not recommended) variables: list: the variables being optimized over. Returns ------- tuple: active_angles, a dict of those variables being optimized. passive_angles, a dict of those variables NOT being optimized. variables: formatted list of the variables being optimized. """ # bring into right format variables = format_variable_list(variables) initial_values = format_variable_dictionary(initial_values) all_variables = all_variables if variables is None: variables = all_variables if initial_values is None: initial_values = {k: numpy.random.uniform(0, 2 * numpy.pi) for k in all_variables} elif hasattr(initial_values, "lower"): if initial_values.lower() == "zero": initial_values = {k:0.0 for k in all_variables} elif initial_values.lower() == "random": initial_values = {k: numpy.random.uniform(0, 2 * numpy.pi) for k in all_variables} else: raise TequilaOptimizerException("unknown initialization instruction: {}".format(initial_values)) elif callable(initial_values): initial_values = {k: initial_values(k) for k in all_variables} elif isinstance(initial_values, numbers.Number): initial_values = {k: initial_values for k in all_variables} else: # autocomplete initial values, warn if you did detected = False for k in all_variables: if k not in initial_values: initial_values[k] = 0.0 detected = True if detected and not self.silent: warnings.warn("initial_variables given but not complete: Autocompleted with zeroes", TequilaWarning) active_angles = {} for v in variables: active_angles[v] = initial_values[v] passive_angles = {} for k, v in initial_values.items(): if k not in active_angles.keys(): passive_angles[k] = v return active_angles, passive_angles, variables def __call__(self, Hamiltonian, unitary, variables: typing.List[Variable] = None, initial_values: typing.Dict[Variable, numbers.Real] = None, gradient: typing.Dict[Variable, Objective] = None, hessian: typing.Dict[typing.Tuple[Variable, Variable], Objective] = None, reset_history: bool = True, *args, **kwargs) -> SciPyResults: """ Perform optimization using scipy optimizers. Parameters ---------- objective: Objective: the objective to optimize. variables: list, optional: the variables of objective to optimize. If None: optimize all. initial_values: dict, optional: a starting point from which to begin optimization. Will be generated if None. gradient: optional: Information or object used to calculate the gradient of objective. Defaults to None: get analytically. hessian: optional: Information or object used to calculate the hessian of objective. Defaults to None: get analytically. reset_history: bool: Default = True: whether or not to reset all history before optimizing. args kwargs Returns ------- ScipyReturnType: the results of optimization. """ H = convert_PQH_to_tq_QH(Hamiltonian) Ham_variables, Ham_derivatives = H._construct_derivatives() #print("hamvars",Ham_variables) all_variables = copy.deepcopy(Ham_variables) #print(all_variables) for var in unitary.extract_variables(): all_variables.append(var) #print(all_variables) infostring = "{:15} : {}\n".format("Method", self.method) #infostring += "{:15} : {} expectationvalues\n".format("Objective", objective.count_expectationvalues()) if self.save_history and reset_history: self.reset_history() active_angles, passive_angles, variables = self.initialize_variables(all_variables, initial_values, variables) #print(active_angles, passive_angles, variables) # Transform the initial value directory into (ordered) arrays param_keys, param_values = zip(*active_angles.items()) param_values = numpy.array(param_values) # process and initialize scipy bounds bounds = None if self.method_bounds is not None: bounds = {k: None for k in active_angles} for k, v in self.method_bounds.items(): if k in bounds: bounds[k] = v infostring += "{:15} : {}\n".format("bounds", self.method_bounds) names, bounds = zip(*bounds.items()) assert (names == param_keys) # make sure the bounds are not shuffled #print(param_keys, param_values) # do the compilation here to avoid costly recompilation during the optimization #compiled_objective = self.compile_objective(objective=objective, *args, **kwargs) E = _EvalContainer(Hamiltonian = H, unitary = unitary, Eval=None, param_keys=param_keys, samples=self.samples, passive_angles=passive_angles, save_history=self.save_history, print_level=self.print_level) E.print_level = 0 (E(param_values)) E.print_level = self.print_level infostring += E.infostring if gradient is not None: infostring += "{:15} : {}\n".format("grad instr", gradient) if hessian is not None: infostring += "{:15} : {}\n".format("hess_instr", hessian) compile_gradient = self.method in (self.gradient_based_methods + self.hessian_based_methods) compile_hessian = self.method in self.hessian_based_methods dE = None ddE = None # detect if numerical gradients shall be used # switch off compiling if so if isinstance(gradient, str): if gradient.lower() == 'qng': compile_gradient = False if compile_hessian: raise TequilaException('Sorry, QNG and hessian not yet tested together.') combos = get_qng_combos(objective, initial_values=initial_values, backend=self.backend, samples=self.samples, noise=self.noise) dE = _QngContainer(combos=combos, param_keys=param_keys, passive_angles=passive_angles) infostring += "{:15} : QNG {}\n".format("gradient", dE) else: dE = gradient compile_gradient = False if compile_hessian: compile_hessian = False if hessian is None: hessian = gradient infostring += "{:15} : scipy numerical {}\n".format("gradient", dE) infostring += "{:15} : scipy numerical {}\n".format("hessian", ddE) if isinstance(gradient,dict): if gradient['method'] == 'qng': func = gradient['function'] compile_gradient = False if compile_hessian: raise TequilaException('Sorry, QNG and hessian not yet tested together.') combos = get_qng_combos(objective,func=func, initial_values=initial_values, backend=self.backend, samples=self.samples, noise=self.noise) dE = _QngContainer(combos=combos, param_keys=param_keys, passive_angles=passive_angles) infostring += "{:15} : QNG {}\n".format("gradient", dE) if isinstance(hessian, str): ddE = hessian compile_hessian = False if compile_gradient: dE =_GradContainer(Ham_derivatives = Ham_derivatives, unitary = unitary, Hamiltonian = H, Eval= E, param_keys=param_keys, samples=self.samples, passive_angles=passive_angles, save_history=self.save_history, print_level=self.print_level) dE.print_level = 0 (dE(param_values)) dE.print_level = self.print_level infostring += dE.infostring if self.print_level > 0: print(self) print(infostring) print("{:15} : {}\n".format("active variables", len(active_angles))) Es = [] optimizer_instance = self class SciPyCallback: energies = [] gradients = [] hessians = [] angles = [] real_iterations = 0 def __call__(self, *args, **kwargs): self.energies.append(E.history[-1]) self.angles.append(E.history_angles[-1]) if dE is not None and not isinstance(dE, str): self.gradients.append(dE.history[-1]) if ddE is not None and not isinstance(ddE, str): self.hessians.append(ddE.history[-1]) self.real_iterations += 1 if 'callback' in optimizer_instance.kwargs: optimizer_instance.kwargs['callback'](E.history_angles[-1]) callback = SciPyCallback() res = scipy.optimize.minimize(E, x0=param_values, jac=dE, hess=ddE, args=(Es,), method=self.method, tol=self.tol, bounds=bounds, constraints=self.method_constraints, options=self.method_options, callback=callback) # failsafe since callback is not implemented everywhere if callback.real_iterations == 0: real_iterations = range(len(E.history)) if self.save_history: self.history.energies = callback.energies self.history.energy_evaluations = E.history self.history.angles = callback.angles self.history.angles_evaluations = E.history_angles self.history.gradients = callback.gradients self.history.hessians = callback.hessians if dE is not None and not isinstance(dE, str): self.history.gradients_evaluations = dE.history if ddE is not None and not isinstance(ddE, str): self.history.hessians_evaluations = ddE.history # some methods like "cobyla" do not support callback functions if len(self.history.energies) == 0: self.history.energies = E.history self.history.angles = E.history_angles # some scipy methods always give back the last value and not the minimum (e.g. cobyla) ea = sorted(zip(E.history, E.history_angles), key=lambda x: x[0]) E_final = ea[0][0] angles_final = ea[0][1] #dict((param_keys[i], res.x[i]) for i in range(len(param_keys))) angles_final = {**angles_final, **passive_angles} return SciPyResults(energy=E_final, history=self.history, variables=format_variable_dictionary(angles_final), scipy_result=res) def minimize(Hamiltonian, unitary, gradient: typing.Union[str, typing.Dict[Variable, Objective]] = None, hessian: typing.Union[str, typing.Dict[typing.Tuple[Variable, Variable], Objective]] = None, initial_values: typing.Dict[typing.Hashable, numbers.Real] = None, variables: typing.List[typing.Hashable] = None, samples: int = None, maxiter: int = 100, backend: str = None, backend_options: dict = None, noise: NoiseModel = None, device: str = None, method: str = "BFGS", tol: float = 1.e-3, method_options: dict = None, method_bounds: typing.Dict[typing.Hashable, numbers.Real] = None, method_constraints=None, silent: bool = False, save_history: bool = True, *args, **kwargs) -> SciPyResults: """ calls the local optimize_scipy scipy funtion instead and pass down the objective construction down Parameters ---------- objective: Objective : The tequila objective to optimize gradient: typing.Union[str, typing.Dict[Variable, Objective], None] : Default value = None): '2-point', 'cs' or '3-point' for numerical gradient evaluation (does not work in combination with all optimizers), dictionary of variables and tequila objective to define own gradient, None for automatic construction (default) Other options include 'qng' to use the quantum natural gradient. hessian: typing.Union[str, typing.Dict[Variable, Objective], None], optional: '2-point', 'cs' or '3-point' for numerical gradient evaluation (does not work in combination with all optimizers), dictionary (keys:tuple of variables, values:tequila objective) to define own gradient, None for automatic construction (default) initial_values: typing.Dict[typing.Hashable, numbers.Real], optional: Initial values as dictionary of Hashable types (variable keys) and floating point numbers. If given None they will all be set to zero variables: typing.List[typing.Hashable], optional: List of Variables to optimize samples: int, optional: samples/shots to take in every run of the quantum circuits (None activates full wavefunction simulation) maxiter: int : (Default value = 100): max iters to use. backend: str, optional: Simulator backend, will be automatically chosen if set to None backend_options: dict, optional: Additional options for the backend Will be unpacked and passed to the compiled objective in every call noise: NoiseModel, optional: a NoiseModel to apply to all expectation values in the objective. method: str : (Default = "BFGS"): Optimization method (see scipy documentation, or 'available methods') tol: float : (Default = 1.e-3): Convergence tolerance for optimization (see scipy documentation) method_options: dict, optional: Dictionary of options (see scipy documentation) method_bounds: typing.Dict[typing.Hashable, typing.Tuple[float, float]], optional: bounds for the variables (see scipy documentation) method_constraints: optional: (see scipy documentation silent: bool : No printout if True save_history: bool: Save the history throughout the optimization Returns ------- SciPyReturnType: the results of optimization """ if isinstance(gradient, dict) or hasattr(gradient, "items"): if all([isinstance(x, Objective) for x in gradient.values()]): gradient = format_variable_dictionary(gradient) if isinstance(hessian, dict) or hasattr(hessian, "items"): if all([isinstance(x, Objective) for x in hessian.values()]): hessian = {(assign_variable(k[0]), assign_variable([k[1]])): v for k, v in hessian.items()} method_bounds = format_variable_dictionary(method_bounds) # set defaults optimizer = optimize_scipy(save_history=save_history, maxiter=maxiter, method=method, method_options=method_options, method_bounds=method_bounds, method_constraints=method_constraints, silent=silent, backend=backend, backend_options=backend_options, device=device, samples=samples, noise_model=noise, tol=tol, *args, **kwargs) if initial_values is not None: initial_values = {assign_variable(k): v for k, v in initial_values.items()} return optimizer(Hamiltonian, unitary, gradient=gradient, hessian=hessian, initial_values=initial_values, variables=variables, *args, **kwargs)
24,489
42.732143
144
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_2.5/energy_optimization.py
import tequila as tq import numpy as np from tequila.objective.objective import Variable import openfermion from hacked_openfermion_qubit_operator import ParamQubitHamiltonian from typing import Union from vqe_utils import convert_PQH_to_tq_QH, convert_tq_QH_to_PQH,\ fold_unitary_into_hamiltonian from grad_hacked import grad from scipy_optimizer import minimize import scipy import random # guess we could substitute that with numpy.random #TODO import argparse import pickle as pk import sys sys.path.insert(0, '../../../') #sys.path.insert(0, '../') # This needs to be properly integrated somewhere else at some point # from tn_update.qq import contract_energy, optimize_wavefunctions from tn_update.my_mpo import * from tn_update.wfn_optimization import contract_energy_mpo, optimize_wavefunctions_mpo, initialize_wfns_randomly def energy_from_wfn_opti(hamiltonian: tq.QubitHamiltonian, n_qubits: int, guess_wfns=None, TOL=1e-4) -> tuple: ''' Get energy using a tensornetwork based method ~ power method (here as blackbox) ''' d = int(2**(n_qubits/2)) # Build MPO h_mpo = MyMPO(hamiltonian=hamiltonian, n_qubits=n_qubits, maxdim=500) h_mpo.make_mpo_from_hamiltonian() # Optimize wavefunctions based on random guess out = None it = 0 while out is None: # Set up random initial guesses for subsystems it += 1 if guess_wfns is None: psiL_rand = initialize_wfns_randomly(d, n_qubits//2) psiR_rand = initialize_wfns_randomly(d, n_qubits//2) else: psiL_rand = guess_wfns[0] psiR_rand = guess_wfns[1] out = optimize_wavefunctions_mpo(h_mpo, psiL_rand, psiR_rand, TOL=TOL, silent=True) energy_rand = out[0] optimal_wfns = [out[1], out[2]] return energy_rand, optimal_wfns def combine_two_clusters(H: tq.QubitHamiltonian, subsystems: list, circ_list: list) -> float: ''' E = nuc_rep + \sum_j c_j <0_A | U_A+ sigma_j|A U_A | 0_A><0_B | U_B+ sigma_j|B U_B | 0_B> i ) Split up Hamiltonian into vector c = [c_j], all sigmas of system A and system B ii ) Two vectors of ExpectationValues E_A=[E(U_A, sigma_j|A)], E_B=[E(U_B, sigma_j|B)] iii) Minimize vectors from ii) iv ) Perform weighted sum \sum_j c_[j] E_A[j] E_B[j] result = nuc_rep + iv) Finishing touch inspired by private tequila-repo / pair-separated objective This is still rather inefficient/unoptimized Can still prune out near-zero coefficients c_j ''' objective = 0.0 n_subsystems = len(subsystems) # Over all Paulistrings in the Hamiltonian for p_index, pauli in enumerate(H.paulistrings): # Gather coefficient coeff = pauli.coeff.real # Empty dictionary for operations: # to be filled with another dictionary per subsystem, where then # e.g. X(0)Z(1)Y(2)X(4) and subsystems=[[0,1,2],[3,4,5]] # -> ops={ 0: {0: 'X', 1: 'Z', 2: 'Y'}, 1: {4: 'X'} } ops = {} for s_index, sys in enumerate(subsystems): for k, v in pauli.items(): if k in sys: if s_index in ops: ops[s_index][k] = v else: ops[s_index] = {k: v} # If no ops gathered -> identity -> nuclear repulsion if len(ops) == 0: #print ("this should only happen ONCE") objective += coeff # If not just identity: # add objective += c_j * prod_subsys( < Paulistring_j_subsys >_{U_subsys} ) elif len(ops) > 0: obj_tmp = coeff for s_index, sys_pauli in ops.items(): #print (s_index, sys_pauli) H_tmp = QubitHamiltonian.from_paulistrings(PauliString(data=sys_pauli)) E_tmp = ExpectationValue(U=circ_list[s_index], H=H_tmp) obj_tmp *= E_tmp objective += obj_tmp initial_values = {k: 0.0 for k in objective.extract_variables()} random_initial_values = {k: 1e-2*np.random.uniform(-1, 1) for k in objective.extract_variables()} method = 'bfgs' # 'bfgs' # 'l-bfgs-b' # 'cobyla' # 'slsqp' curr_res = tq.minimize(method=method, objective=objective, initial_values=initial_values, gradient='two-point', backend='qulacs', method_options={"finite_diff_rel_step": 1e-3}) return curr_res.energy def energy_from_tq_qcircuit(hamiltonian: Union[tq.QubitHamiltonian, ParamQubitHamiltonian], n_qubits: int, circuit = Union[list, tq.QCircuit], subsystems: list = [[0,1,2,3,4,5]], initial_guess = None)-> tuple: ''' Get minimal energy using tequila ''' result = None # If only one circuit handed over, just run simple VQE if isinstance(circuit, list) and len(circuit) == 1: circuit = circuit[0] if isinstance(circuit, tq.QCircuit): if isinstance(hamiltonian, tq.QubitHamiltonian): E = tq.ExpectationValue(H=hamiltonian, U=circuit) if initial_guess is None: initial_angles = {k: 0.0 for k in E.extract_variables()} else: initial_angles = initial_guess #print ("optimizing non-param...") result = tq.minimize(objective=E, method='l-bfgs-b', silent=True, backend='qulacs', initial_values=initial_angles) #gradient='two-point', backend='qulacs', #method_options={"finite_diff_rel_step": 1e-4}) elif isinstance(hamiltonian, ParamQubitHamiltonian): if initial_guess is None: raise Exception("Need to provide initial guess for this to work.") initial_angles = None else: initial_angles = initial_guess #print ("optimizing param...") result = minimize(hamiltonian, circuit, method='bfgs', initial_values=initial_angles, backend="qulacs", silent=True) # If more circuits handed over, assume subsystems else: # TODO!! implement initial guess for the combine_two_clusters thing #print ("Should not happen for now...") result = combine_two_clusters(hamiltonian, subsystems, circuit) return result.energy, result.angles def mixed_optimization(hamiltonian: ParamQubitHamiltonian, n_qubits: int, initial_guess: Union[dict, list]=None, init_angles: list=None): ''' Minimizes energy using wfn opti and a parametrized Hamiltonian min_{psi, theta fixed} <psi | H(theta) | psi> --> min_{t, p fixed} <p | H(t) | p> ^---------------------------------------------------^ until convergence ''' energy, optimal_state = None, None H_qh = convert_PQH_to_tq_QH(hamiltonian) var_keys, H_derivs = H_qh._construct_derivatives() print("var keys", var_keys, flush=True) print('var dict', init_angles, flush=True) # if not init_angles: # var_vals = [0. for i in range(len(var_keys))] # initialize with 0 # else: # var_vals = init_angles def build_variable_dict(keys, values): assert(len(keys)==len(values)) out = dict() for idx, key in enumerate(keys): out[key] = complex(values[idx]) return out var_dict = init_angles var_vals = [*init_angles.values()] assert(build_variable_dict(var_keys, var_vals) == var_dict) def wrap_energy_eval(psi): ''' like energy_from_wfn_opti but instead of optimize get inner product ''' def energy_eval_fn(x): var_dict = build_variable_dict(var_keys, x) H_qh_fix = H_qh(var_dict) H_mpo = MyMPO(hamiltonian=H_qh_fix, n_qubits=n_qubits, maxdim=500) H_mpo.make_mpo_from_hamiltonian() return contract_energy_mpo(H_mpo, psi[0], psi[1]) return energy_eval_fn def wrap_gradient_eval(psi): ''' call derivatives with updated variable list ''' def gradient_eval_fn(x): variables = build_variable_dict(var_keys, x) deriv_expectations = H_derivs.values() # list of ParamQubitHamiltonian's deriv_qhs = [convert_PQH_to_tq_QH(d) for d in deriv_expectations] deriv_qhs = [d(variables) for d in deriv_qhs] # list of tq.QubitHamiltonian's # print(deriv_qhs) deriv_mpos = [MyMPO(hamiltonian=d, n_qubits=n_qubits, maxdim=500)\ for d in deriv_qhs] # print(deriv_mpos[0].n_qubits) for d in deriv_mpos: d.make_mpo_from_hamiltonian() # deriv_mpos = [d.make_mpo_from_hamiltonian() for d in deriv_mpos] return np.asarray([contract_energy_mpo(d, psi[0], psi[1]) for d in deriv_mpos]) return gradient_eval_fn def do_wfn_opti(values, guess_wfns, TOL): # H_qh = H_qh(H_vars) var_dict = build_variable_dict(var_keys, values) en, psi = energy_from_wfn_opti(H_qh(var_dict), n_qubits=n_qubits, guess_wfns=guess_wfns, TOL=TOL) return en, psi def do_param_opti(psi, x0): result = scipy.optimize.minimize(fun=wrap_energy_eval(psi), jac=wrap_gradient_eval(psi), method='bfgs', x0=x0, options={'maxiter': 4}) # print(result) return result e_prev, psi_prev = 123., None # print("iguess", initial_guess) e_curr, psi_curr = do_wfn_opti(var_vals, initial_guess, 1e-5) print('first eval', e_curr, flush=True) def converged(e_prev, e_curr, TOL=1e-4): return True if np.abs(e_prev-e_curr) < TOL else False it = 0 var_prev = var_vals print("vars before comp", var_prev, flush=True) while not converged(e_prev, e_curr) and it < 50: e_prev, psi_prev = e_curr, psi_curr # print('before param opti') res = do_param_opti(psi_curr, var_prev) var_curr = res['x'] print('curr vars', var_curr, flush=True) e_curr = res['fun'] print('en before wfn opti', e_curr, flush=True) # print("iiiiiguess", psi_prev) e_curr, psi_curr = do_wfn_opti(var_curr, psi_prev, 1e-3) print('en after wfn opti', e_curr, flush=True) it += 1 print('at iteration', it, flush=True) return e_curr, psi_curr # optimize parameters with fixed wavefunction # define/wrap energy function - given |p>, evaluate <p|H(t)|p> ''' def wrap_gradient(objective: typing.Union[Objective, QTensor], no_compile=False, *args, **kwargs): def gradient_fn(variable: Variable = None): return grad(objective: typing.Union[Objective, QTensor], variable: Variable = None, no_compile=False, *args, **kwargs) return grad_fn ''' def minimize_energy(hamiltonian: Union[ParamQubitHamiltonian, tq.QubitHamiltonian], n_qubits: int, type_energy_eval: str='wfn', cluster_circuit: tq.QCircuit=None, initial_guess=None, initial_mixed_angles: dict=None) -> float: ''' Minimizes energy functional either according a power-method inspired shortcut ('wfn') or using a unitary circuit ('qc') ''' if type_energy_eval == 'wfn': if isinstance(hamiltonian, tq.QubitHamiltonian): energy, optimal_state = energy_from_wfn_opti(hamiltonian, n_qubits, initial_guess) elif isinstance(hamiltonian, ParamQubitHamiltonian): init_angles = initial_mixed_angles energy, optimal_state = mixed_optimization(hamiltonian=hamiltonian, n_qubits=n_qubits, initial_guess=initial_guess, init_angles=init_angles) elif type_energy_eval == 'qc': if cluster_circuit is None: raise Exception("Need to hand over circuit!") energy, optimal_state = energy_from_tq_qcircuit(hamiltonian, n_qubits, cluster_circuit, [[0,1,2,3],[4,5,6,7]], initial_guess) else: raise Exception("Option not implemented!") return energy, optimal_state
12,457
43.021201
225
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_2.5/parallel_annealing.py
import tequila as tq import multiprocessing import copy from time import sleep from mutation_options import * from pathos.multiprocessing import ProcessingPool as Pool def evolve_population(hamiltonian, type_energy_eval, cluster_circuit, process_id, num_offsprings, actions_ratio, tasks, results): """ This function carries a single step of the simulated annealing on a single member of the generation args: process_id: A unique identifier for each process num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for mutations tasks: multiprocessing queue to pass family_id, instructions and current_fitness family_id: A unique identifier for each family instructions: An object consisting of the instructions in the quantum circuit current_fitness: Current fitness value of the circuit results: multiprocessing queue to pass results back """ #print('[%s] evaluation routine starts' % process_id) while True: try: #getting parameters for mutation and carrying it family_id, instructions, current_fitness = tasks.get() #check if patience has been exhausted if instructions.patience == 0: instructions.reset_to_best() best_child = 0 best_energy = current_fitness new_generations = {} for off_id in range(1, num_offsprings+1): scheduled_ratio = schedule_actions_ratio(epoch=0, steady_ratio=actions_ratio) action = get_action(scheduled_ratio) updated_instructions = copy.deepcopy(instructions) updated_instructions.update_by_action(action) new_fitness, wfn = evaluate_fitness(updated_instructions, hamiltonian, type_energy_eval, cluster_circuit) updated_instructions.set_reference_wfn(wfn) prob_acceptance = get_prob_acceptance(current_fitness, new_fitness, updated_instructions.T, updated_instructions.reference_energy) # need to figure out in case we have two equals new_generations[str(off_id)] = updated_instructions if best_energy > new_fitness: # now two equals -> "first one" is picked best_child = off_id best_energy = new_fitness # decision = np.random.binomial(1, prob_acceptance) # if decision == 0: if best_child == 0: # Add result to the queue instructions.patience -= 1 #print('Reduced patience -- now ' + str(updated_instructions.patience)) if instructions.patience == 0: if instructions.best_previous_instructions: instructions.reset_to_best() else: instructions.update_T() results.put((family_id, instructions, current_fitness)) else: # Add result to the queue if (best_energy < current_fitness): new_generations[str(best_child)].update_best_previous_instructions() new_generations[str(best_child)].update_T() results.put((family_id, new_generations[str(best_child)], best_energy)) except Exception as eeee: #print('[%s] evaluation routine quits' % process_id) #print(eeee) # Indicate finished results.put(-1) break return def evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, num_processors=4, type_energy_eval='wfn', cluster_circuit=None): """ This function does parallel mutation on all the members of the generation and updates the generation args: num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for sampling instructions_dict: A dictionary with the "Instructions" objects the corresponding fitness values as values num_processors: Number of processors to use for parallel run """ # Define IPC manager manager = multiprocessing.Manager() # Define a list (queue) for tasks and computation results tasks = manager.Queue() results = manager.Queue() processes = [] pool = Pool(processes=num_processors) for i in range(num_processors): process_id = 'P%i' % i # Create the process, and connect it to the worker function new_process = multiprocessing.Process(target=evolve_population, args=(hamiltonian, type_energy_eval, cluster_circuit, process_id, num_offsprings, actions_ratio, tasks, results)) # Add new process to the list of processes processes.append(new_process) # Start the process new_process.start() #print("putting tasks") for family_id in instructions_dict: single_task = (family_id, instructions_dict[family_id][0], instructions_dict[family_id][1]) tasks.put(single_task) # Wait while the workers process - change it to something for our case later # sleep(5) multiprocessing.Barrier(num_processors) #print("after barrier") # Quit the worker processes by sending them -1 for i in range(num_processors): tasks.put(-1) # Read calculation results num_finished_processes = 0 while True: # Read result #print("num fin", num_finished_processes) try: family_id, updated_instructions, new_fitness = results.get() instructions_dict[family_id] = (updated_instructions, new_fitness) except: # Process has finished num_finished_processes += 1 if num_finished_processes == num_processors: break for process in processes: process.join() pool.close()
6,456
38.371951
146
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_2.5/single_thread_annealing.py
import tequila as tq import copy from mutation_options import * def st_evolve_population(hamiltonian, type_energy_eval, cluster_circuit, num_offsprings, actions_ratio, tasks): """ This function carries a single step of the simulated annealing on a single member of the generation args: num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for mutations tasks: a tuple of (family_id, instructions and current_fitness) family_id: A unique identifier for each family instructions: An object consisting of the instructions in the quantum circuit current_fitness: Current fitness value of the circuit """ family_id, instructions, current_fitness = tasks #check if patience has been exhausted if instructions.patience == 0: if instructions.best_previous_instructions: instructions.reset_to_best() best_child = 0 best_energy = current_fitness new_generations = {} for off_id in range(1, num_offsprings+1): scheduled_ratio = schedule_actions_ratio(epoch=0, steady_ratio=actions_ratio) action = get_action(scheduled_ratio) updated_instructions = copy.deepcopy(instructions) updated_instructions.update_by_action(action) new_fitness, wfn = evaluate_fitness(updated_instructions, hamiltonian, type_energy_eval, cluster_circuit) updated_instructions.set_reference_wfn(wfn) prob_acceptance = get_prob_acceptance(current_fitness, new_fitness, updated_instructions.T, updated_instructions.reference_energy) # need to figure out in case we have two equals new_generations[str(off_id)] = updated_instructions if best_energy > new_fitness: # now two equals -> "first one" is picked best_child = off_id best_energy = new_fitness # decision = np.random.binomial(1, prob_acceptance) # if decision == 0: if best_child == 0: # Add result to the queue instructions.patience -= 1 #print('Reduced patience -- now ' + str(updated_instructions.patience)) if instructions.patience == 0: if instructions.best_previous_instructions: instructions.reset_to_best() else: instructions.update_T() results = ((family_id, instructions, current_fitness)) else: # Add result to the queue if (best_energy < current_fitness): new_generations[str(best_child)].update_best_previous_instructions() new_generations[str(best_child)].update_T() results = ((family_id, new_generations[str(best_child)], best_energy)) return results def st_evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, type_energy_eval='wfn', cluster_circuit=None): """ This function does a single threas mutation on all the members of the generation and updates the generation args: num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for sampling instructions_dict: A dictionary with the "Instructions" objects the corresponding fitness values as values """ for family_id in instructions_dict: task = (family_id, instructions_dict[family_id][0], instructions_dict[family_id][1]) results = st_evolve_population(hamiltonian, type_energy_eval, cluster_circuit, num_offsprings, actions_ratio, task) family_id, updated_instructions, new_fitness = results instructions_dict[family_id] = (updated_instructions, new_fitness)
4,005
40.298969
138
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_2.5/mutation_options.py
import argparse import numpy as np import random import copy import tequila as tq from typing import Union from collections import Counter from time import time from vqe_utils import convert_PQH_to_tq_QH, convert_tq_QH_to_PQH,\ fold_unitary_into_hamiltonian from energy_optimization import minimize_energy global_seed = 1 class Instructions: ''' TODO need to put some documentation here ''' def __init__(self, n_qubits, mu=2.0, sigma=0.4, alpha=0.9, T_0=1.0, beta=0.5, patience=10, max_non_cliffords=0, reference_energy=0., number=None): # hardcoded values for now self.num_non_cliffords = 0 self.max_non_cliffords = max_non_cliffords # ------------------------ self.starting_patience = patience self.patience = patience self.mu = mu self.sigma = sigma self.alpha = alpha self.beta = beta self.T_0 = T_0 self.T = T_0 self.gates = self.get_random_gates(number=number) self.n_qubits = n_qubits self.positions = self.get_random_positions() self.best_previous_instructions = {} self.reference_energy = reference_energy self.best_reference_wfn = None self.noncliff_replacements = {} def _str(self): print(self.gates) print(self.positions) def set_reference_wfn(self, reference_wfn): self.best_reference_wfn = reference_wfn def update_T(self, update_type: str = 'regular', best_temp=None): # Regular update if update_type.lower() == 'regular': self.T = self.alpha * self.T # Temperature update if patience ran out elif update_type.lower() == 'patience': self.T = self.beta*best_temp + (1-self.beta)*self.T_0 def get_random_gates(self, number=None): ''' Randomly generates a list of gates. number indicates the number of gates to generate otherwise, number will be drawn from a log normal distribution ''' mu, sigma = self.mu, self.sigma full_options = ['X','Y','Z','S','H','CX', 'CY', 'CZ','SWAP', 'UCC2c', 'UCC4c', 'UCC2', 'UCC4'] clifford_options = ['X','Y','Z','S','H','CX', 'CY', 'CZ','SWAP', 'UCC2c', 'UCC4c'] #non_clifford_options = ['UCC2', 'UCC4'] # Gate distribution, selecting number of gates to add k = np.random.lognormal(mu, sigma) k = np.int(k) if number is not None: k = number # Selecting gate types gates = None if self.num_non_cliffords < self.max_non_cliffords: gates = random.choices(full_options, k=k) # with replacement else: gates = random.choices(clifford_options, k=k) new_num_non_cliffords = 0 if "UCC2" in gates: new_num_non_cliffords += Counter(gates)["UCC2"] if "UCC4" in gates: new_num_non_cliffords += Counter(gates)["UCC4"] if (new_num_non_cliffords+self.num_non_cliffords) <= self.max_non_cliffords: self.num_non_cliffords += new_num_non_cliffords else: extra_cliffords = (new_num_non_cliffords+self.num_non_cliffords) - self.max_non_cliffords assert(extra_cliffords >= 0) new_gates = random.choices(clifford_options, k=extra_cliffords) for g in new_gates: try: gates[gates.index("UCC4")] = g except: gates[gates.index("UCC2")] = g self.num_non_cliffords = self.max_non_cliffords if k == 1: if gates == "UCC2c" or gates == "UCC4c": gates = get_string_Cliff_ucc(gates) if gates == "UCC2" or gates == "UCC4": gates = get_string_ucc(gates) else: for ind, gate in enumerate(gates): if gate == "UCC2c" or gate == "UCC4c": gates[ind] = get_string_Cliff_ucc(gate) if gate == "UCC2" or gate == "UCC4": gates[ind] = get_string_ucc(gate) return gates def get_random_positions(self, gates=None): ''' Randomly assign gates to qubits. ''' if gates is None: gates = self.gates n_qubits = self.n_qubits single_qubit = ['X','Y','Z','S','H'] # two_qubit = ['CX','CY','CZ', 'SWAP'] two_qubit = ['CX', 'CY', 'CZ', 'SWAP', 'UCC2c', 'UCC2'] four_qubit = ['UCC4c', 'UCC4'] qubits = list(range(0, n_qubits)) q_positions = [] for gate in gates: if gate in four_qubit: p = random.sample(qubits, k=4) if gate in two_qubit: p = random.sample(qubits, k=2) if gate in single_qubit: p = random.sample(qubits, k=1) if "UCC2" in gate: p = random.sample(qubits, k=2) if "UCC4" in gate: p = random.sample(qubits, k=4) q_positions.append(p) return q_positions def delete(self, number=None): ''' Randomly drops some gates from a clifford instruction set if not specified, the number of gates to drop is sampled from a uniform distribution over all the gates ''' gates = copy.deepcopy(self.gates) positions = copy.deepcopy(self.positions) n_qubits = self.n_qubits if number is not None: num_to_drop = number else: num_to_drop = random.sample(range(1,len(gates)-1), k=1)[0] action_indices = random.sample(range(0,len(gates)-1), k=num_to_drop) for index in sorted(action_indices, reverse=True): if "UCC2_" in str(gates[index]) or "UCC4_" in str(gates[index]): self.num_non_cliffords -= 1 del gates[index] del positions[index] self.gates = gates self.positions = positions #print ('deleted {} gates'.format(num_to_drop)) def add(self, number=None): ''' adds a random selection of clifford gates to the end of a clifford instruction set if number is not specified, the number of gates to add will be drawn from a log normal distribution ''' gates = copy.deepcopy(self.gates) positions = copy.deepcopy(self.positions) n_qubits = self.n_qubits added_instructions = self.get_new_instructions(number=number) gates.extend(added_instructions['gates']) positions.extend(added_instructions['positions']) self.gates = gates self.positions = positions #print ('added {} gates'.format(len(added_instructions['gates']))) def change(self, number=None): ''' change a random number of gates and qubit positions in a clifford instruction set if not specified, the number of gates to change is sampled from a uniform distribution over all the gates ''' gates = copy.deepcopy(self.gates) positions = copy.deepcopy(self.positions) n_qubits = self.n_qubits if number is not None: num_to_change = number else: num_to_change = random.sample(range(1,len(gates)), k=1)[0] action_indices = random.sample(range(0,len(gates)-1), k=num_to_change) added_instructions = self.get_new_instructions(number=num_to_change) for i in range(num_to_change): gates[action_indices[i]] = added_instructions['gates'][i] positions[action_indices[i]] = added_instructions['positions'][i] self.gates = gates self.positions = positions #print ('changed {} gates'.format(len(added_instructions['gates']))) # TODO to be debugged! def prune(self): ''' Prune instructions to remove redundant operations: --> first gate should go beyond subsystems (this assumes expressible enough subsystem-ciruits #TODO later -> this needs subsystem information in here! --> 2 subsequent gates that are their respective inverse can be removed #TODO this might change the number of qubits acted on in theory? ''' pass #print ("DEBUG PRUNE FUNCTION!") # gates = copy.deepcopy(self.gates) # positions = copy.deepcopy(self.positions) # for g_index in range(len(gates)-1): # if (gates[g_index] == gates[g_index+1] and not 'S' in gates[g_index])\ # or (gates[g_index] == 'S' and gates[g_index+1] == 'S-dag')\ # or (gates[g_index] == 'S-dag' and gates[g_index+1] == 'S'): # print(len(gates)) # if positions[g_index] == positions[g_index+1]: # self.gates.pop(g_index) # self.positions.pop(g_index) def update_by_action(self, action: str): ''' Updates instruction dictionary -> Either adds, deletes or changes gates ''' if action == 'delete': try: self.delete() # In case there are too few gates to delete except: pass elif action == 'add': self.add() elif action == 'change': self.change() else: raise Exception("Unknown action type " + action + ".") self.prune() def update_best_previous_instructions(self): ''' Overwrites the best previous instructions with the current ones. ''' self.best_previous_instructions['gates'] = copy.deepcopy(self.gates) self.best_previous_instructions['positions'] = copy.deepcopy(self.positions) self.best_previous_instructions['T'] = copy.deepcopy(self.T) def reset_to_best(self): ''' Overwrites the current instructions with best previous ones. ''' #print ('Patience ran out... resetting to best previous instructions.') self.gates = copy.deepcopy(self.best_previous_instructions['gates']) self.positions = copy.deepcopy(self.best_previous_instructions['positions']) self.patience = copy.deepcopy(self.starting_patience) self.update_T(update_type='patience', best_temp=copy.deepcopy(self.best_previous_instructions['T'])) def get_new_instructions(self, number=None): ''' Returns a a clifford instruction set, a dictionary of gates and qubit positions for building a clifford circuit ''' mu = self.mu sigma = self.sigma n_qubits = self.n_qubits instruction = {} gates = self.get_random_gates(number=number) q_positions = self.get_random_positions(gates) assert(len(q_positions) == len(gates)) instruction['gates'] = gates instruction['positions'] = q_positions # instruction['n_qubits'] = n_qubits # instruction['patience'] = patience # instruction['best_previous_options'] = {} return instruction def replace_cg_w_ncg(self, gate_id): ''' replaces a set of Clifford gates with corresponding non-Cliffords ''' print("gates before", self.gates, flush=True) gate = self.gates[gate_id] if gate == 'X': gate = "Rx" elif gate == 'Y': gate = "Ry" elif gate == 'Z': gate = "Rz" elif gate == 'S': gate = "S_nc" #gate = "Rz" elif gate == 'H': gate = "H_nc" # this does not work??????? # gate = "Ry" elif gate == 'CX': gate = "CRx" elif gate == 'CY': gate = "CRy" elif gate == 'CZ': gate = "CRz" elif gate == 'SWAP':#find a way to change this as well pass # gate = "SWAP" elif "UCC2c" in str(gate): pre_gate = gate.split("_")[0] mid_gate = gate.split("_")[-1] gate = pre_gate + "_" + "UCC2" + "_" +mid_gate elif "UCC4c" in str(gate): pre_gate = gate.split("_")[0] mid_gate = gate.split("_")[-1] gate = pre_gate + "_" + "UCC4" + "_" + mid_gate self.gates[gate_id] = gate print("gates after", self.gates, flush=True) def build_circuit(instructions): ''' constructs a tequila circuit from a clifford instruction set ''' gates = instructions.gates q_positions = instructions.positions init_angles = {} clifford_circuit = tq.QCircuit() # for i in range(1, len(gates)): # TODO len(q_positions) not == len(gates) for i in range(len(gates)): if len(q_positions[i]) == 2: q1, q2 = q_positions[i] elif len(q_positions[i]) == 1: q1 = q_positions[i] q2 = None elif not len(q_positions[i]) == 4: raise Exception("q_positions[i] must have length 1, 2 or 4...") if gates[i] == 'X': clifford_circuit += tq.gates.X(q1) if gates[i] == 'Y': clifford_circuit += tq.gates.Y(q1) if gates[i] == 'Z': clifford_circuit += tq.gates.Z(q1) if gates[i] == 'S': clifford_circuit += tq.gates.S(q1) if gates[i] == 'H': clifford_circuit += tq.gates.H(q1) if gates[i] == 'CX': clifford_circuit += tq.gates.CX(q1, q2) if gates[i] == 'CY': #using generators clifford_circuit += tq.gates.S(q2) clifford_circuit += tq.gates.CX(q1, q2) clifford_circuit += tq.gates.S(q2).dagger() if gates[i] == 'CZ': #using generators clifford_circuit += tq.gates.H(q2) clifford_circuit += tq.gates.CX(q1, q2) clifford_circuit += tq.gates.H(q2) if gates[i] == 'SWAP': clifford_circuit += tq.gates.CX(q1, q2) clifford_circuit += tq.gates.CX(q2, q1) clifford_circuit += tq.gates.CX(q1, q2) if "UCC2c" in str(gates[i]) or "UCC4c" in str(gates[i]): clifford_circuit += get_clifford_UCC_circuit(gates[i], q_positions[i]) # NON-CLIFFORD STUFF FROM HERE ON global global_seed if gates[i] == "S_nc": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.S(q1) clifford_circuit += tq.gates.Rz(angle=var_name, target=q1) if gates[i] == "H_nc": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.H(q1) clifford_circuit += tq.gates.Ry(angle=var_name, target=q1) if gates[i] == "Rx": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.X(q1) clifford_circuit += tq.gates.Rx(angle=var_name, target=q1) if gates[i] == "Ry": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.Y(q1) clifford_circuit += tq.gates.Ry(angle=var_name, target=q1) if gates[i] == "Rz": global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0 clifford_circuit += tq.gates.Z(q1) clifford_circuit += tq.gates.Rz(angle=var_name, target=q1) if gates[i] == "CRx": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = np.pi clifford_circuit += tq.gates.Rx(angle=var_name, target=q2, control=q1) if gates[i] == "CRy": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = np.pi clifford_circuit += tq.gates.Ry(angle=var_name, target=q2, control=q1) if gates[i] == "CRz": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = np.pi clifford_circuit += tq.gates.Rz(angle=var_name, target=q2, control=q1) def get_ucc_init_angles(gate): angle = None pre_gate = gate.split("_")[0] mid_gate = gate.split("_")[-1] if mid_gate == 'Z': angle = 0. elif mid_gate == 'S': angle = 0. elif mid_gate == 'S-dag': angle = 0. else: raise Exception("This should not happen -- center/mid gate should be Z,S,S_dag.") return angle if "UCC2_" in str(gates[i]) or "UCC4_" in str(gates[i]): uccc_circuit = get_non_clifford_UCC_circuit(gates[i], q_positions[i]) clifford_circuit += uccc_circuit try: var_name = uccc_circuit.extract_variables()[0] init_angles[var_name]= get_ucc_init_angles(gates[i]) except: init_angles = {} return clifford_circuit, init_angles def get_non_clifford_UCC_circuit(gate, positions): """ """ pre_cir_dic = {"X":tq.gates.X, "Y":tq.gates.Y, "H":tq.gates.H, "I":None} pre_gate = gate.split("_")[0] pre_gates = pre_gate.split(*"#") pre_circuit = tq.QCircuit() for i, pos in enumerate(positions): try: pre_circuit += pre_cir_dic[pre_gates[i]](pos) except: pass for i, pos in enumerate(positions[:-1]): pre_circuit += tq.gates.CX(pos, positions[i+1]) global global_seed mid_gate = gate.split("_")[-1] mid_circuit = tq.QCircuit() if mid_gate == "S": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit += tq.gates.S(positions[-1]) mid_circuit += tq.gates.Rz(angle=tq.Variable(var_name), target=positions[-1]) elif mid_gate == "S-dag": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit += tq.gates.S(positions[-1]).dagger() mid_circuit += tq.gates.Rz(angle=tq.Variable(var_name), target=positions[-1]) elif mid_gate == "Z": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit += tq.gates.Z(positions[-1]) mid_circuit += tq.gates.Rz(angle=tq.Variable(var_name), target=positions[-1]) return pre_circuit + mid_circuit + pre_circuit.dagger() def get_string_Cliff_ucc(gate): """ this function randomly sample basis change and mid circuit elements for a ucc-type clifford circuit and adds it to the gate """ pre_circ_comp = ["X", "Y", "H", "I"] mid_circ_comp = ["S", "S-dag", "Z"] p = None if "UCC2c" in gate: p = random.sample(pre_circ_comp, k=2) elif "UCC4c" in gate: p = random.sample(pre_circ_comp, k=4) pre_gate = "#".join([str(item) for item in p]) mid_gate = random.sample(mid_circ_comp, k=1)[0] return str(pre_gate + "_" + gate + "_" + mid_gate) def get_string_ucc(gate): """ this function randomly sample basis change and mid circuit elements for a ucc-type clifford circuit and adds it to the gate """ pre_circ_comp = ["X", "Y", "H", "I"] p = None if "UCC2" in gate: p = random.sample(pre_circ_comp, k=2) elif "UCC4" in gate: p = random.sample(pre_circ_comp, k=4) pre_gate = "#".join([str(item) for item in p]) mid_gate = str(random.random() * 2 * np.pi) return str(pre_gate + "_" + gate + "_" + mid_gate) def get_clifford_UCC_circuit(gate, positions): """ This function creates an approximate UCC excitation circuit using only clifford Gates """ #pre_circ_comp = ["X", "Y", "H", "I"] pre_cir_dic = {"X":tq.gates.X, "Y":tq.gates.Y, "H":tq.gates.H, "I":None} pre_gate = gate.split("_")[0] pre_gates = pre_gate.split(*"#") #pre_gates = [] #if gate == "UCC2": # pre_gates = random.choices(pre_circ_comp, k=2) #if gate == "UCC4": # pre_gates = random.choices(pre_circ_comp, k=4) pre_circuit = tq.QCircuit() for i, pos in enumerate(positions): try: pre_circuit += pre_cir_dic[pre_gates[i]](pos) except: pass for i, pos in enumerate(positions[:-1]): pre_circuit += tq.gates.CX(pos, positions[i+1]) #mid_circ_comp = ["S", "S-dag", "Z"] #mid_gate = random.sample(mid_circ_comp, k=1)[0] mid_gate = gate.split("_")[-1] mid_circuit = tq.QCircuit() if mid_gate == "S": mid_circuit += tq.gates.S(positions[-1]) elif mid_gate == "S-dag": mid_circuit += tq.gates.S(positions[-1]).dagger() elif mid_gate == "Z": mid_circuit += tq.gates.Z(positions[-1]) return pre_circuit + mid_circuit + pre_circuit.dagger() def get_UCC_circuit(gate, positions): """ This function creates an UCC excitation circuit """ #pre_circ_comp = ["X", "Y", "H", "I"] pre_cir_dic = {"X":tq.gates.X, "Y":tq.gates.Y, "H":tq.gates.H, "I":None} pre_gate = gate.split("_")[0] pre_gates = pre_gate.split(*"#") pre_circuit = tq.QCircuit() for i, pos in enumerate(positions): try: pre_circuit += pre_cir_dic[pre_gates[i]](pos) except: pass for i, pos in enumerate(positions[:-1]): pre_circuit += tq.gates.CX(pos, positions[i+1]) mid_gate_val = gate.split("_")[-1] global global_seed np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit = tq.gates.Rz(target=positions[-1], angle=tq.Variable(var_name)) # mid_circ_comp = ["S", "S-dag", "Z"] # mid_gate = random.sample(mid_circ_comp, k=1)[0] # mid_circuit = tq.QCircuit() # if mid_gate == "S": # mid_circuit += tq.gates.S(positions[-1]) # elif mid_gate == "S-dag": # mid_circuit += tq.gates.S(positions[-1]).dagger() # elif mid_gate == "Z": # mid_circuit += tq.gates.Z(positions[-1]) return pre_circuit + mid_circuit + pre_circuit.dagger() def schedule_actions_ratio(epoch: int, action_options: list = ['delete', 'change', 'add'], decay: int = 30, steady_ratio: Union[tuple, list] = [0.2, 0.6, 0.2]) -> list: delete, change, add = tuple(steady_ratio) actions_ratio = [] for action in action_options: if action == 'delete': actions_ratio += [ delete*(1-np.exp(-1*epoch / decay)) ] elif action == 'change': actions_ratio += [ change*(1-np.exp(-1*epoch / decay)) ] elif action == 'add': actions_ratio += [ (1-add)*np.exp(-1*epoch / decay) + add ] else: print('Action type ', action, ' not defined!') # unnecessary for current schedule # if not np.isclose(np.sum(actions_ratio), 1.0): # actions_ratio /= np.sum(actions_ratio) return actions_ratio def get_action(ratio: list = [0.20,0.60,0.20]): ''' randomly chooses an action from delete, change, add ratio denotes the multinomial probabilities ''' choice = np.random.multinomial(n=1, pvals = ratio, size = 1) index = np.where(choice[0] == 1) action_options = ['delete', 'change', 'add'] action = action_options[index[0].item()] return action def get_prob_acceptance(E_curr, E_prev, T, reference_energy): ''' Computes acceptance probability of a certain action based on change in energy ''' delta_E = E_curr - E_prev prob = 0 if delta_E < 0 and E_curr < reference_energy: prob = 1 else: if E_curr < reference_energy: prob = np.exp(-delta_E/T) else: prob = 0 return prob def perform_folding(hamiltonian, circuit): # QubitHamiltonian -> ParamQubitHamiltonian param_hamiltonian = convert_tq_QH_to_PQH(hamiltonian) gates = circuit.gates # Go backwards gates.reverse() for gate in gates: # print("\t folding", gate) param_hamiltonian = (fold_unitary_into_hamiltonian(gate, param_hamiltonian)) # hamiltonian = convert_PQH_to_tq_QH(param_hamiltonian)() hamiltonian = param_hamiltonian return hamiltonian def evaluate_fitness(instructions, hamiltonian: tq.QubitHamiltonian, type_energy_eval: str, cluster_circuit: tq.QCircuit=None) -> tuple: ''' Evaluates fitness=objective=energy given a system for a set of instructions ''' #print ("evaluating fitness") n_qubits = instructions.n_qubits clifford_circuit, init_angles = build_circuit(instructions) # tq.draw(clifford_circuit, backend="cirq") ## TODO check if cluster_circuit is parametrized t0 = time() t1 = None folded_hamiltonian = perform_folding(hamiltonian, clifford_circuit) t1 = time() #print ("\tfolding took ", t1-t0) parametrized = len(clifford_circuit.extract_variables()) > 0 initial_guess = None if not parametrized: folded_hamiltonian = (convert_PQH_to_tq_QH(folded_hamiltonian))() elif parametrized: # TODO clifford_circuit is both ref + rest; so nomenclature is shit here variables = [gate.extract_variables() for gate in clifford_circuit.gates\ if gate.extract_variables()] variables = np.array(variables).flatten().tolist() # TODO this initial_guess is absolutely useless rn and is just causing problems if called initial_guess = { k: 0.1 for k in variables } if instructions.best_reference_wfn is not None: initial_guess = instructions.best_reference_wfn E_new, optimal_state = minimize_energy(hamiltonian=folded_hamiltonian, n_qubits=n_qubits, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit, initial_guess=initial_guess,\ initial_mixed_angles=init_angles) t2 = time() #print ("evaluated fitness; comp was ", t2-t1) #print ("current fitness: ", E_new) return E_new, optimal_state
26,497
34.096689
191
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_2.5/hacked_openfermion_qubit_operator.py
import tequila as tq import sympy import copy #from param_hamiltonian import get_geometry, generate_ucc_ansatz from hacked_openfermion_symbolic_operator import SymbolicOperator # Define products of all Pauli operators for symbolic multiplication. _PAULI_OPERATOR_PRODUCTS = { ('I', 'I'): (1., 'I'), ('I', 'X'): (1., 'X'), ('X', 'I'): (1., 'X'), ('I', 'Y'): (1., 'Y'), ('Y', 'I'): (1., 'Y'), ('I', 'Z'): (1., 'Z'), ('Z', 'I'): (1., 'Z'), ('X', 'X'): (1., 'I'), ('Y', 'Y'): (1., 'I'), ('Z', 'Z'): (1., 'I'), ('X', 'Y'): (1.j, 'Z'), ('X', 'Z'): (-1.j, 'Y'), ('Y', 'X'): (-1.j, 'Z'), ('Y', 'Z'): (1.j, 'X'), ('Z', 'X'): (1.j, 'Y'), ('Z', 'Y'): (-1.j, 'X') } _clifford_h_products = { ('I') : (1., 'I'), ('X') : (1., 'Z'), ('Y') : (-1., 'Y'), ('Z') : (1., 'X') } _clifford_s_products = { ('I') : (1., 'I'), ('X') : (-1., 'Y'), ('Y') : (1., 'X'), ('Z') : (1., 'Z') } _clifford_s_dag_products = { ('I') : (1., 'I'), ('X') : (1., 'Y'), ('Y') : (-1., 'X'), ('Z') : (1., 'Z') } _clifford_cx_products = { ('I', 'I'): (1., 'I', 'I'), ('I', 'X'): (1., 'I', 'X'), ('I', 'Y'): (1., 'Z', 'Y'), ('I', 'Z'): (1., 'Z', 'Z'), ('X', 'I'): (1., 'X', 'X'), ('X', 'X'): (1., 'X', 'I'), ('X', 'Y'): (1., 'Y', 'Z'), ('X', 'Z'): (-1., 'Y', 'Y'), ('Y', 'I'): (1., 'Y', 'X'), ('Y', 'X'): (1., 'Y', 'I'), ('Y', 'Y'): (-1., 'X', 'Z'), ('Y', 'Z'): (1., 'X', 'Y'), ('Z', 'I'): (1., 'Z', 'I'), ('Z', 'X'): (1., 'Z', 'X'), ('Z', 'Y'): (1., 'I', 'Y'), ('Z', 'Z'): (1., 'I', 'Z'), } _clifford_cy_products = { ('I', 'I'): (1., 'I', 'I'), ('I', 'X'): (1., 'Z', 'X'), ('I', 'Y'): (1., 'I', 'Y'), ('I', 'Z'): (1., 'Z', 'Z'), ('X', 'I'): (1., 'X', 'Y'), ('X', 'X'): (-1., 'Y', 'Z'), ('X', 'Y'): (1., 'X', 'I'), ('X', 'Z'): (-1., 'Y', 'X'), ('Y', 'I'): (1., 'Y', 'Y'), ('Y', 'X'): (1., 'X', 'Z'), ('Y', 'Y'): (1., 'Y', 'I'), ('Y', 'Z'): (-1., 'X', 'X'), ('Z', 'I'): (1., 'Z', 'I'), ('Z', 'X'): (1., 'I', 'X'), ('Z', 'Y'): (1., 'Z', 'Y'), ('Z', 'Z'): (1., 'I', 'Z'), } _clifford_cz_products = { ('I', 'I'): (1., 'I', 'I'), ('I', 'X'): (1., 'Z', 'X'), ('I', 'Y'): (1., 'Z', 'Y'), ('I', 'Z'): (1., 'I', 'Z'), ('X', 'I'): (1., 'X', 'Z'), ('X', 'X'): (-1., 'Y', 'Y'), ('X', 'Y'): (-1., 'Y', 'X'), ('X', 'Z'): (1., 'X', 'I'), ('Y', 'I'): (1., 'Y', 'Z'), ('Y', 'X'): (-1., 'X', 'Y'), ('Y', 'Y'): (1., 'X', 'X'), ('Y', 'Z'): (1., 'Y', 'I'), ('Z', 'I'): (1., 'Z', 'I'), ('Z', 'X'): (1., 'I', 'X'), ('Z', 'Y'): (1., 'I', 'Y'), ('Z', 'Z'): (1., 'Z', 'Z'), } COEFFICIENT_TYPES = (int, float, complex, sympy.Expr, tq.Variable) class ParamQubitHamiltonian(SymbolicOperator): @property def actions(self): """The allowed actions.""" return ('X', 'Y', 'Z') @property def action_strings(self): """The string representations of the allowed actions.""" return ('X', 'Y', 'Z') @property def action_before_index(self): """Whether action comes before index in string representations.""" return True @property def different_indices_commute(self): """Whether factors acting on different indices commute.""" return True def renormalize(self): """Fix the trace norm of an operator to 1""" norm = self.induced_norm(2) if numpy.isclose(norm, 0.0): raise ZeroDivisionError('Cannot renormalize empty or zero operator') else: self /= norm def _simplify(self, term, coefficient=1.0): """Simplify a term using commutator and anti-commutator relations.""" if not term: return coefficient, term term = sorted(term, key=lambda factor: factor[0]) new_term = [] left_factor = term[0] for right_factor in term[1:]: left_index, left_action = left_factor right_index, right_action = right_factor # Still on the same qubit, keep simplifying. if left_index == right_index: new_coefficient, new_action = _PAULI_OPERATOR_PRODUCTS[ left_action, right_action] left_factor = (left_index, new_action) coefficient *= new_coefficient # Reached different qubit, save result and re-initialize. else: if left_action != 'I': new_term.append(left_factor) left_factor = right_factor # Save result of final iteration. if left_factor[1] != 'I': new_term.append(left_factor) return coefficient, tuple(new_term) def _clifford_simplify_h(self, qubit): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 for left, right in term: if left == qubit: coeff, new_pauli = _clifford_h_products[right] new_term.append(tuple((left, new_pauli))) else: new_term.append(tuple((left,right))) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self def _clifford_simplify_s(self, qubit): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 for left, right in term: if left == qubit: coeff, new_pauli = _clifford_s_products[right] new_term.append(tuple((left, new_pauli))) else: new_term.append(tuple((left,right))) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self def _clifford_simplify_s_dag(self, qubit): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 for left, right in term: if left == qubit: coeff, new_pauli = _clifford_s_dag_products[right] new_term.append(tuple((left, new_pauli))) else: new_term.append(tuple((left,right))) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self def _clifford_simplify_control_g(self, axis, control_q, target_q): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 target = "I" control = "I" for left, right in term: if left == control_q: control = right elif left == target_q: target = right else: new_term.append(tuple((left,right))) new_c = "I" new_t = "I" if not (target == "I" and control == "I"): if axis == "X": coeff, new_c, new_t = _clifford_cx_products[control, target] if axis == "Y": coeff, new_c, new_t = _clifford_cy_products[control, target] if axis == "Z": coeff, new_c, new_t = _clifford_cz_products[control, target] if new_c != "I": new_term.append(tuple((control_q, new_c))) if new_t != "I": new_term.append(tuple((target_q, new_t))) new_term = sorted(new_term, key=lambda factor: factor[0]) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self if __name__ == "__main__": """geometry = get_geometry("H2", 0.714) print(geometry) basis_set = 'sto-3g' ref_anz, uccsd_anz, ham = generate_ucc_ansatz(geometry, basis_set) print(ham) b_ham = tq.grouping.binary_rep.BinaryHamiltonian.init_from_qubit_hamiltonian(ham) c_ham = tq.grouping.binary_rep.BinaryHamiltonian.init_from_qubit_hamiltonian(ham) print(b_ham) print(b_ham.get_binary()) print(b_ham.get_coeff()) param = uccsd_anz.extract_variables() print(param) for term in b_ham.binary_terms: print(term.coeff) term.set_coeff(param[0]) print(term.coeff) print(b_ham.get_coeff()) d_ham = c_ham.to_qubit_hamiltonian() + b_ham.to_qubit_hamiltonian() """ term = [(2,'X'), (0,'Y'), (3, 'Z')] coeff = tq.Variable("a") coeff = coeff *2.j print(coeff) print(type(coeff)) print(coeff({"a":1})) ham = ParamQubitHamiltonian(term= term, coefficient=coeff) print(ham.terms) print(str(ham)) for term in ham.terms: print(ham.terms[term]({"a":1,"b":2})) term = [(2,'X'), (0,'Z'), (3, 'Z')] coeff = tq.Variable("b") print(coeff({"b":1})) b_ham = ParamQubitHamiltonian(term= term, coefficient=coeff) print(b_ham.terms) print(str(b_ham)) for term in b_ham.terms: print(b_ham.terms[term]({"a":1,"b":2})) coeff = tq.Variable("a")*tq.Variable("b") print(coeff) print(coeff({"a":1,"b":2})) ham *= b_ham print(ham.terms) print(str(ham)) for term in ham.terms: coeff = (ham.terms[term]) print(coeff) print(coeff({"a":1,"b":2})) ham = ham*2. print(ham.terms) print(str(ham))
9,918
29.614198
85
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_2.5/HEA.py
import tequila as tq import numpy as np from tequila import gates as tq_g from tequila.objective.objective import Variable def generate_HEA(num_qubits, circuit_id=11, num_layers=1): """ This function generates different types of hardware efficient circuits as in this paper https://onlinelibrary.wiley.com/doi/full/10.1002/qute.201900070 param: num_qubits (int) -> the number of qubits in the circuit param: circuit_id (int) -> the type of hardware efficient circuit param: num_layers (int) -> the number of layers of the HEA input: num_qubits -> 4 circuit_id -> 11 num_layers -> 1 returns: ansatz (tq.QCircuit()) -> a circuit as shown below 0: ───Ry(0.318309886183791*pi*f((y0,))_0)───Rz(0.318309886183791*pi*f((z0,))_1)───@───────────────────────────────────────────────────────────────────────────────────── │ 1: ───Ry(0.318309886183791*pi*f((y1,))_2)───Rz(0.318309886183791*pi*f((z1,))_3)───X───Ry(0.318309886183791*pi*f((y4,))_8)────Rz(0.318309886183791*pi*f((z4,))_9)────@─── │ 2: ───Ry(0.318309886183791*pi*f((y2,))_4)───Rz(0.318309886183791*pi*f((z2,))_5)───@───Ry(0.318309886183791*pi*f((y5,))_10)───Rz(0.318309886183791*pi*f((z5,))_11)───X─── │ 3: ───Ry(0.318309886183791*pi*f((y3,))_6)───Rz(0.318309886183791*pi*f((z3,))_7)───X───────────────────────────────────────────────────────────────────────────────────── """ circuit = tq.QCircuit() qubits = [i for i in range(num_qubits)] if circuit_id == 1: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 2: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.CNOT(target=qubit, control=qubits[ind]) return circuit elif circuit_id == 3: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=qubit, control=qubits[ind]) count += 1 return circuit elif circuit_id == 4: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=qubit, control=qubits[ind]) count += 1 return circuit elif circuit_id == 5: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): for target in qubits: if control != target: variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=target, control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 6: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=qubits[ind+1], control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=qubits[ind+1], control=control) count += 1 return circuit elif circuit_id == 7: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): for target in qubits: if control != target: variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=target, control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 8: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=qubits[ind+1], control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=qubits[ind+1], control=control) count += 1 return circuit elif circuit_id == 9: count = 0 for _ in range(num_layers): for qubit in qubits: circuit += tq_g.H(qubit) for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.Z(target=qubit, control=qubits[ind]) for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 10: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.Z(target=qubit, control=qubits[ind]) circuit += tq_g.Z(target=qubits[0], control=qubits[-1]) for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 11: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: circuit += tq_g.X(target=qubits[ind+1], control=control) for ind, qubit in enumerate(qubits[1:-1]): variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: circuit += tq_g.X(target=qubits[ind+1], control=control) return circuit elif circuit_id == 12: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: circuit += tq_g.Z(target=qubits[ind+1], control=control) for ind, control in enumerate(qubits[1:-1]): variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = control) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = control) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: circuit += tq_g.Z(target=qubits[ind+1], control=control) return circuit elif circuit_id == 13: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubit, control=qubits[ind]) count += 1 variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubits[0], control=qubits[-1]) count += 1 for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=qubit, target=qubits[ind]) count += 1 variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=qubits[0], target=qubits[-1]) count += 1 return circuit elif circuit_id == 14: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubit, control=qubits[ind]) count += 1 variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubits[0], control=qubits[-1]) count += 1 for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=qubit, target=qubits[ind]) count += 1 variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=qubits[0], target=qubits[-1]) count += 1 return circuit elif circuit_id == 15: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.X(target=qubit, control=qubits[ind]) circuit += tq_g.X(control=qubits[-1], target=qubits[0]) for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.X(control=qubit, target=qubits[ind]) circuit += tq_g.X(target=qubits[-1], control=qubits[0]) return circuit elif circuit_id == 16: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=control, target=qubits[ind+1]) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=control, target=qubits[ind+1]) count += 1 return circuit elif circuit_id == 17: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=control, target=qubits[ind+1]) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=control, target=qubits[ind+1]) count += 1 return circuit elif circuit_id == 18: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[:-1]): variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubit, control=qubits[ind+1]) count += 1 variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubits[-1], control=qubits[0]) count += 1 return circuit elif circuit_id == 19: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[:-1]): variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubit, control=qubits[ind+1]) count += 1 variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubits[-1], control=qubits[0]) count += 1 return circuit
18,425
45.530303
172
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_2.5/grad_hacked.py
from tequila.circuit.compiler import CircuitCompiler from tequila.objective.objective import Objective, ExpectationValueImpl, Variable, \ assign_variable, identity, FixedVariable from tequila import TequilaException from tequila.objective import QTensor from tequila.simulators.simulator_api import compile import typing from numpy import vectorize from tequila.autograd_imports import jax, __AUTOGRAD__BACKEND__ def grad(objective: typing.Union[Objective, QTensor], variable: Variable = None, no_compile=False, *args, **kwargs): ''' wrapper function for getting the gradients of Objectives,ExpectationValues, Unitaries (including single gates), and Transforms. :param obj (QCircuit,ParametrizedGateImpl,Objective,ExpectationValue,Transform,Variable): structure to be differentiated :param variables (list of Variable): parameter with respect to which obj should be differentiated. default None: total gradient. return: dictionary of Objectives, if called on gate, circuit, exp.value, or objective; if Variable or Transform, returns number. ''' if variable is None: # None means that all components are created variables = objective.extract_variables() result = {} if len(variables) == 0: raise TequilaException("Error in gradient: Objective has no variables") for k in variables: assert (k is not None) result[k] = grad(objective, k, no_compile=no_compile) return result else: variable = assign_variable(variable) if isinstance(objective, QTensor): f = lambda x: grad(objective=x, variable=variable, *args, **kwargs) ff = vectorize(f) return ff(objective) if variable not in objective.extract_variables(): return Objective() if no_compile: compiled = objective else: compiler = CircuitCompiler(multitarget=True, trotterized=True, hadamard_power=True, power=True, controlled_phase=True, controlled_rotation=True, gradient_mode=True) compiled = compiler(objective, variables=[variable]) if variable not in compiled.extract_variables(): raise TequilaException("Error in taking gradient. Objective does not depend on variable {} ".format(variable)) if isinstance(objective, ExpectationValueImpl): return __grad_expectationvalue(E=objective, variable=variable) elif objective.is_expectationvalue(): return __grad_expectationvalue(E=compiled.args[-1], variable=variable) elif isinstance(compiled, Objective) or (hasattr(compiled, "args") and hasattr(compiled, "transformation")): return __grad_objective(objective=compiled, variable=variable) else: raise TequilaException("Gradient not implemented for other types than ExpectationValue and Objective.") def __grad_objective(objective: Objective, variable: Variable): args = objective.args transformation = objective.transformation dO = None processed_expectationvalues = {} for i, arg in enumerate(args): if __AUTOGRAD__BACKEND__ == "jax": df = jax.grad(transformation, argnums=i, holomorphic=True) elif __AUTOGRAD__BACKEND__ == "autograd": df = jax.grad(transformation, argnum=i) else: raise TequilaException("Can't differentiate without autograd or jax") # We can detect one simple case where the outer derivative is const=1 if transformation is None or transformation == identity: outer = 1.0 else: outer = Objective(args=args, transformation=df) if hasattr(arg, "U"): # save redundancies if arg in processed_expectationvalues: inner = processed_expectationvalues[arg] else: inner = __grad_inner(arg=arg, variable=variable) processed_expectationvalues[arg] = inner else: # this means this inner derivative is purely variable dependent inner = __grad_inner(arg=arg, variable=variable) if inner == 0.0: # don't pile up zero expectationvalues continue if dO is None: dO = outer * inner else: dO = dO + outer * inner if dO is None: raise TequilaException("caught None in __grad_objective") return dO # def __grad_vector_objective(objective: Objective, variable: Variable): # argsets = objective.argsets # transformations = objective._transformations # outputs = [] # for pos in range(len(objective)): # args = argsets[pos] # transformation = transformations[pos] # dO = None # # processed_expectationvalues = {} # for i, arg in enumerate(args): # if __AUTOGRAD__BACKEND__ == "jax": # df = jax.grad(transformation, argnums=i) # elif __AUTOGRAD__BACKEND__ == "autograd": # df = jax.grad(transformation, argnum=i) # else: # raise TequilaException("Can't differentiate without autograd or jax") # # # We can detect one simple case where the outer derivative is const=1 # if transformation is None or transformation == identity: # outer = 1.0 # else: # outer = Objective(args=args, transformation=df) # # if hasattr(arg, "U"): # # save redundancies # if arg in processed_expectationvalues: # inner = processed_expectationvalues[arg] # else: # inner = __grad_inner(arg=arg, variable=variable) # processed_expectationvalues[arg] = inner # else: # # this means this inner derivative is purely variable dependent # inner = __grad_inner(arg=arg, variable=variable) # # if inner == 0.0: # # don't pile up zero expectationvalues # continue # # if dO is None: # dO = outer * inner # else: # dO = dO + outer * inner # # if dO is None: # dO = Objective() # outputs.append(dO) # if len(outputs) == 1: # return outputs[0] # return outputs def __grad_inner(arg, variable): ''' a modified loop over __grad_objective, which gets derivatives all the way down to variables, return 1 or 0 when a variable is (isnt) identical to var. :param arg: a transform or variable object, to be differentiated :param variable: the Variable with respect to which par should be differentiated. :ivar var: the string representation of variable ''' assert (isinstance(variable, Variable)) if isinstance(arg, Variable): if arg == variable: return 1.0 else: return 0.0 elif isinstance(arg, FixedVariable): return 0.0 elif isinstance(arg, ExpectationValueImpl): return __grad_expectationvalue(arg, variable=variable) elif hasattr(arg, "abstract_expectationvalue"): E = arg.abstract_expectationvalue dE = __grad_expectationvalue(E, variable=variable) return compile(dE, **arg._input_args) else: return __grad_objective(objective=arg, variable=variable) def __grad_expectationvalue(E: ExpectationValueImpl, variable: Variable): ''' implements the analytic partial derivative of a unitary as it would appear in an expectation value. See the paper. :param unitary: the unitary whose gradient should be obtained :param variables (list, dict, str): the variables with respect to which differentiation should be performed. :return: vector (as dict) of dU/dpi as Objective (without hamiltonian) ''' hamiltonian = E.H unitary = E.U if not (unitary.verify()): raise TequilaException("error in grad_expectationvalue unitary is {}".format(unitary)) # fast return if possible if variable not in unitary.extract_variables(): return 0.0 param_gates = unitary._parameter_map[variable] dO = Objective() for idx_g in param_gates: idx, g = idx_g dOinc = __grad_shift_rule(unitary, g, idx, variable, hamiltonian) dO += dOinc assert dO is not None return dO def __grad_shift_rule(unitary, g, i, variable, hamiltonian): ''' function for getting the gradients of directly differentiable gates. Expects precompiled circuits. :param unitary: QCircuit: the QCircuit object containing the gate to be differentiated :param g: a parametrized: the gate being differentiated :param i: Int: the position in unitary at which g appears :param variable: Variable or String: the variable with respect to which gate g is being differentiated :param hamiltonian: the hamiltonian with respect to which unitary is to be measured, in the case that unitary is contained within an ExpectationValue :return: an Objective, whose calculation yields the gradient of g w.r.t variable ''' # possibility for overwride in custom gate construction if hasattr(g, "shifted_gates"): inner_grad = __grad_inner(g.parameter, variable) shifted = g.shifted_gates() dOinc = Objective() for x in shifted: w, g = x Ux = unitary.replace_gates(positions=[i], circuits=[g]) wx = w * inner_grad Ex = Objective.ExpectationValue(U=Ux, H=hamiltonian) dOinc += wx * Ex return dOinc else: raise TequilaException('No shift found for gate {}\nWas the compiler called?'.format(g))
9,886
38.548
132
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_2.5/vqe_utils.py
import tequila as tq import numpy as np from hacked_openfermion_qubit_operator import ParamQubitHamiltonian from openfermion import QubitOperator from HEA import * def get_ansatz_circuit(ansatz_type, geometry, basis_set=None, trotter_steps = 1, name=None, circuit_id=None,num_layers=1): """ This function generates the ansatz for the molecule and the Hamiltonian param: ansatz_type (str) -> the type of the ansatz ('UCCSD, UpCCGSD, SPA, HEA') param: geometry (str) -> the geometry of the molecule param: basis_set (str) -> the basis set for wchich the ansatz has to generated param: trotter_steps (int) -> the number of trotter step to be used in the trotter decomposition param: name (str) -> the name for the madness molecule param: circuit_id (int) -> the type of hardware efficient ansatz param: num_layers (int) -> the number of layers of the HEA e.g.: input: ansatz_type -> "UCCSD" geometry -> "H 0.0 0.0 0.0\nH 0.0 0.0 0.714" basis_set -> 'sto-3g' trotter_steps -> 1 name -> None circuit_id -> None num_layers -> 1 returns: ucc_ansatz (tq.QCircuit()) -> a circuit printed below: circuit: FermionicExcitation(target=(0, 1, 2, 3), control=(), parameter=Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = []) FermionicExcitation(target=(0, 1, 2, 3), control=(), parameter=Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = []) Hamiltonian (tq.QubitHamiltonian()) -> -0.0621+0.1755Z(0)+0.1755Z(1)-0.2358Z(2)-0.2358Z(3)+0.1699Z(0)Z(1) +0.0449Y(0)X(1)X(2)Y(3)-0.0449Y(0)Y(1)X(2)X(3)-0.0449X(0)X(1)Y(2)Y(3) +0.0449X(0)Y(1)Y(2)X(3)+0.1221Z(0)Z(2)+0.1671Z(0)Z(3)+0.1671Z(1)Z(2) +0.1221Z(1)Z(3)+0.1756Z(2)Z(3) fci_ener (float) -> """ ham = tq.QubitHamiltonian() fci_ener = 0.0 ansatz = tq.QCircuit() if ansatz_type == "UCCSD": molecule = tq.Molecule(geometry=geometry, basis_set=basis_set) ansatz = molecule.make_uccsd_ansatz(trotter_steps) ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy(method="fci") elif ansatz_type == "UCCS": molecule = tq.Molecule(geometry=geometry, basis_set=basis_set, backend='psi4') ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy("fci") indices = molecule.make_upccgsd_indices(key='UCCS') print("indices are:", indices) ansatz = molecule.make_upccgsd_layer(indices=indices, include_singles=True, include_doubles=False) elif ansatz_type == "UpCCGSD": molecule = tq.Molecule(name=name, geometry=geometry, n_pno=None) ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy("fci") ansatz = molecule.make_upccgsd_ansatz() elif ansatz_type == "SPA": molecule = tq.Molecule(name=name, geometry=geometry, n_pno=None) ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy("fci") ansatz = molecule.make_upccgsd_ansatz(name="SPA") elif ansatz_type == "HEA": molecule = tq.Molecule(geometry=geometry, basis_set=basis_set) ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy(method="fci") ansatz = generate_HEA(molecule.n_orbitals * 2, circuit_id) else: raise Exception("not implemented any other ansatz, please choose from 'UCCSD, UpCCGSD, SPA, HEA'") return ansatz, ham, fci_ener def get_generator_for_gates(unitary): """ This function takes a unitary gate and returns the generator of the the gate so that it can be padded to the Hamiltonian param: unitary (tq.QGateImpl()) -> the unitary circuit element that has to be converted to a paulistring e.g.: input: unitary -> a FermionicGateImpl object as the one printed below FermionicExcitation(target=(0, 1, 2, 3), control=(), parameter=Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = []) returns: parameter (tq.Variable()) -> (1, 0, 1, 0) generator (tq.QubitHamiltonian()) -> -0.1250Y(0)Y(1)Y(2)X(3)+0.1250Y(0)X(1)Y(2)Y(3) +0.1250X(0)X(1)Y(2)X(3)+0.1250X(0)Y(1)Y(2)Y(3) -0.1250Y(0)X(1)X(2)X(3)-0.1250Y(0)Y(1)X(2)Y(3) -0.1250X(0)Y(1)X(2)X(3)+0.1250X(0)X(1)X(2)Y(3) null_proj (tq.QubitHamiltonian()) -> -0.1250Z(0)Z(1)+0.1250Z(1)Z(3)+0.1250Z(0)Z(3) +0.1250Z(1)Z(2)+0.1250Z(0)Z(2)-0.1250Z(2)Z(3) -0.1250Z(0)Z(1)Z(2)Z(3) """ try: parameter = None generator = None null_proj = None if isinstance(unitary, tq.quantumchemistry.qc_base.FermionicGateImpl): parameter = unitary.extract_variables() generator = unitary.generator null_proj = unitary.p0 else: #getting parameter if unitary.is_parametrized(): parameter = unitary.extract_variables() else: parameter = [None] try: generator = unitary.make_generator(include_controls=True) except: generator = unitary.generator() """if len(parameter) == 0: parameter = [tq.objective.objective.assign_variable(unitary.parameter)]""" return parameter[0], generator, null_proj except Exception as e: print("An Exception happened, details :",e) pass def fold_unitary_into_hamiltonian(unitary, Hamiltonian): """ This function return a list of the resulting Hamiltonian terms after folding the paulistring correspondig to the unitary into the Hamiltonian param: unitary (tq.QGateImpl()) -> the unitary to be folded into the Hamiltonian param: Hamiltonian (ParamQubitHamiltonian()) -> the Hamiltonian of the system e.g.: input: unitary -> a FermionicGateImpl object as the one printed below FermionicExcitation(target=(0, 1, 2, 3), control=(), parameter=Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = []) Hamiltonian -> -0.06214952615456104 [] + -0.044941923860490916 [X0 X1 Y2 Y3] + 0.044941923860490916 [X0 Y1 Y2 X3] + 0.044941923860490916 [Y0 X1 X2 Y3] + -0.044941923860490916 [Y0 Y1 X2 X3] + 0.17547360045040505 [Z0] + 0.16992958569230643 [Z0 Z1] + 0.12212314332112947 [Z0 Z2] + 0.1670650671816204 [Z0 Z3] + 0.17547360045040508 [Z1] + 0.1670650671816204 [Z1 Z2] + 0.12212314332112947 [Z1 Z3] + -0.23578915712819945 [Z2] + 0.17561918557144712 [Z2 Z3] + -0.23578915712819945 [Z3] returns: folded_hamiltonian (ParamQubitHamiltonian()) -> Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [X0 X1 X2 X3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [X0 X1 Y2 Y3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [X0 Y1 X2 Y3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [X0 Y1 Y2 X3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Y0 X1 X2 Y3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Y0 X1 Y2 X3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Y0 Y1 X2 X3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Y0 Y1 Y2 Y3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z1] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z1 Z2] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z1 Z2 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z1 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z2] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z2 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z1] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z1 Z2] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z1 Z2 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z1 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z2] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z2 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z3] """ folded_hamiltonian = ParamQubitHamiltonian() if isinstance(unitary, tq.circuit._gates_impl.DifferentiableGateImpl) and not isinstance(unitary, tq.circuit._gates_impl.PhaseGateImpl): variable, generator, null_proj = get_generator_for_gates(unitary) # print(generator) # print(null_proj) #converting into ParamQubitHamiltonian() c_generator = convert_tq_QH_to_PQH(generator) """c_null_proj = convert_tq_QH_to_PQH(null_proj) print(variable) prod1 = (null_proj*ham*generator - generator*ham*null_proj) print(prod1) #print((Hamiltonian*c_generator)) prod2 = convert_PQH_to_tq_QH(c_null_proj*Hamiltonian*c_generator - c_generator*Hamiltonian*c_null_proj)({var:0.1 for var in variable.extract_variables()}) print(prod2) assert prod1 ==prod2 raise Exception("testing")""" #print("starting", flush=True) #handling the parameterize gates if variable is not None: #print("folding generator") # adding the term: cos^2(\theta)*H temp_ham = ParamQubitHamiltonian().identity() temp_ham *= Hamiltonian temp_ham *= (variable.apply(tq.numpy.cos)**2) #print(convert_PQH_to_tq_QH(temp_ham)({var:1. for var in variable.extract_variables()})) folded_hamiltonian += temp_ham #print("step1 done", flush=True) # adding the term: sin^2(\theta)*G*H*G temp_ham = ParamQubitHamiltonian().identity() temp_ham *= c_generator temp_ham *= Hamiltonian temp_ham *= c_generator temp_ham *= (variable.apply(tq.numpy.sin)**2) #print(convert_PQH_to_tq_QH(temp_ham)({var:1. for var in variable.extract_variables()})) folded_hamiltonian += temp_ham #print("step2 done", flush=True) # adding the term: i*cos^2(\theta)8sin^2(\theta)*(G*H -H*G) temp_ham1 = ParamQubitHamiltonian().identity() temp_ham1 *= c_generator temp_ham1 *= Hamiltonian temp_ham2 = ParamQubitHamiltonian().identity() temp_ham2 *= Hamiltonian temp_ham2 *= c_generator temp_ham = temp_ham1 - temp_ham2 temp_ham *= 1.0j temp_ham *= variable.apply(tq.numpy.sin) * variable.apply(tq.numpy.cos) #print(convert_PQH_to_tq_QH(temp_ham)({var:1. for var in variable.extract_variables()})) folded_hamiltonian += temp_ham #print("step3 done", flush=True) #handling the non-paramterized gates else: raise Exception("This function is not implemented yet") # adding the term: G*H*G folded_hamiltonian += c_generator*Hamiltonian*c_generator #print("Halfway there", flush=True) #handle the FermionicGateImpl gates if null_proj is not None: print("folding null projector") c_null_proj = convert_tq_QH_to_PQH(null_proj) #print("step4 done", flush=True) # adding the term: (1-cos(\theta))^2*P0*H*P0 temp_ham = ParamQubitHamiltonian().identity() temp_ham *= c_null_proj temp_ham *= Hamiltonian temp_ham *= c_null_proj temp_ham *= ((1-variable.apply(tq.numpy.cos))**2) folded_hamiltonian += temp_ham #print("step5 done", flush=True) # adding the term: 2*cos(\theta)*(1-cos(\theta))*(P0*H +H*P0) temp_ham1 = ParamQubitHamiltonian().identity() temp_ham1 *= c_null_proj temp_ham1 *= Hamiltonian temp_ham2 = ParamQubitHamiltonian().identity() temp_ham2 *= Hamiltonian temp_ham2 *= c_null_proj temp_ham = temp_ham1 + temp_ham2 temp_ham *= (variable.apply(tq.numpy.cos)*(1-variable.apply(tq.numpy.cos))) folded_hamiltonian += temp_ham #print("step6 done", flush=True) # adding the term: i*sin(\theta)*(1-cos(\theta))*(G*H*P0 - P0*H*G) temp_ham1 = ParamQubitHamiltonian().identity() temp_ham1 *= c_generator temp_ham1 *= Hamiltonian temp_ham1 *= c_null_proj temp_ham2 = ParamQubitHamiltonian().identity() temp_ham2 *= c_null_proj temp_ham2 *= Hamiltonian temp_ham2 *= c_generator temp_ham = temp_ham1 - temp_ham2 temp_ham *= 1.0j temp_ham *= (variable.apply(tq.numpy.sin)*(1-variable.apply(tq.numpy.cos))) folded_hamiltonian += temp_ham #print("step7 done", flush=True) elif isinstance(unitary, tq.circuit._gates_impl.PhaseGateImpl): if np.isclose(unitary.parameter, np.pi/2.0): return Hamiltonian._clifford_simplify_s(unitary.qubits[0]) elif np.isclose(unitary.parameter, -1.*np.pi/2.0): return Hamiltonian._clifford_simplify_s_dag(unitary.qubits[0]) else: raise Exception("Only DifferentiableGateImpl, PhaseGateImpl(S), Pauligate(X,Y,Z), Controlled(X,Y,Z) and Hadamrd(H) implemented yet") elif isinstance(unitary, tq.circuit._gates_impl.QGateImpl): if unitary.is_controlled(): if unitary.name == "X": return Hamiltonian._clifford_simplify_control_g("X", unitary.control[0], unitary.target[0]) elif unitary.name == "Y": return Hamiltonian._clifford_simplify_control_g("Y", unitary.control[0], unitary.target[0]) elif unitary.name == "Z": return Hamiltonian._clifford_simplify_control_g("Z", unitary.control[0], unitary.target[0]) else: raise Exception("Only DifferentiableGateImpl, PhaseGateImpl(S), Pauligate(X,Y,Z), Controlled(X,Y,Z) and Hadamrd(H) implemented yet") else: if unitary.name == "X": gate = convert_tq_QH_to_PQH(tq.paulis.X(unitary.qubits[0])) return gate*Hamiltonian*gate elif unitary.name == "Y": gate = convert_tq_QH_to_PQH(tq.paulis.Y(unitary.qubits[0])) return gate*Hamiltonian*gate elif unitary.name == "Z": gate = convert_tq_QH_to_PQH(tq.paulis.Z(unitary.qubits[0])) return gate*Hamiltonian*gate elif unitary.name == "H": return Hamiltonian._clifford_simplify_h(unitary.qubits[0]) else: raise Exception("Only DifferentiableGateImpl, PhaseGateImpl(S), Pauligate(X,Y,Z), Controlled(X,Y,Z) and Hadamrd(H) implemented yet") else: raise Exception("Only DifferentiableGateImpl, PhaseGateImpl(S), Pauligate(X,Y,Z), Controlled(X,Y,Z) and Hadamrd(H) implemented yet") return folded_hamiltonian def convert_tq_QH_to_PQH(Hamiltonian): """ This function takes the tequila QubitHamiltonian object and converts into a ParamQubitHamiltonian object. param: Hamiltonian (tq.QubitHamiltonian()) -> the Hamiltonian to be converted e.g: input: Hamiltonian -> -0.0621+0.1755Z(0)+0.1755Z(1)-0.2358Z(2)-0.2358Z(3)+0.1699Z(0)Z(1) +0.0449Y(0)X(1)X(2)Y(3)-0.0449Y(0)Y(1)X(2)X(3)-0.0449X(0)X(1)Y(2)Y(3) +0.0449X(0)Y(1)Y(2)X(3)+0.1221Z(0)Z(2)+0.1671Z(0)Z(3)+0.1671Z(1)Z(2) +0.1221Z(1)Z(3)+0.1756Z(2)Z(3) returns: param_hamiltonian (ParamQubitHamiltonian()) -> -0.06214952615456104 [] + -0.044941923860490916 [X0 X1 Y2 Y3] + 0.044941923860490916 [X0 Y1 Y2 X3] + 0.044941923860490916 [Y0 X1 X2 Y3] + -0.044941923860490916 [Y0 Y1 X2 X3] + 0.17547360045040505 [Z0] + 0.16992958569230643 [Z0 Z1] + 0.12212314332112947 [Z0 Z2] + 0.1670650671816204 [Z0 Z3] + 0.17547360045040508 [Z1] + 0.1670650671816204 [Z1 Z2] + 0.12212314332112947 [Z1 Z3] + -0.23578915712819945 [Z2] + 0.17561918557144712 [Z2 Z3] + -0.23578915712819945 [Z3] """ param_hamiltonian = ParamQubitHamiltonian() Hamiltonian = Hamiltonian.to_openfermion() for term in Hamiltonian.terms: param_hamiltonian += ParamQubitHamiltonian(term = term, coefficient = Hamiltonian.terms[term]) return param_hamiltonian class convert_PQH_to_tq_QH: def __init__(self, Hamiltonian): self.param_hamiltonian = Hamiltonian def __call__(self,variables=None): """ This function takes the ParamQubitHamiltonian object and converts into a tequila QubitHamiltonian object. param: param_hamiltonian (ParamQubitHamiltonian()) -> the Hamiltonian to be converted param: variables (dict) -> a dictionary with the values of the variables in the Hamiltonian coefficient e.g: input: param_hamiltonian -> a [Y0 X2 Z3] + b [Z0 X2 Z3] variables -> {"a":1,"b":2} returns: Hamiltonian (tq.QubitHamiltonian()) -> +1.0000Y(0)X(2)Z(3)+2.0000Z(0)X(2)Z(3) """ Hamiltonian = tq.QubitHamiltonian() for term in self.param_hamiltonian.terms: val = self.param_hamiltonian.terms[term]# + self.param_hamiltonian.imag_terms[term]*1.0j if isinstance(val, tq.Variable) or isinstance(val, tq.objective.objective.Objective): try: for key in variables.keys(): variables[key] = variables[key] #print(variables) val = val(variables) #print(val) except Exception as e: print(e) raise Exception("You forgot to pass the dictionary with the values of the variables") Hamiltonian += tq.QubitHamiltonian(QubitOperator(term=term, coefficient=val)) return Hamiltonian def _construct_derivatives(self, variables=None): """ """ derivatives = {} variable_names = [] for term in self.param_hamiltonian.terms: val = self.param_hamiltonian.terms[term]# + self.param_hamiltonian.imag_terms[term]*1.0j #print(val) if isinstance(val, tq.Variable) or isinstance(val, tq.objective.objective.Objective): variable = val.extract_variables() for var in list(variable): from grad_hacked import grad derivative = ParamQubitHamiltonian(term = term, coefficient = grad(val, var)) if var not in variable_names: variable_names.append(var) if var not in list(derivatives.keys()): derivatives[var] = derivative else: derivatives[var] += derivative return variable_names, derivatives def get_geometry(name, b_l): """ This is utility fucntion that generates tehe geometry string of a Molecule param: name (str) -> name of the molecule param: b_l (float) -> the bond length of the molecule e.g.: input: name -> "H2" b_l -> 0.714 returns: geo_str (str) -> "H 0.0 0.0 0.0\nH 0.0 0.0 0.714" """ geo_str = None if name == "LiH": geo_str = "H 0.0 0.0 0.0\nLi 0.0 0.0 {0}".format(b_l) elif name == "H2": geo_str = "H 0.0 0.0 0.0\nH 0.0 0.0 {0}".format(b_l) elif name == "BeH2": geo_str = "H 0.0 0.0 {0}\nH 0.0 0.0 {1}\nBe 0.0 0.0 0.0".format(b_l,-1*b_l) elif name == "N2": geo_str = "N 0.0 0.0 0.0\nN 0.0 0.0 {0}".format(b_l) elif name == "H4": geo_str = "H 0.0 0.0 0.0\nH 0.0 0.0 {0}\nH 0.0 0.0 {1}\nH 0.0 0.0 {2}".format(b_l,-1*b_l,2*b_l) return geo_str
27,934
51.807183
162
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_2.5/hacked_openfermion_symbolic_operator.py
import abc import copy import itertools import re import warnings import sympy import tequila as tq from tequila.objective.objective import Objective, Variable from openfermion.config import EQ_TOLERANCE COEFFICIENT_TYPES = (int, float, complex, sympy.Expr, Variable, Objective) class SymbolicOperator(metaclass=abc.ABCMeta): """Base class for FermionOperator and QubitOperator. A SymbolicOperator stores an object which represents a weighted sum of terms; each term is a product of individual factors of the form (`index`, `action`), where `index` is a nonnegative integer and the possible values for `action` are determined by the subclass. For instance, for the subclass FermionOperator, `action` can be 1 or 0, indicating raising or lowering, and for QubitOperator, `action` is from the set {'X', 'Y', 'Z'}. The coefficients of the terms are stored in a dictionary whose keys are the terms. SymbolicOperators of the same type can be added or multiplied together. Note: Adding SymbolicOperators is faster using += (as this is done by in-place addition). Specifying the coefficient during initialization is faster than multiplying a SymbolicOperator with a scalar. Attributes: actions (tuple): A tuple of objects representing the possible actions. e.g. for FermionOperator, this is (1, 0). action_strings (tuple): A tuple of string representations of actions. These should be in one-to-one correspondence with actions and listed in the same order. e.g. for FermionOperator, this is ('^', ''). action_before_index (bool): A boolean indicating whether in string representations, the action should come before the index. different_indices_commute (bool): A boolean indicating whether factors acting on different indices commute. terms (dict): **key** (tuple of tuples): A dictionary storing the coefficients of the terms in the operator. The keys are the terms. A term is a product of individual factors; each factor is represented by a tuple of the form (`index`, `action`), and these tuples are collected into a larger tuple which represents the term as the product of its factors. """ @staticmethod def _issmall(val, tol=EQ_TOLERANCE): '''Checks whether a value is near-zero Parses the allowed coefficients above for near-zero tests. Args: val (COEFFICIENT_TYPES) -- the value to be tested tol (float) -- tolerance for inequality ''' if isinstance(val, sympy.Expr): if sympy.simplify(abs(val) < tol) == True: return True return False if isinstance(val, tq.Variable) or isinstance(val, tq.objective.objective.Objective): return False if abs(val) < tol: return True return False @abc.abstractproperty def actions(self): """The allowed actions. Returns a tuple of objects representing the possible actions. """ pass @abc.abstractproperty def action_strings(self): """The string representations of the allowed actions. Returns a tuple containing string representations of the possible actions, in the same order as the `actions` property. """ pass @abc.abstractproperty def action_before_index(self): """Whether action comes before index in string representations. Example: For QubitOperator, the actions are ('X', 'Y', 'Z') and the string representations look something like 'X0 Z2 Y3'. So the action comes before the index, and this function should return True. For FermionOperator, the string representations look like '0^ 1 2^ 3'. The action comes after the index, so this function should return False. """ pass @abc.abstractproperty def different_indices_commute(self): """Whether factors acting on different indices commute.""" pass __hash__ = None def __init__(self, term=None, coefficient=1.): if not isinstance(coefficient, COEFFICIENT_TYPES): raise ValueError('Coefficient must be a numeric type.') # Initialize the terms dictionary self.terms = {} # Detect if the input is the string representation of a sum of terms; # if so, initialization needs to be handled differently if isinstance(term, str) and '[' in term: self._long_string_init(term, coefficient) return # Zero operator: leave the terms dictionary empty if term is None: return # Parse the term # Sequence input if isinstance(term, (list, tuple)): term = self._parse_sequence(term) # String input elif isinstance(term, str): term = self._parse_string(term) # Invalid input type else: raise ValueError('term specified incorrectly.') # Simplify the term coefficient, term = self._simplify(term, coefficient=coefficient) # Add the term to the dictionary self.terms[term] = coefficient def _long_string_init(self, long_string, coefficient): r""" Initialization from a long string representation. e.g. For FermionOperator: '1.5 [2^ 3] + 1.4 [3^ 0]' """ pattern = r'(.*?)\[(.*?)\]' # regex for a term for match in re.findall(pattern, long_string, flags=re.DOTALL): # Determine the coefficient for this term coef_string = re.sub(r"\s+", "", match[0]) if coef_string and coef_string[0] == '+': coef_string = coef_string[1:].strip() if coef_string == '': coef = 1.0 elif coef_string == '-': coef = -1.0 else: try: if 'j' in coef_string: if coef_string[0] == '-': coef = -complex(coef_string[1:]) else: coef = complex(coef_string) else: coef = float(coef_string) except ValueError: raise ValueError( 'Invalid coefficient {}.'.format(coef_string)) coef *= coefficient # Parse the term, simpify it and add to the dict term = self._parse_string(match[1]) coef, term = self._simplify(term, coefficient=coef) if term not in self.terms: self.terms[term] = coef else: self.terms[term] += coef def _validate_factor(self, factor): """Check that a factor of a term is valid.""" if len(factor) != 2: raise ValueError('Invalid factor {}.'.format(factor)) index, action = factor if action not in self.actions: raise ValueError('Invalid action in factor {}. ' 'Valid actions are: {}'.format( factor, self.actions)) if not isinstance(index, int) or index < 0: raise ValueError('Invalid index in factor {}. ' 'The index should be a non-negative ' 'integer.'.format(factor)) def _simplify(self, term, coefficient=1.0): """Simplifies a term.""" if self.different_indices_commute: term = sorted(term, key=lambda factor: factor[0]) return coefficient, tuple(term) def _parse_sequence(self, term): """Parse a term given as a sequence type (i.e., list, tuple, etc.). e.g. For QubitOperator: [('X', 2), ('Y', 0), ('Z', 3)] -> (('Y', 0), ('X', 2), ('Z', 3)) """ if not term: # Empty sequence return () elif isinstance(term[0], int): # Single factor self._validate_factor(term) return (tuple(term),) else: # Check that all factors in the term are valid for factor in term: self._validate_factor(factor) # Return a tuple return tuple(term) def _parse_string(self, term): """Parse a term given as a string. e.g. For FermionOperator: "2^ 3" -> ((2, 1), (3, 0)) """ factors = term.split() # Convert the string representations of the factors to tuples processed_term = [] for factor in factors: # Get the index and action string if self.action_before_index: # The index is at the end of the string; find where it starts. if not factor[-1].isdigit(): raise ValueError('Invalid factor {}.'.format(factor)) index_start = len(factor) - 1 while index_start > 0 and factor[index_start - 1].isdigit(): index_start -= 1 if factor[index_start - 1] == '-': raise ValueError('Invalid index in factor {}. ' 'The index should be a non-negative ' 'integer.'.format(factor)) index = int(factor[index_start:]) action_string = factor[:index_start] else: # The index is at the beginning of the string; find where # it ends if factor[0] == '-': raise ValueError('Invalid index in factor {}. ' 'The index should be a non-negative ' 'integer.'.format(factor)) if not factor[0].isdigit(): raise ValueError('Invalid factor {}.'.format(factor)) index_end = 1 while (index_end <= len(factor) - 1 and factor[index_end].isdigit()): index_end += 1 index = int(factor[:index_end]) action_string = factor[index_end:] # Convert the action string to an action if action_string in self.action_strings: action = self.actions[self.action_strings.index(action_string)] else: raise ValueError('Invalid action in factor {}. ' 'Valid actions are: {}'.format( factor, self.action_strings)) # Add the factor to the list as a tuple processed_term.append((index, action)) # Return a tuple return tuple(processed_term) @property def constant(self): """The value of the constant term.""" return self.terms.get((), 0.0) @constant.setter def constant(self, value): self.terms[()] = value @classmethod def zero(cls): """ Returns: additive_identity (SymbolicOperator): A symbolic operator o with the property that o+x = x+o = x for all operators x of the same class. """ return cls(term=None) @classmethod def identity(cls): """ Returns: multiplicative_identity (SymbolicOperator): A symbolic operator u with the property that u*x = x*u = x for all operators x of the same class. """ return cls(term=()) def __str__(self): """Return an easy-to-read string representation.""" if not self.terms: return '0' string_rep = '' for term, coeff in sorted(self.terms.items()): if self._issmall(coeff): continue tmp_string = '{} ['.format(coeff) for factor in term: index, action = factor action_string = self.action_strings[self.actions.index(action)] if self.action_before_index: tmp_string += '{}{} '.format(action_string, index) else: tmp_string += '{}{} '.format(index, action_string) string_rep += '{}] +\n'.format(tmp_string.strip()) return string_rep[:-3] def __repr__(self): return str(self) def __imul__(self, multiplier): """In-place multiply (*=) with scalar or operator of the same type. Default implementation is to multiply coefficients and concatenate terms. Args: multiplier(complex float, or SymbolicOperator): multiplier Returns: product (SymbolicOperator): Mutated self. """ # Handle scalars. if isinstance(multiplier, COEFFICIENT_TYPES): for term in self.terms: self.terms[term] *= multiplier return self # Handle operator of the same type elif isinstance(multiplier, self.__class__): result_terms = dict() for left_term in self.terms: for right_term in multiplier.terms: left_coefficient = self.terms[left_term] right_coefficient = multiplier.terms[right_term] new_coefficient = left_coefficient * right_coefficient new_term = left_term + right_term new_coefficient, new_term = self._simplify( new_term, coefficient=new_coefficient) # Update result dict. if new_term in result_terms: result_terms[new_term] += new_coefficient else: result_terms[new_term] = new_coefficient self.terms = result_terms return self # Invalid multiplier type else: raise TypeError('Cannot multiply {} with {}'.format( self.__class__.__name__, multiplier.__class__.__name__)) def __mul__(self, multiplier): """Return self * multiplier for a scalar, or a SymbolicOperator. Args: multiplier: A scalar, or a SymbolicOperator. Returns: product (SymbolicOperator) Raises: TypeError: Invalid type cannot be multiply with SymbolicOperator. """ if isinstance(multiplier, COEFFICIENT_TYPES + (type(self),)): product = copy.deepcopy(self) product *= multiplier return product else: raise TypeError('Object of invalid type cannot multiply with ' + type(self) + '.') def __iadd__(self, addend): """In-place method for += addition of SymbolicOperator. Args: addend (SymbolicOperator, or scalar): The operator to add. If scalar, adds to the constant term Returns: sum (SymbolicOperator): Mutated self. Raises: TypeError: Cannot add invalid type. """ if isinstance(addend, type(self)): for term in addend.terms: self.terms[term] = (self.terms.get(term, 0.0) + addend.terms[term]) if self._issmall(self.terms[term]): del self.terms[term] elif isinstance(addend, COEFFICIENT_TYPES): self.constant += addend else: raise TypeError('Cannot add invalid type to {}.'.format(type(self))) return self def __add__(self, addend): """ Args: addend (SymbolicOperator): The operator to add. Returns: sum (SymbolicOperator) """ summand = copy.deepcopy(self) summand += addend return summand def __radd__(self, addend): """ Args: addend (SymbolicOperator): The operator to add. Returns: sum (SymbolicOperator) """ return self + addend def __isub__(self, subtrahend): """In-place method for -= subtraction of SymbolicOperator. Args: subtrahend (A SymbolicOperator, or scalar): The operator to subtract if scalar, subtracts from the constant term. Returns: difference (SymbolicOperator): Mutated self. Raises: TypeError: Cannot subtract invalid type. """ if isinstance(subtrahend, type(self)): for term in subtrahend.terms: self.terms[term] = (self.terms.get(term, 0.0) - subtrahend.terms[term]) if self._issmall(self.terms[term]): del self.terms[term] elif isinstance(subtrahend, COEFFICIENT_TYPES): self.constant -= subtrahend else: raise TypeError('Cannot subtract invalid type from {}.'.format( type(self))) return self def __sub__(self, subtrahend): """ Args: subtrahend (SymbolicOperator): The operator to subtract. Returns: difference (SymbolicOperator) """ minuend = copy.deepcopy(self) minuend -= subtrahend return minuend def __rsub__(self, subtrahend): """ Args: subtrahend (SymbolicOperator): The operator to subtract. Returns: difference (SymbolicOperator) """ return -1 * self + subtrahend def __rmul__(self, multiplier): """ Return multiplier * self for a scalar. We only define __rmul__ for scalars because the left multiply exist for SymbolicOperator and left multiply is also queried as the default behavior. Args: multiplier: A scalar to multiply by. Returns: product: A new instance of SymbolicOperator. Raises: TypeError: Object of invalid type cannot multiply SymbolicOperator. """ if not isinstance(multiplier, COEFFICIENT_TYPES): raise TypeError('Object of invalid type cannot multiply with ' + type(self) + '.') return self * multiplier def __truediv__(self, divisor): """ Return self / divisor for a scalar. Note: This is always floating point division. Args: divisor: A scalar to divide by. Returns: A new instance of SymbolicOperator. Raises: TypeError: Cannot divide local operator by non-scalar type. """ if not isinstance(divisor, COEFFICIENT_TYPES): raise TypeError('Cannot divide ' + type(self) + ' by non-scalar type.') return self * (1.0 / divisor) def __div__(self, divisor): """ For compatibility with Python 2. """ return self.__truediv__(divisor) def __itruediv__(self, divisor): if not isinstance(divisor, COEFFICIENT_TYPES): raise TypeError('Cannot divide ' + type(self) + ' by non-scalar type.') self *= (1.0 / divisor) return self def __idiv__(self, divisor): """ For compatibility with Python 2. """ return self.__itruediv__(divisor) def __neg__(self): """ Returns: negation (SymbolicOperator) """ return -1 * self def __pow__(self, exponent): """Exponentiate the SymbolicOperator. Args: exponent (int): The exponent with which to raise the operator. Returns: exponentiated (SymbolicOperator) Raises: ValueError: Can only raise SymbolicOperator to non-negative integer powers. """ # Handle invalid exponents. if not isinstance(exponent, int) or exponent < 0: raise ValueError( 'exponent must be a non-negative int, but was {} {}'.format( type(exponent), repr(exponent))) # Initialized identity. exponentiated = self.__class__(()) # Handle non-zero exponents. for _ in range(exponent): exponentiated *= self return exponentiated def __eq__(self, other): """Approximate numerical equality (not true equality).""" return self.isclose(other) def __ne__(self, other): return not (self == other) def __iter__(self): self._iter = iter(self.terms.items()) return self def __next__(self): term, coefficient = next(self._iter) return self.__class__(term=term, coefficient=coefficient) def isclose(self, other, tol=EQ_TOLERANCE): """Check if other (SymbolicOperator) is close to self. Comparison is done for each term individually. Return True if the difference between each term in self and other is less than EQ_TOLERANCE Args: other(SymbolicOperator): SymbolicOperator to compare against. """ if not isinstance(self, type(other)): return NotImplemented # terms which are in both: for term in set(self.terms).intersection(set(other.terms)): a = self.terms[term] b = other.terms[term] if not (isinstance(a, sympy.Expr) or isinstance(b, sympy.Expr)): tol *= max(1, abs(a), abs(b)) if self._issmall(a - b, tol) is False: return False # terms only in one (compare to 0.0 so only abs_tol) for term in set(self.terms).symmetric_difference(set(other.terms)): if term in self.terms: if self._issmall(self.terms[term], tol) is False: return False else: if self._issmall(other.terms[term], tol) is False: return False return True def compress(self, abs_tol=EQ_TOLERANCE): """ Eliminates all terms with coefficients close to zero and removes small imaginary and real parts. Args: abs_tol(float): Absolute tolerance, must be at least 0.0 """ new_terms = {} for term in self.terms: coeff = self.terms[term] if isinstance(coeff, sympy.Expr): if sympy.simplify(sympy.im(coeff) <= abs_tol) == True: coeff = sympy.re(coeff) if sympy.simplify(sympy.re(coeff) <= abs_tol) == True: coeff = 1j * sympy.im(coeff) if (sympy.simplify(abs(coeff) <= abs_tol) != True): new_terms[term] = coeff continue if isinstance(val, tq.Variable) or isinstance(val, tq.objective.objective.Objective): continue # Remove small imaginary and real parts if abs(coeff.imag) <= abs_tol: coeff = coeff.real if abs(coeff.real) <= abs_tol: coeff = 1.j * coeff.imag # Add the term if the coefficient is large enough if abs(coeff) > abs_tol: new_terms[term] = coeff self.terms = new_terms def induced_norm(self, order=1): r""" Compute the induced p-norm of the operator. If we represent an operator as :math: `\sum_{j} w_j H_j` where :math: `w_j` are scalar coefficients then this norm is :math: `\left(\sum_{j} \| w_j \|^p \right)^{\frac{1}{p}} where :math: `p` is the order of the induced norm Args: order(int): the order of the induced norm. """ norm = 0. for coefficient in self.terms.values(): norm += abs(coefficient)**order return norm**(1. / order) def many_body_order(self): """Compute the many-body order of a SymbolicOperator. The many-body order of a SymbolicOperator is the maximum length of a term with nonzero coefficient. Returns: int """ if not self.terms: # Zero operator return 0 else: return max( len(term) for term, coeff in self.terms.items() if (self._issmall(coeff) is False)) @classmethod def accumulate(cls, operators, start=None): """Sums over SymbolicOperators.""" total = copy.deepcopy(start or cls.zero()) for operator in operators: total += operator return total def get_operators(self): """Gets a list of operators with a single term. Returns: operators([self.__class__]): A generator of the operators in self. """ for term, coefficient in self.terms.items(): yield self.__class__(term, coefficient) def get_operator_groups(self, num_groups): """Gets a list of operators with a few terms. Args: num_groups(int): How many operators to get in the end. Returns: operators([self.__class__]): A list of operators summing up to self. """ if num_groups < 1: warnings.warn('Invalid num_groups {} < 1.'.format(num_groups), RuntimeWarning) num_groups = 1 operators = self.get_operators() num_groups = min(num_groups, len(self.terms)) for i in range(num_groups): yield self.accumulate( itertools.islice(operators, len(range(i, len(self.terms), num_groups))))
25,797
35.697013
97
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_0.7/main.py
import tequila as tq import numpy as np from tequila.objective.objective import Variable import openfermion from typing import Union from vqe_utils import convert_PQH_to_tq_QH, convert_tq_QH_to_PQH,\ fold_unitary_into_hamiltonian from energy_optimization import * from do_annealing import * import random # guess we could substitute that with numpy.random #TODO import argparse import pickle as pk import matplotlib.pyplot as plt # Main hyperparameters mu = 2.0 # lognormal dist mean sigma = 0.4 # lognormal dist std T_0 = 1.0 # T_0, initial starting temperature # max_epochs = 25 # num_epochs, max number of iterations max_epochs = 20 # num_epochs, max number of iterations min_epochs = 2 # num_epochs, max number of iterations5 # min_epochs = 20 # num_epochs, max number of iterations tol = 1e-6 # minimum change in energy required, otherwise terminate optimization actions_ratio = [.15, .6, .25] patience = 100 beta = 0.5 max_non_cliffords = 0 type_energy_eval='wfn' num_population = 24 num_offsprings = 20 num_processors = 8 #tuning, input as lists. # parser.add_argument('--alphas', type = float, nargs = '+', help='alpha, temperature decay', required=True) alphas = [0.9] # alpha, temperature decay' #Required be = False h2 = True n2 = False name_prefix = '../../data/' # Construct qubit-Hamiltonian #num_active = 3 #active_orbitals = list(range(num_active)) if be: R1 = rrrr R2 = 0.7 geometry = "be 0.0 0.0 0.0\nh 0.0 0.0 {R1}\nh 0.0 0.0 -{R2}" name = "/h/292/philipps/software/moldata/beh2/beh2_{R1:2.2f}_{R2:2.2f}_180" # adapt of you move data mol = tq.Molecule(name=name.format(R1=R1, R2=R2), geometry=geometry.format(R1=R1,R2=R2), n_pno=None) lqm = mol.local_qubit_map(hcb=False) H = mol.make_hamiltonian().map_qubits(lqm).simplify() #print("FCI ENERGY: ", mol.compute_energy(method="fci")) U_spa = mol.make_upccgsd_ansatz(name="SPA").map_qubits(lqm) U = U_spa elif n2: R1 = rrrr geometry = "N 0.0 0.0 0.0\nN 0.0 0.0 {R1}" # name = "/home/abhinav/matter_lab/moldata/n2/n2_{R1:2.2f}" # adapt of you move data name = "/h/292/philipps/software/moldata/n2/n2_{R1:2.2f}" # adapt of you move data mol = tq.Molecule(name=name.format(R1=R1), geometry=geometry.format(R1=R1), n_pno=None) lqm = mol.local_qubit_map(hcb=False) H = mol.make_hamiltonian().map_qubits(lqm).simplify() # print("FCI ENERGY: ", mol.compute_energy(method="fci")) print("Skip FCI calculation, take old data...") U_spa = mol.make_upccgsd_ansatz(name="SPA").map_qubits(lqm) U = U_spa elif h2: active_orbitals = list(range(3)) mol = tq.Molecule(geometry='H 0.0 0.0 0.0\n H 0.0 0.0 0.7', basis_set='6-31g', active_orbitals=active_orbitals, backend='psi4') H = mol.make_hamiltonian().simplify() print("FCI ENERGY: ", mol.compute_energy(method="fci")) U = mol.make_uccsd_ansatz(trotter_steps=1) # Alternatively, get qubit-Hamiltonian from openfermion/externally # with open("ham_6qubits.txt") as hamstring_file: """if be: with open("ham_beh2_3_3.txt") as hamstring_file: hamstring = hamstring_file.read() #print(hamstring) H = tq.QubitHamiltonian().from_string(string=hamstring, openfermion_format=True) elif h2: with open("ham_6qubits.txt") as hamstring_file: hamstring = hamstring_file.read() #print(hamstring) H = tq.QubitHamiltonian().from_string(string=hamstring, openfermion_format=True)""" n_qubits = len(H.qubits) ''' Option 'wfn': "Shortcut" via wavefunction-optimization using MPO-rep of Hamiltonian Option 'qc': Need to input a proper quantum circuit ''' # Clifford optimization in the context of reduced-size quantum circuits starting_E = 123.456 reference = True if reference: if type_energy_eval.lower() == 'wfn': starting_E, _ = minimize_energy(hamiltonian=H, n_qubits=n_qubits, type_energy_eval='wfn') print('starting energy wfn: {:.5f}'.format(starting_E), flush=True) elif type_energy_eval.lower() == 'qc': starting_E, _ = minimize_energy(hamiltonian=H, n_qubits=n_qubits, type_energy_eval='qc', cluster_circuit=U) print('starting energy spa: {:.5f}'.format(starting_E)) else: raise Exception("type_energy_eval must be either 'wfn' or 'qc', but is", type_energy_eval) starting_E, _ = minimize_energy(hamiltonian=H, n_qubits=n_qubits, type_energy_eval='wfn') """for alpha in alphas: print('Starting optimization, alpha = {:3f}'.format(alpha)) # print('Energy to beat', minimize_energy(H, n_qubits, 'wfn')[0]) simulated_annealing(hamiltonian=H, num_population=num_population, num_offsprings=num_offsprings, num_processors=num_processors, tol=tol, max_epochs=max_epochs, min_epochs=min_epochs, T_0=T_0, alpha=alpha, actions_ratio=actions_ratio, max_non_cliffords=max_non_cliffords, verbose=True, patience=patience, beta=beta, type_energy_eval=type_energy_eval.lower(), cluster_circuit=U, starting_energy=starting_E)""" alter_cliffords = True if alter_cliffords: print("starting to replace cliffords with non-clifford gates to see if that improves the current fitness") replace_cliff_with_non_cliff(hamiltonian=H, num_population=num_population, num_offsprings=num_offsprings, num_processors=num_processors, tol=tol, max_epochs=max_epochs, min_epochs=min_epochs, T_0=T_0, alpha=alphas[0], actions_ratio=actions_ratio, max_non_cliffords=max_non_cliffords, verbose=True, patience=patience, beta=beta, type_energy_eval=type_energy_eval.lower(), cluster_circuit=U, starting_energy=starting_E) # accepted_E, tested_E, decisions, instructions_list, best_instructions, temp, best_E = simulated_annealing(hamiltonian=H, # population=4, # num_mutations=2, # num_processors=1, # tol=opt.tol, max_epochs=opt.max_epochs, # min_epochs=opt.min_epochs, T_0=opt.T_0, alpha=alpha, # mu=opt.mu, sigma=opt.sigma, verbose=True, prev_E = starting_E, patience = 10, beta = 0.5, # energy_eval='qc', # eval_circuit=U # print(best_E) # print(best_instructions) # print(len(accepted_E)) # plt.plot(accepted_E) # plt.show() # #pickling data # data = {'accepted_energies': accepted_E, 'tested_energies': tested_E, # 'decisions': decisions, 'instructions': instructions_list, # 'best_instructions': best_instructions, 'temperature': temp, # 'best_energy': best_E} # f_name = '{}{}_alpha_{:.2f}.pk'.format(opt.name_prefix, r, alpha) # pk.dump(data, open(f_name, 'wb')) # print('Finished optimization, data saved in {}'.format(f_name))
7,368
40.869318
129
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_0.7/my_mpo.py
import numpy as np import tensornetwork as tn from tensornetwork.backends.abstract_backend import AbstractBackend tn.set_default_backend("pytorch") #tn.set_default_backend("numpy") from typing import List, Union, Text, Optional, Any, Type Tensor = Any import tequila as tq import torch EPS = 1e-12 class SubOperator: """ This is just a helper class to store coefficient, operators and positions in an intermediate format """ def __init__(self, coefficient: float, operators: List, positions: List ): self._coefficient = coefficient self._operators = operators self._positions = positions @property def coefficient(self): return self._coefficient @property def operators(self): return self._operators @property def positions(self): return self._positions class MPOContainer: """ Class that handles the MPO. Is able to set values at certain positions, update containers (wannabe-equivalent to dynamic arrays) and compress the MPO """ def __init__(self, n_qubits: int, ): self.n_qubits = n_qubits self.container = [ np.zeros((1,1,2,2), dtype=np.complex) for q in range(self.n_qubits) ] def get_dim(self): """ Returns max dimension of container """ d = 1 for q in range(len(self.container)): d = max(d, self.container[q].shape[0]) return d def set_tensor(self, qubit: int, set_at: list, add_operator: Union[np.ndarray, float]): """ set_at: where to put data """ # Set a matrix if len(set_at) == 2: self.container[qubit][set_at[0],set_at[1],:,:] = add_operator[:,:] # Set specific values elif len(set_at) == 4: self.container[qubit][set_at[0],set_at[1],set_at[2],set_at[3]] =\ add_operator else: raise Exception("set_at needs to be either of length 2 or 4") def update_container(self, qubit: int, update_dir: list, add_operator: np.ndarray): """ This should mimick a dynamic array update_dir: e.g. [1,1,0,0] -> extend dimension along where there's a 1 the last two dimensions are always 2x2 only """ old_shape = self.container[qubit].shape # print(old_shape) if not len(update_dir) == 4: if len(update_dir) == 2: update_dir += [0, 0] else: raise Exception("update_dir needs to be either of length 2 or 4") if update_dir[2] or update_dir[3]: raise Exception("Last two dims must be zero.") new_shape = tuple(update_dir[i]+old_shape[i] for i in range(len(update_dir))) new_tensor = np.zeros(new_shape, dtype=np.complex) # Copy old values new_tensor[:old_shape[0],:old_shape[1],:,:] = self.container[qubit][:,:,:,:] # Add new values new_tensor[new_shape[0]-1,new_shape[1]-1,:,:] = add_operator[:,:] # Overwrite container self.container[qubit] = new_tensor def compress_mpo(self): """ Compression of MPO via SVD """ n_qubits = len(self.container) for q in range(n_qubits): my_shape = self.container[q].shape self.container[q] =\ self.container[q].reshape((my_shape[0], my_shape[1], -1)) # Go forwards for q in range(n_qubits-1): # Apply permutation [0 1 2] -> [0 2 1] my_tensor = np.swapaxes(self.container[q], 1, 2) my_tensor = my_tensor.reshape((-1, my_tensor.shape[2])) # full_matrices flag corresponds to 'econ' -> no zero-singular values u, s, vh = np.linalg.svd(my_tensor, full_matrices=False) # Count the non-zero singular values num_nonzeros = len(np.argwhere(s>EPS)) # Construct matrix from square root of singular values s = np.diag(np.sqrt(s[:num_nonzeros])) u = u[:,:num_nonzeros] vh = vh[:num_nonzeros,:] # Distribute weights to left- and right singular vectors (@ = np.matmul) u = u @ s vh = s @ vh # Apply permutation [0 1 2] -> [0 2 1] u = u.reshape((self.container[q].shape[0],\ self.container[q].shape[2], -1)) self.container[q] = np.swapaxes(u, 1, 2) self.container[q+1] = tn.ncon([vh, self.container[q+1]], [(-1, 1),(1, -2, -3)]) # Go backwards for q in range(n_qubits-1, 0, -1): my_tensor = self.container[q] my_tensor = my_tensor.reshape((self.container[q].shape[0], -1)) # full_matrices flag corresponds to 'econ' -> no zero-singular values u, s, vh = np.linalg.svd(my_tensor, full_matrices=False) # Count the non-zero singular values num_nonzeros = len(np.argwhere(s>EPS)) # Construct matrix from square root of singular values s = np.diag(np.sqrt(s[:num_nonzeros])) u = u[:,:num_nonzeros] vh = vh[:num_nonzeros,:] # Distribute weights to left- and right singular vectors u = u @ s vh = s @ vh self.container[q] = np.reshape(vh, (num_nonzeros, self.container[q].shape[1], self.container[q].shape[2])) self.container[q-1] = tn.ncon([self.container[q-1], u], [(-1, 1, -3),(1, -2)]) for q in range(n_qubits): my_shape = self.container[q].shape self.container[q] = self.container[q].reshape((my_shape[0],\ my_shape[1],2,2)) # TODO maybe make subclass of tn.FiniteMPO if it makes sense #class my_MPO(tn.FiniteMPO): class MyMPO: """ Class building up on tensornetwork FiniteMPO to handle MPO-Hamiltonians """ def __init__(self, hamiltonian: Union[tq.QubitHamiltonian, Text], # tensors: List[Tensor], backend: Optional[Union[AbstractBackend, Text]] = None, n_qubits: Optional[int] = None, name: Optional[Text] = None, maxdim: Optional[int] = 10000) -> None: # TODO: modifiy docstring """ Initialize a finite MPO object Args: tensors: The mpo tensors. backend: An optional backend. Defaults to the defaulf backend of TensorNetwork. name: An optional name for the MPO. """ self.hamiltonian = hamiltonian self.maxdim = maxdim if n_qubits: self._n_qubits = n_qubits else: self._n_qubits = self.get_n_qubits() @property def n_qubits(self): return self._n_qubits def make_mpo_from_hamiltonian(self): intermediate = self.openfermion_to_intermediate() # for i in range(len(intermediate)): # print(intermediate[i].coefficient) # print(intermediate[i].operators) # print(intermediate[i].positions) self.mpo = self.intermediate_to_mpo(intermediate) def openfermion_to_intermediate(self): # Here, have either a QubitHamiltonian or a file with a of-operator # Start with Qubithamiltonian def get_pauli_matrix(string): pauli_matrices = { 'I': np.array([[1, 0], [0, 1]], dtype=np.complex), 'Z': np.array([[1, 0], [0, -1]], dtype=np.complex), 'X': np.array([[0, 1], [1, 0]], dtype=np.complex), 'Y': np.array([[0, -1j], [1j, 0]], dtype=np.complex) } return pauli_matrices[string.upper()] intermediate = [] first = True # Store all paulistrings in intermediate format for paulistring in self.hamiltonian.paulistrings: coefficient = paulistring.coeff # print(coefficient) operators = [] positions = [] # Only first one should be identity -> distribute over all if first and not paulistring.items(): positions += [] operators += [] first = False elif not first and not paulistring.items(): raise Exception("Only first Pauli should be identity.") # Get operators and where they act for k,v in paulistring.items(): positions += [k] operators += [get_pauli_matrix(v)] tmp_op = SubOperator(coefficient=coefficient, operators=operators, positions=positions) intermediate += [tmp_op] # print("len intermediate = num Pauli strings", len(intermediate)) return intermediate def build_single_mpo(self, intermediate, j): # Set MPO Container n_qubits = self._n_qubits mpo = MPOContainer(n_qubits=n_qubits) # *********************************************************************** # Set first entries (of which we know that they are 2x2-matrices) # Typically, this is an identity my_coefficient = intermediate[j].coefficient my_positions = intermediate[j].positions my_operators = intermediate[j].operators for q in range(n_qubits): if not q in my_positions: mpo.set_tensor(qubit=q, set_at=[0,0], add_operator=np.complex(my_coefficient)**(1/n_qubits)* np.eye(2)) elif q in my_positions: my_pos_index = my_positions.index(q) mpo.set_tensor(qubit=q, set_at=[0,0], add_operator=np.complex(my_coefficient)**(1/n_qubits)* my_operators[my_pos_index]) # *********************************************************************** # All other entries # while (j smaller than number of intermediates left) and mpo.dim() <= self.maxdim # Re-write this based on positions keyword! j += 1 while j < len(intermediate) and mpo.get_dim() < self.maxdim: # """ my_coefficient = intermediate[j].coefficient my_positions = intermediate[j].positions my_operators = intermediate[j].operators for q in range(n_qubits): # It is guaranteed that every index appears only once in positions if q == 0: update_dir = [0,1] elif q == n_qubits-1: update_dir = [1,0] else: update_dir = [1,1] # If there's an operator on my position, add that if q in my_positions: my_pos_index = my_positions.index(q) mpo.update_container(qubit=q, update_dir=update_dir, add_operator= np.complex(my_coefficient)**(1/n_qubits)* my_operators[my_pos_index]) # Else add an identity else: mpo.update_container(qubit=q, update_dir=update_dir, add_operator= np.complex(my_coefficient)**(1/n_qubits)* np.eye(2)) if not j % 100: mpo.compress_mpo() #print("\t\tAt iteration ", j, " MPO has dimension ", mpo.get_dim()) j += 1 mpo.compress_mpo() #print("\tAt final iteration ", j-1, " MPO has dimension ", mpo.get_dim()) return mpo, j def intermediate_to_mpo(self, intermediate): n_qubits = self._n_qubits # TODO Change to multiple MPOs mpo_list = [] j_global = 0 num_mpos = 0 # Start with 0, then final one is correct while j_global < len(intermediate): current_mpo, j_global = self.build_single_mpo(intermediate, j_global) mpo_list += [current_mpo] num_mpos += 1 return mpo_list def construct_matrix(self): # TODO extend to lists of MPOs ''' Recover matrix, e.g. to compare with Hamiltonian that we get from tq ''' mpo = self.mpo # Contract over all bond indices # mpo.container has indices [bond, bond, physical, physical] n_qubits = self._n_qubits d = int(2**(n_qubits/2)) first = True H = None #H = np.zeros((d,d,d,d), dtype='complex') # Define network nodes # | | | | # -O--O--...--O--O- # | | | | for m in mpo: assert(n_qubits == len(m.container)) nodes = [tn.Node(m.container[q], name=str(q)) for q in range(n_qubits)] # Connect network (along double -- above) for q in range(n_qubits-1): nodes[q][1] ^ nodes[q+1][0] # Collect dangling edges (free indices) edges = [] # Left dangling edge edges += [nodes[0].get_edge(0)] # Right dangling edge edges += [nodes[-1].get_edge(1)] # Upper dangling edges for q in range(n_qubits): edges += [nodes[q].get_edge(2)] # Lower dangling edges for q in range(n_qubits): edges += [nodes[q].get_edge(3)] # Contract between all nodes along non-dangling edges res = tn.contractors.auto(nodes, output_edge_order=edges) # Reshape to get tensor of order 4 (get rid of left- and right open indices # and combine top&bottom into one) if isinstance(res.tensor, torch.Tensor): H_m = res.tensor.numpy() if not first: H += H_m else: H = H_m first = False return H.reshape((d,d,d,d))
14,354
36.480418
99
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_0.7/do_annealing.py
import tequila as tq import numpy as np import pickle from pathos.multiprocessing import ProcessingPool as Pool from parallel_annealing import * #from dummy_par import * from mutation_options import * from single_thread_annealing import * def find_best_instructions(instructions_dict): """ This function finds the instruction with the best fitness args: instructions_dict: A dictionary with the "Instructions" objects the corresponding fitness values as values """ best_instructions = None best_fitness = 10000000 for key in instructions_dict: if instructions_dict[key][1] <= best_fitness: best_instructions = instructions_dict[key][0] best_fitness = instructions_dict[key][1] return best_instructions, best_fitness def simulated_annealing(num_population, num_offsprings, actions_ratio, hamiltonian, max_epochs=100, min_epochs=1, tol=1e-6, type_energy_eval="wfn", cluster_circuit=None, patience = 20, num_processors=4, T_0=1.0, alpha=0.9, max_non_cliffords=0, verbose=False, beta=0.5, starting_energy=None): """ this function tries to find the clifford circuit that best lowers the energy of the hamiltonian using simulated annealing. params: - num_population = number of members in a generation - num_offsprings = number of mutations carried on every member - num_processors = number of processors to use for parallelization - T_0 = initial temperature - alpha = temperature decay - beta = parameter to adjust temperature on resetting after running out of patience - max_epochs = max iterations for optimizing - min_epochs = min iterations for optimizing - tol = minimum change in energy required, otherwise terminate optimization - verbose = display energies/decisions at iterations of not - hamiltonian = original hamiltonian - actions_ratio = The ratio of the different actions for mutations - type_energy_eval = keyword specifying the type of optimization method to use for energy minimization - cluster_circuit = the reference circuit to which clifford gates are added - patience = the number of epochs before resetting the optimization """ if verbose: print("Starting to Optimize Cluster circuit", flush=True) num_qubits = len(hamiltonian.qubits) if verbose: print("Initializing Generation", flush=True) # restart = False if previous_instructions is None\ # else True restart = False instructions_dict = {} instructions_list = [] current_fitness_list = [] fitness, wfn = None, None # pre-initialize with None for instruction_id in range(num_population): instructions = None if restart: try: instructions = Instructions(n_qubits=num_qubits, alpha=alpha, T_0=T_0, beta=beta, patience=patience, max_non_cliffords=max_non_cliffords, reference_energy=starting_energy) instructions.gates = pickle.load(open("instruct_gates.pickle", "rb")) instructions.positions = pickle.load(open("instruct_positions.pickle", "rb")) instructions.best_reference_wfn = pickle.load(open("best_reference_wfn.pickle", "rb")) print("Added a guess from previous runs", flush=True) fitness, wfn = evaluate_fitness(instructions=instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) except Exception as e: print(e) raise Exception("Did not find a guess from previous runs") # pass restart = False #print(instructions._str()) else: failed = True while failed: instructions = Instructions(n_qubits=num_qubits, alpha=alpha, T_0=T_0, beta=beta, patience=patience, max_non_cliffords=max_non_cliffords, reference_energy=starting_energy) instructions.prune() fitness, wfn = evaluate_fitness(instructions=instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) # if fitness <= starting_energy: failed = False instructions.set_reference_wfn(wfn) current_fitness_list.append(fitness) instructions_list.append(instructions) instructions_dict[instruction_id] = (instructions, fitness) if verbose: print("First Generation details: \n", flush=True) for key in instructions_dict: print("Initial Instructions number: ", key, flush=True) instructions_dict[key][0]._str() print("Initial fitness values: ", instructions_dict[key][1], flush=True) best_instructions, best_energy = find_best_instructions(instructions_dict) if verbose: print("Best member of the Generation: \n", flush=True) print("Instructions: ", flush=True) best_instructions._str() print("fitness value: ", best_energy, flush=True) pickle.dump(best_instructions.gates, open("instruct_gates.pickle", "wb")) pickle.dump(best_instructions.positions, open("instruct_positions.pickle", "wb")) pickle.dump(best_instructions.best_reference_wfn, open("best_reference_wfn.pickle", "wb")) epoch = 0 previous_best_energy = best_energy converged = False has_improved_before = False dts = [] #pool = multiprocessing.Pool(processes=num_processors) while (epoch < max_epochs): print("Epoch: ", epoch, flush=True) import time t0 = time.time() if num_processors == 1: st_evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, type_energy_eval, cluster_circuit) else: evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, num_processors, type_energy_eval, cluster_circuit) t1 = time.time() dts += [t1-t0] best_instructions, best_energy = find_best_instructions(instructions_dict) if verbose: print("Best member of the Generation: \n", flush=True) print("Instructions: ", flush=True) best_instructions._str() print("fitness value: ", best_energy, flush=True) # A bit confusing, but: # Want that current best energy has improved something previous, is better than # some starting energy and achieves some convergence criterion has_improved_before = True if np.abs(best_energy - previous_best_energy) < 0\ else False if np.abs(best_energy - previous_best_energy) < tol and has_improved_before: if starting_energy is not None: converged = True if best_energy < starting_energy else False else: converged = True else: converged = False if best_energy < previous_best_energy: previous_best_energy = best_energy epoch += 1 pickle.dump(best_instructions.gates, open("instruct_gates.pickle", "wb")) pickle.dump(best_instructions.positions, open("instruct_positions.pickle", "wb")) pickle.dump(best_instructions.best_reference_wfn, open("best_reference_wfn.pickle", "wb")) #pool.close() if converged: print("Converged after ", epoch, " iterations.", flush=True) print("Best energy:", best_energy, flush=True) print("\t with instructions", best_instructions.gates, best_instructions.positions, flush=True) print("\t optimal parameters", best_instructions.best_reference_wfn, flush=True) print("average time: ", np.average(dts), flush=True) print("overall time: ", np.sum(dts), flush=True) # best_instructions.replace_UCCXc_with_UCC(number=max_non_cliffords) pickle.dump(best_instructions.gates, open("instruct_gates.pickle", "wb")) pickle.dump(best_instructions.positions, open("instruct_positions.pickle", "wb")) pickle.dump(best_instructions.best_reference_wfn, open("best_reference_wfn.pickle", "wb")) def replace_cliff_with_non_cliff(num_population, num_offsprings, actions_ratio, hamiltonian, max_epochs=100, min_epochs=1, tol=1e-6, type_energy_eval="wfn", cluster_circuit=None, patience = 20, num_processors=4, T_0=1.0, alpha=0.9, max_non_cliffords=0, verbose=False, beta=0.5, starting_energy=None): """ this function tries to find the clifford circuit that best lowers the energy of the hamiltonian using simulated annealing. params: - num_population = number of members in a generation - num_offsprings = number of mutations carried on every member - num_processors = number of processors to use for parallelization - T_0 = initial temperature - alpha = temperature decay - beta = parameter to adjust temperature on resetting after running out of patience - max_epochs = max iterations for optimizing - min_epochs = min iterations for optimizing - tol = minimum change in energy required, otherwise terminate optimization - verbose = display energies/decisions at iterations of not - hamiltonian = original hamiltonian - actions_ratio = The ratio of the different actions for mutations - type_energy_eval = keyword specifying the type of optimization method to use for energy minimization - cluster_circuit = the reference circuit to which clifford gates are added - patience = the number of epochs before resetting the optimization """ if verbose: print("Starting to replace clifford gates Cluster circuit with non-clifford gates one at a time", flush=True) num_qubits = len(hamiltonian.qubits) #get the best clifford object instructions = Instructions(n_qubits=num_qubits, alpha=alpha, T_0=T_0, beta=beta, patience=patience, max_non_cliffords=max_non_cliffords, reference_energy=starting_energy) instructions.gates = pickle.load(open("instruct_gates.pickle", "rb")) instructions.positions = pickle.load(open("instruct_positions.pickle", "rb")) instructions.best_reference_wfn = pickle.load(open("best_reference_wfn.pickle", "rb")) fitness, wfn = evaluate_fitness(instructions=instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) if verbose: print("Initial energy after previous Clifford optimization is",\ fitness, flush=True) print("Starting with instructions", instructions.gates, instructions.positions, flush=True) instructions_dict = {} instructions_dict[0] = (instructions, fitness) for gate_id, (gate, position) in enumerate(zip(instructions.gates, instructions.positions)): print(gate) altered_instructions = copy.deepcopy(instructions) # skip if controlled rotation if gate[0]=='C': continue altered_instructions.replace_cg_w_ncg(gate_id) # altered_instructions.max_non_cliffords = 1 # TODO why is this set to 1?? altered_instructions.max_non_cliffords = max_non_cliffords #clifford_circuit, init_angles = build_circuit(instructions) #print(clifford_circuit, init_angles) #folded_hamiltonian = perform_folding(hamiltonian, clifford_circuit) #folded_hamiltonian2 = (convert_PQH_to_tq_QH(folded_hamiltonian))() #print(folded_hamiltonian) #clifford_circuit, init_angles = build_circuit(altered_instructions) #print(clifford_circuit, init_angles) #folded_hamiltonian = perform_folding(hamiltonian, clifford_circuit) #folded_hamiltonian1 = (convert_PQH_to_tq_QH(folded_hamiltonian))(init_angles) #print(folded_hamiltonian1 - folded_hamiltonian2) #print(folded_hamiltonian) #raise Exception("teste") counter = 0 success = False while not success: counter += 1 try: fitness, wfn = evaluate_fitness(instructions=altered_instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) success = True except Exception as e: print(e) if counter > 5: print("This replacement failed more than 5 times") success = True instructions_dict[gate_id+1] = (altered_instructions, fitness) #circuit = build_circuit(altered_instructions) #tq.draw(circuit,backend="cirq") best_instructions, best_energy = find_best_instructions(instructions_dict) print("best instrucitons after the non-clifford opimizaton") print("Best energy:", best_energy, flush=True) print("\t with instructions", best_instructions.gates, best_instructions.positions, flush=True)
13,155
46.154122
187
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_0.7/scipy_optimizer.py
import numpy, copy, scipy, typing, numbers from tequila import BitString, BitNumbering, BitStringLSB from tequila.utils.keymap import KeyMapRegisterToSubregister from tequila.circuit.compiler import change_basis from tequila.utils import to_float import tequila as tq from tequila.objective import Objective from tequila.optimizers.optimizer_scipy import OptimizerSciPy, SciPyResults from tequila.objective.objective import assign_variable, Variable, format_variable_dictionary, format_variable_list from tequila.circuit.noise import NoiseModel #from tequila.optimizers._containers import _EvalContainer, _GradContainer, _HessContainer, _QngContainer from vqe_utils import * class _EvalContainer: """ Overwrite the call function Container Class to access scipy and keep the optimization history. This class is used by the SciPy optimizer and should not be used elsewhere. Attributes --------- objective: the objective to evaluate. param_keys: the dictionary mapping parameter keys to positions in a numpy array. samples: the number of samples to evaluate objective with. save_history: whether or not to save, in a history, information about each time __call__ occurs. print_level dictates the verbosity of printing during call. N: the length of param_keys. history: if save_history, a list of energies received from every __call__ history_angles: if save_history, a list of angles sent to __call__. """ def __init__(self, Hamiltonian, unitary, param_keys, Ham_derivatives= None, Eval=None, passive_angles=None, samples=1024, save_history=True, print_level: int = 3): self.Hamiltonian = Hamiltonian self.unitary = unitary self.samples = samples self.param_keys = param_keys self.N = len(param_keys) self.save_history = save_history self.print_level = print_level self.passive_angles = passive_angles self.Eval = Eval self.infostring = None self.Ham_derivatives = Ham_derivatives if save_history: self.history = [] self.history_angles = [] def __call__(self, p, *args, **kwargs): """ call a wrapped objective. Parameters ---------- p: numpy array: Parameters with which to call the objective. args kwargs Returns ------- numpy.array: value of self.objective with p translated into variables, as a numpy array. """ angles = {}#dict((self.param_keys[i], p[i]) for i in range(self.N)) for i in range(self.N): if self.param_keys[i] in self.unitary.extract_variables(): angles[self.param_keys[i]] = p[i] else: angles[self.param_keys[i]] = complex(p[i]) if self.passive_angles is not None: angles = {**angles, **self.passive_angles} vars = format_variable_dictionary(angles) Hamiltonian = self.Hamiltonian(vars) #print(Hamiltonian) #print(self.unitary) #print(vars) Expval = tq.ExpectationValue(H=Hamiltonian, U=self.unitary) #print(Expval) E = tq.simulate(Expval, vars, backend='qulacs', samples=self.samples) self.infostring = "{:15} : {} expectationvalues\n".format("Objective", Expval.count_expectationvalues()) if self.print_level > 2: print("E={:+2.8f}".format(E), " angles=", angles, " samples=", self.samples) elif self.print_level > 1: print("E={:+2.8f}".format(E)) if self.save_history: self.history.append(E) self.history_angles.append(angles) return complex(E) # jax types confuses optimizers class _GradContainer(_EvalContainer): """ Overwrite the call function Container Class to access scipy and keep the optimization history. This class is used by the SciPy optimizer and should not be used elsewhere. see _EvalContainer for details. """ def __call__(self, p, *args, **kwargs): """ call the wrapped qng. Parameters ---------- p: numpy array: Parameters with which to call gradient args kwargs Returns ------- numpy.array: value of self.objective with p translated into variables, as a numpy array. """ Ham_derivatives = self.Ham_derivatives Hamiltonian = self.Hamiltonian unitary = self.unitary dE_vec = numpy.zeros(self.N) memory = dict() #variables = dict((self.param_keys[i], p[i]) for i in range(len(self.param_keys))) variables = {}#dict((self.param_keys[i], p[i]) for i in range(self.N)) for i in range(len(self.param_keys)): if self.param_keys[i] in self.unitary.extract_variables(): variables[self.param_keys[i]] = p[i] else: variables[self.param_keys[i]] = complex(p[i]) if self.passive_angles is not None: variables = {**variables, **self.passive_angles} vars = format_variable_dictionary(variables) expvals = 0 for i in range(self.N): derivative = 0.0 if self.param_keys[i] in list(unitary.extract_variables()): Ham = Hamiltonian(vars) Expval = tq.ExpectationValue(H=Ham, U=unitary) temp_derivative = tq.compile(objective = tq.grad(objective = Expval, variable = self.param_keys[i]),backend='qulacs') expvals += temp_derivative.count_expectationvalues() derivative += temp_derivative if self.param_keys[i] in list(Ham_derivatives.keys()): #print(self.param_keys[i]) Ham = Ham_derivatives[self.param_keys[i]] Ham = convert_PQH_to_tq_QH(Ham) H = Ham(vars) #print(H) #raise Exception("testing") Expval = tq.ExpectationValue(H=H, U=unitary) expvals += Expval.count_expectationvalues() derivative += tq.simulate(Expval, vars, backend='qulacs', samples=self.samples) #print(derivative) #print(type(H)) if isinstance(derivative, float) or isinstance(derivative, numpy.complex64) : dE_vec[i] = derivative else: dE_vec[i] = derivative(variables=variables, samples=self.samples) memory[self.param_keys[i]] = dE_vec[i] self.infostring = "{:15} : {} expectationvalues\n".format("gradient", expvals) self.history.append(memory) return numpy.asarray(dE_vec, dtype=numpy.complex64) class optimize_scipy(OptimizerSciPy): """ overwrite the expectation and gradient container objects """ def initialize_variables(self, all_variables, initial_values, variables): """ Convenience function to format the variables of some objective recieved in calls to optimzers. Parameters ---------- objective: Objective: the objective being optimized. initial_values: dict or string: initial values for the variables of objective, as a dictionary. if string: can be `zero` or `random` if callable: custom function that initializes when keys are passed if None: random initialization between 0 and 2pi (not recommended) variables: list: the variables being optimized over. Returns ------- tuple: active_angles, a dict of those variables being optimized. passive_angles, a dict of those variables NOT being optimized. variables: formatted list of the variables being optimized. """ # bring into right format variables = format_variable_list(variables) initial_values = format_variable_dictionary(initial_values) all_variables = all_variables if variables is None: variables = all_variables if initial_values is None: initial_values = {k: numpy.random.uniform(0, 2 * numpy.pi) for k in all_variables} elif hasattr(initial_values, "lower"): if initial_values.lower() == "zero": initial_values = {k:0.0 for k in all_variables} elif initial_values.lower() == "random": initial_values = {k: numpy.random.uniform(0, 2 * numpy.pi) for k in all_variables} else: raise TequilaOptimizerException("unknown initialization instruction: {}".format(initial_values)) elif callable(initial_values): initial_values = {k: initial_values(k) for k in all_variables} elif isinstance(initial_values, numbers.Number): initial_values = {k: initial_values for k in all_variables} else: # autocomplete initial values, warn if you did detected = False for k in all_variables: if k not in initial_values: initial_values[k] = 0.0 detected = True if detected and not self.silent: warnings.warn("initial_variables given but not complete: Autocompleted with zeroes", TequilaWarning) active_angles = {} for v in variables: active_angles[v] = initial_values[v] passive_angles = {} for k, v in initial_values.items(): if k not in active_angles.keys(): passive_angles[k] = v return active_angles, passive_angles, variables def __call__(self, Hamiltonian, unitary, variables: typing.List[Variable] = None, initial_values: typing.Dict[Variable, numbers.Real] = None, gradient: typing.Dict[Variable, Objective] = None, hessian: typing.Dict[typing.Tuple[Variable, Variable], Objective] = None, reset_history: bool = True, *args, **kwargs) -> SciPyResults: """ Perform optimization using scipy optimizers. Parameters ---------- objective: Objective: the objective to optimize. variables: list, optional: the variables of objective to optimize. If None: optimize all. initial_values: dict, optional: a starting point from which to begin optimization. Will be generated if None. gradient: optional: Information or object used to calculate the gradient of objective. Defaults to None: get analytically. hessian: optional: Information or object used to calculate the hessian of objective. Defaults to None: get analytically. reset_history: bool: Default = True: whether or not to reset all history before optimizing. args kwargs Returns ------- ScipyReturnType: the results of optimization. """ H = convert_PQH_to_tq_QH(Hamiltonian) Ham_variables, Ham_derivatives = H._construct_derivatives() #print("hamvars",Ham_variables) all_variables = copy.deepcopy(Ham_variables) #print(all_variables) for var in unitary.extract_variables(): all_variables.append(var) #print(all_variables) infostring = "{:15} : {}\n".format("Method", self.method) #infostring += "{:15} : {} expectationvalues\n".format("Objective", objective.count_expectationvalues()) if self.save_history and reset_history: self.reset_history() active_angles, passive_angles, variables = self.initialize_variables(all_variables, initial_values, variables) #print(active_angles, passive_angles, variables) # Transform the initial value directory into (ordered) arrays param_keys, param_values = zip(*active_angles.items()) param_values = numpy.array(param_values) # process and initialize scipy bounds bounds = None if self.method_bounds is not None: bounds = {k: None for k in active_angles} for k, v in self.method_bounds.items(): if k in bounds: bounds[k] = v infostring += "{:15} : {}\n".format("bounds", self.method_bounds) names, bounds = zip(*bounds.items()) assert (names == param_keys) # make sure the bounds are not shuffled #print(param_keys, param_values) # do the compilation here to avoid costly recompilation during the optimization #compiled_objective = self.compile_objective(objective=objective, *args, **kwargs) E = _EvalContainer(Hamiltonian = H, unitary = unitary, Eval=None, param_keys=param_keys, samples=self.samples, passive_angles=passive_angles, save_history=self.save_history, print_level=self.print_level) E.print_level = 0 (E(param_values)) E.print_level = self.print_level infostring += E.infostring if gradient is not None: infostring += "{:15} : {}\n".format("grad instr", gradient) if hessian is not None: infostring += "{:15} : {}\n".format("hess_instr", hessian) compile_gradient = self.method in (self.gradient_based_methods + self.hessian_based_methods) compile_hessian = self.method in self.hessian_based_methods dE = None ddE = None # detect if numerical gradients shall be used # switch off compiling if so if isinstance(gradient, str): if gradient.lower() == 'qng': compile_gradient = False if compile_hessian: raise TequilaException('Sorry, QNG and hessian not yet tested together.') combos = get_qng_combos(objective, initial_values=initial_values, backend=self.backend, samples=self.samples, noise=self.noise) dE = _QngContainer(combos=combos, param_keys=param_keys, passive_angles=passive_angles) infostring += "{:15} : QNG {}\n".format("gradient", dE) else: dE = gradient compile_gradient = False if compile_hessian: compile_hessian = False if hessian is None: hessian = gradient infostring += "{:15} : scipy numerical {}\n".format("gradient", dE) infostring += "{:15} : scipy numerical {}\n".format("hessian", ddE) if isinstance(gradient,dict): if gradient['method'] == 'qng': func = gradient['function'] compile_gradient = False if compile_hessian: raise TequilaException('Sorry, QNG and hessian not yet tested together.') combos = get_qng_combos(objective,func=func, initial_values=initial_values, backend=self.backend, samples=self.samples, noise=self.noise) dE = _QngContainer(combos=combos, param_keys=param_keys, passive_angles=passive_angles) infostring += "{:15} : QNG {}\n".format("gradient", dE) if isinstance(hessian, str): ddE = hessian compile_hessian = False if compile_gradient: dE =_GradContainer(Ham_derivatives = Ham_derivatives, unitary = unitary, Hamiltonian = H, Eval= E, param_keys=param_keys, samples=self.samples, passive_angles=passive_angles, save_history=self.save_history, print_level=self.print_level) dE.print_level = 0 (dE(param_values)) dE.print_level = self.print_level infostring += dE.infostring if self.print_level > 0: print(self) print(infostring) print("{:15} : {}\n".format("active variables", len(active_angles))) Es = [] optimizer_instance = self class SciPyCallback: energies = [] gradients = [] hessians = [] angles = [] real_iterations = 0 def __call__(self, *args, **kwargs): self.energies.append(E.history[-1]) self.angles.append(E.history_angles[-1]) if dE is not None and not isinstance(dE, str): self.gradients.append(dE.history[-1]) if ddE is not None and not isinstance(ddE, str): self.hessians.append(ddE.history[-1]) self.real_iterations += 1 if 'callback' in optimizer_instance.kwargs: optimizer_instance.kwargs['callback'](E.history_angles[-1]) callback = SciPyCallback() res = scipy.optimize.minimize(E, x0=param_values, jac=dE, hess=ddE, args=(Es,), method=self.method, tol=self.tol, bounds=bounds, constraints=self.method_constraints, options=self.method_options, callback=callback) # failsafe since callback is not implemented everywhere if callback.real_iterations == 0: real_iterations = range(len(E.history)) if self.save_history: self.history.energies = callback.energies self.history.energy_evaluations = E.history self.history.angles = callback.angles self.history.angles_evaluations = E.history_angles self.history.gradients = callback.gradients self.history.hessians = callback.hessians if dE is not None and not isinstance(dE, str): self.history.gradients_evaluations = dE.history if ddE is not None and not isinstance(ddE, str): self.history.hessians_evaluations = ddE.history # some methods like "cobyla" do not support callback functions if len(self.history.energies) == 0: self.history.energies = E.history self.history.angles = E.history_angles # some scipy methods always give back the last value and not the minimum (e.g. cobyla) ea = sorted(zip(E.history, E.history_angles), key=lambda x: x[0]) E_final = ea[0][0] angles_final = ea[0][1] #dict((param_keys[i], res.x[i]) for i in range(len(param_keys))) angles_final = {**angles_final, **passive_angles} return SciPyResults(energy=E_final, history=self.history, variables=format_variable_dictionary(angles_final), scipy_result=res) def minimize(Hamiltonian, unitary, gradient: typing.Union[str, typing.Dict[Variable, Objective]] = None, hessian: typing.Union[str, typing.Dict[typing.Tuple[Variable, Variable], Objective]] = None, initial_values: typing.Dict[typing.Hashable, numbers.Real] = None, variables: typing.List[typing.Hashable] = None, samples: int = None, maxiter: int = 100, backend: str = None, backend_options: dict = None, noise: NoiseModel = None, device: str = None, method: str = "BFGS", tol: float = 1.e-3, method_options: dict = None, method_bounds: typing.Dict[typing.Hashable, numbers.Real] = None, method_constraints=None, silent: bool = False, save_history: bool = True, *args, **kwargs) -> SciPyResults: """ calls the local optimize_scipy scipy funtion instead and pass down the objective construction down Parameters ---------- objective: Objective : The tequila objective to optimize gradient: typing.Union[str, typing.Dict[Variable, Objective], None] : Default value = None): '2-point', 'cs' or '3-point' for numerical gradient evaluation (does not work in combination with all optimizers), dictionary of variables and tequila objective to define own gradient, None for automatic construction (default) Other options include 'qng' to use the quantum natural gradient. hessian: typing.Union[str, typing.Dict[Variable, Objective], None], optional: '2-point', 'cs' or '3-point' for numerical gradient evaluation (does not work in combination with all optimizers), dictionary (keys:tuple of variables, values:tequila objective) to define own gradient, None for automatic construction (default) initial_values: typing.Dict[typing.Hashable, numbers.Real], optional: Initial values as dictionary of Hashable types (variable keys) and floating point numbers. If given None they will all be set to zero variables: typing.List[typing.Hashable], optional: List of Variables to optimize samples: int, optional: samples/shots to take in every run of the quantum circuits (None activates full wavefunction simulation) maxiter: int : (Default value = 100): max iters to use. backend: str, optional: Simulator backend, will be automatically chosen if set to None backend_options: dict, optional: Additional options for the backend Will be unpacked and passed to the compiled objective in every call noise: NoiseModel, optional: a NoiseModel to apply to all expectation values in the objective. method: str : (Default = "BFGS"): Optimization method (see scipy documentation, or 'available methods') tol: float : (Default = 1.e-3): Convergence tolerance for optimization (see scipy documentation) method_options: dict, optional: Dictionary of options (see scipy documentation) method_bounds: typing.Dict[typing.Hashable, typing.Tuple[float, float]], optional: bounds for the variables (see scipy documentation) method_constraints: optional: (see scipy documentation silent: bool : No printout if True save_history: bool: Save the history throughout the optimization Returns ------- SciPyReturnType: the results of optimization """ if isinstance(gradient, dict) or hasattr(gradient, "items"): if all([isinstance(x, Objective) for x in gradient.values()]): gradient = format_variable_dictionary(gradient) if isinstance(hessian, dict) or hasattr(hessian, "items"): if all([isinstance(x, Objective) for x in hessian.values()]): hessian = {(assign_variable(k[0]), assign_variable([k[1]])): v for k, v in hessian.items()} method_bounds = format_variable_dictionary(method_bounds) # set defaults optimizer = optimize_scipy(save_history=save_history, maxiter=maxiter, method=method, method_options=method_options, method_bounds=method_bounds, method_constraints=method_constraints, silent=silent, backend=backend, backend_options=backend_options, device=device, samples=samples, noise_model=noise, tol=tol, *args, **kwargs) if initial_values is not None: initial_values = {assign_variable(k): v for k, v in initial_values.items()} return optimizer(Hamiltonian, unitary, gradient=gradient, hessian=hessian, initial_values=initial_values, variables=variables, *args, **kwargs)
24,489
42.732143
144
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_0.7/energy_optimization.py
import tequila as tq import numpy as np from tequila.objective.objective import Variable import openfermion from hacked_openfermion_qubit_operator import ParamQubitHamiltonian from typing import Union from vqe_utils import convert_PQH_to_tq_QH, convert_tq_QH_to_PQH,\ fold_unitary_into_hamiltonian from grad_hacked import grad from scipy_optimizer import minimize import scipy import random # guess we could substitute that with numpy.random #TODO import argparse import pickle as pk import sys sys.path.insert(0, '../../../') #sys.path.insert(0, '../') # This needs to be properly integrated somewhere else at some point # from tn_update.qq import contract_energy, optimize_wavefunctions from tn_update.my_mpo import * from tn_update.wfn_optimization import contract_energy_mpo, optimize_wavefunctions_mpo, initialize_wfns_randomly def energy_from_wfn_opti(hamiltonian: tq.QubitHamiltonian, n_qubits: int, guess_wfns=None, TOL=1e-4) -> tuple: ''' Get energy using a tensornetwork based method ~ power method (here as blackbox) ''' d = int(2**(n_qubits/2)) # Build MPO h_mpo = MyMPO(hamiltonian=hamiltonian, n_qubits=n_qubits, maxdim=500) h_mpo.make_mpo_from_hamiltonian() # Optimize wavefunctions based on random guess out = None it = 0 while out is None: # Set up random initial guesses for subsystems it += 1 if guess_wfns is None: psiL_rand = initialize_wfns_randomly(d, n_qubits//2) psiR_rand = initialize_wfns_randomly(d, n_qubits//2) else: psiL_rand = guess_wfns[0] psiR_rand = guess_wfns[1] out = optimize_wavefunctions_mpo(h_mpo, psiL_rand, psiR_rand, TOL=TOL, silent=True) energy_rand = out[0] optimal_wfns = [out[1], out[2]] return energy_rand, optimal_wfns def combine_two_clusters(H: tq.QubitHamiltonian, subsystems: list, circ_list: list) -> float: ''' E = nuc_rep + \sum_j c_j <0_A | U_A+ sigma_j|A U_A | 0_A><0_B | U_B+ sigma_j|B U_B | 0_B> i ) Split up Hamiltonian into vector c = [c_j], all sigmas of system A and system B ii ) Two vectors of ExpectationValues E_A=[E(U_A, sigma_j|A)], E_B=[E(U_B, sigma_j|B)] iii) Minimize vectors from ii) iv ) Perform weighted sum \sum_j c_[j] E_A[j] E_B[j] result = nuc_rep + iv) Finishing touch inspired by private tequila-repo / pair-separated objective This is still rather inefficient/unoptimized Can still prune out near-zero coefficients c_j ''' objective = 0.0 n_subsystems = len(subsystems) # Over all Paulistrings in the Hamiltonian for p_index, pauli in enumerate(H.paulistrings): # Gather coefficient coeff = pauli.coeff.real # Empty dictionary for operations: # to be filled with another dictionary per subsystem, where then # e.g. X(0)Z(1)Y(2)X(4) and subsystems=[[0,1,2],[3,4,5]] # -> ops={ 0: {0: 'X', 1: 'Z', 2: 'Y'}, 1: {4: 'X'} } ops = {} for s_index, sys in enumerate(subsystems): for k, v in pauli.items(): if k in sys: if s_index in ops: ops[s_index][k] = v else: ops[s_index] = {k: v} # If no ops gathered -> identity -> nuclear repulsion if len(ops) == 0: #print ("this should only happen ONCE") objective += coeff # If not just identity: # add objective += c_j * prod_subsys( < Paulistring_j_subsys >_{U_subsys} ) elif len(ops) > 0: obj_tmp = coeff for s_index, sys_pauli in ops.items(): #print (s_index, sys_pauli) H_tmp = QubitHamiltonian.from_paulistrings(PauliString(data=sys_pauli)) E_tmp = ExpectationValue(U=circ_list[s_index], H=H_tmp) obj_tmp *= E_tmp objective += obj_tmp initial_values = {k: 0.0 for k in objective.extract_variables()} random_initial_values = {k: 1e-2*np.random.uniform(-1, 1) for k in objective.extract_variables()} method = 'bfgs' # 'bfgs' # 'l-bfgs-b' # 'cobyla' # 'slsqp' curr_res = tq.minimize(method=method, objective=objective, initial_values=initial_values, gradient='two-point', backend='qulacs', method_options={"finite_diff_rel_step": 1e-3}) return curr_res.energy def energy_from_tq_qcircuit(hamiltonian: Union[tq.QubitHamiltonian, ParamQubitHamiltonian], n_qubits: int, circuit = Union[list, tq.QCircuit], subsystems: list = [[0,1,2,3,4,5]], initial_guess = None)-> tuple: ''' Get minimal energy using tequila ''' result = None # If only one circuit handed over, just run simple VQE if isinstance(circuit, list) and len(circuit) == 1: circuit = circuit[0] if isinstance(circuit, tq.QCircuit): if isinstance(hamiltonian, tq.QubitHamiltonian): E = tq.ExpectationValue(H=hamiltonian, U=circuit) if initial_guess is None: initial_angles = {k: 0.0 for k in E.extract_variables()} else: initial_angles = initial_guess #print ("optimizing non-param...") result = tq.minimize(objective=E, method='l-bfgs-b', silent=True, backend='qulacs', initial_values=initial_angles) #gradient='two-point', backend='qulacs', #method_options={"finite_diff_rel_step": 1e-4}) elif isinstance(hamiltonian, ParamQubitHamiltonian): if initial_guess is None: raise Exception("Need to provide initial guess for this to work.") initial_angles = None else: initial_angles = initial_guess #print ("optimizing param...") result = minimize(hamiltonian, circuit, method='bfgs', initial_values=initial_angles, backend="qulacs", silent=True) # If more circuits handed over, assume subsystems else: # TODO!! implement initial guess for the combine_two_clusters thing #print ("Should not happen for now...") result = combine_two_clusters(hamiltonian, subsystems, circuit) return result.energy, result.angles def mixed_optimization(hamiltonian: ParamQubitHamiltonian, n_qubits: int, initial_guess: Union[dict, list]=None, init_angles: list=None): ''' Minimizes energy using wfn opti and a parametrized Hamiltonian min_{psi, theta fixed} <psi | H(theta) | psi> --> min_{t, p fixed} <p | H(t) | p> ^---------------------------------------------------^ until convergence ''' energy, optimal_state = None, None H_qh = convert_PQH_to_tq_QH(hamiltonian) var_keys, H_derivs = H_qh._construct_derivatives() print("var keys", var_keys, flush=True) print('var dict', init_angles, flush=True) # if not init_angles: # var_vals = [0. for i in range(len(var_keys))] # initialize with 0 # else: # var_vals = init_angles def build_variable_dict(keys, values): assert(len(keys)==len(values)) out = dict() for idx, key in enumerate(keys): out[key] = complex(values[idx]) return out var_dict = init_angles var_vals = [*init_angles.values()] assert(build_variable_dict(var_keys, var_vals) == var_dict) def wrap_energy_eval(psi): ''' like energy_from_wfn_opti but instead of optimize get inner product ''' def energy_eval_fn(x): var_dict = build_variable_dict(var_keys, x) H_qh_fix = H_qh(var_dict) H_mpo = MyMPO(hamiltonian=H_qh_fix, n_qubits=n_qubits, maxdim=500) H_mpo.make_mpo_from_hamiltonian() return contract_energy_mpo(H_mpo, psi[0], psi[1]) return energy_eval_fn def wrap_gradient_eval(psi): ''' call derivatives with updated variable list ''' def gradient_eval_fn(x): variables = build_variable_dict(var_keys, x) deriv_expectations = H_derivs.values() # list of ParamQubitHamiltonian's deriv_qhs = [convert_PQH_to_tq_QH(d) for d in deriv_expectations] deriv_qhs = [d(variables) for d in deriv_qhs] # list of tq.QubitHamiltonian's # print(deriv_qhs) deriv_mpos = [MyMPO(hamiltonian=d, n_qubits=n_qubits, maxdim=500)\ for d in deriv_qhs] # print(deriv_mpos[0].n_qubits) for d in deriv_mpos: d.make_mpo_from_hamiltonian() # deriv_mpos = [d.make_mpo_from_hamiltonian() for d in deriv_mpos] return np.asarray([contract_energy_mpo(d, psi[0], psi[1]) for d in deriv_mpos]) return gradient_eval_fn def do_wfn_opti(values, guess_wfns, TOL): # H_qh = H_qh(H_vars) var_dict = build_variable_dict(var_keys, values) en, psi = energy_from_wfn_opti(H_qh(var_dict), n_qubits=n_qubits, guess_wfns=guess_wfns, TOL=TOL) return en, psi def do_param_opti(psi, x0): result = scipy.optimize.minimize(fun=wrap_energy_eval(psi), jac=wrap_gradient_eval(psi), method='bfgs', x0=x0, options={'maxiter': 4}) # print(result) return result e_prev, psi_prev = 123., None # print("iguess", initial_guess) e_curr, psi_curr = do_wfn_opti(var_vals, initial_guess, 1e-5) print('first eval', e_curr, flush=True) def converged(e_prev, e_curr, TOL=1e-4): return True if np.abs(e_prev-e_curr) < TOL else False it = 0 var_prev = var_vals print("vars before comp", var_prev, flush=True) while not converged(e_prev, e_curr) and it < 50: e_prev, psi_prev = e_curr, psi_curr # print('before param opti') res = do_param_opti(psi_curr, var_prev) var_curr = res['x'] print('curr vars', var_curr, flush=True) e_curr = res['fun'] print('en before wfn opti', e_curr, flush=True) # print("iiiiiguess", psi_prev) e_curr, psi_curr = do_wfn_opti(var_curr, psi_prev, 1e-3) print('en after wfn opti', e_curr, flush=True) it += 1 print('at iteration', it, flush=True) return e_curr, psi_curr # optimize parameters with fixed wavefunction # define/wrap energy function - given |p>, evaluate <p|H(t)|p> ''' def wrap_gradient(objective: typing.Union[Objective, QTensor], no_compile=False, *args, **kwargs): def gradient_fn(variable: Variable = None): return grad(objective: typing.Union[Objective, QTensor], variable: Variable = None, no_compile=False, *args, **kwargs) return grad_fn ''' def minimize_energy(hamiltonian: Union[ParamQubitHamiltonian, tq.QubitHamiltonian], n_qubits: int, type_energy_eval: str='wfn', cluster_circuit: tq.QCircuit=None, initial_guess=None, initial_mixed_angles: dict=None) -> float: ''' Minimizes energy functional either according a power-method inspired shortcut ('wfn') or using a unitary circuit ('qc') ''' if type_energy_eval == 'wfn': if isinstance(hamiltonian, tq.QubitHamiltonian): energy, optimal_state = energy_from_wfn_opti(hamiltonian, n_qubits, initial_guess) elif isinstance(hamiltonian, ParamQubitHamiltonian): init_angles = initial_mixed_angles energy, optimal_state = mixed_optimization(hamiltonian=hamiltonian, n_qubits=n_qubits, initial_guess=initial_guess, init_angles=init_angles) elif type_energy_eval == 'qc': if cluster_circuit is None: raise Exception("Need to hand over circuit!") energy, optimal_state = energy_from_tq_qcircuit(hamiltonian, n_qubits, cluster_circuit, [[0,1,2,3],[4,5,6,7]], initial_guess) else: raise Exception("Option not implemented!") return energy, optimal_state
12,457
43.021201
225
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_0.7/parallel_annealing.py
import tequila as tq import multiprocessing import copy from time import sleep from mutation_options import * from pathos.multiprocessing import ProcessingPool as Pool def evolve_population(hamiltonian, type_energy_eval, cluster_circuit, process_id, num_offsprings, actions_ratio, tasks, results): """ This function carries a single step of the simulated annealing on a single member of the generation args: process_id: A unique identifier for each process num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for mutations tasks: multiprocessing queue to pass family_id, instructions and current_fitness family_id: A unique identifier for each family instructions: An object consisting of the instructions in the quantum circuit current_fitness: Current fitness value of the circuit results: multiprocessing queue to pass results back """ #print('[%s] evaluation routine starts' % process_id) while True: try: #getting parameters for mutation and carrying it family_id, instructions, current_fitness = tasks.get() #check if patience has been exhausted if instructions.patience == 0: instructions.reset_to_best() best_child = 0 best_energy = current_fitness new_generations = {} for off_id in range(1, num_offsprings+1): scheduled_ratio = schedule_actions_ratio(epoch=0, steady_ratio=actions_ratio) action = get_action(scheduled_ratio) updated_instructions = copy.deepcopy(instructions) updated_instructions.update_by_action(action) new_fitness, wfn = evaluate_fitness(updated_instructions, hamiltonian, type_energy_eval, cluster_circuit) updated_instructions.set_reference_wfn(wfn) prob_acceptance = get_prob_acceptance(current_fitness, new_fitness, updated_instructions.T, updated_instructions.reference_energy) # need to figure out in case we have two equals new_generations[str(off_id)] = updated_instructions if best_energy > new_fitness: # now two equals -> "first one" is picked best_child = off_id best_energy = new_fitness # decision = np.random.binomial(1, prob_acceptance) # if decision == 0: if best_child == 0: # Add result to the queue instructions.patience -= 1 #print('Reduced patience -- now ' + str(updated_instructions.patience)) if instructions.patience == 0: if instructions.best_previous_instructions: instructions.reset_to_best() else: instructions.update_T() results.put((family_id, instructions, current_fitness)) else: # Add result to the queue if (best_energy < current_fitness): new_generations[str(best_child)].update_best_previous_instructions() new_generations[str(best_child)].update_T() results.put((family_id, new_generations[str(best_child)], best_energy)) except Exception as eeee: #print('[%s] evaluation routine quits' % process_id) #print(eeee) # Indicate finished results.put(-1) break return def evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, num_processors=4, type_energy_eval='wfn', cluster_circuit=None): """ This function does parallel mutation on all the members of the generation and updates the generation args: num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for sampling instructions_dict: A dictionary with the "Instructions" objects the corresponding fitness values as values num_processors: Number of processors to use for parallel run """ # Define IPC manager manager = multiprocessing.Manager() # Define a list (queue) for tasks and computation results tasks = manager.Queue() results = manager.Queue() processes = [] pool = Pool(processes=num_processors) for i in range(num_processors): process_id = 'P%i' % i # Create the process, and connect it to the worker function new_process = multiprocessing.Process(target=evolve_population, args=(hamiltonian, type_energy_eval, cluster_circuit, process_id, num_offsprings, actions_ratio, tasks, results)) # Add new process to the list of processes processes.append(new_process) # Start the process new_process.start() #print("putting tasks") for family_id in instructions_dict: single_task = (family_id, instructions_dict[family_id][0], instructions_dict[family_id][1]) tasks.put(single_task) # Wait while the workers process - change it to something for our case later # sleep(5) multiprocessing.Barrier(num_processors) #print("after barrier") # Quit the worker processes by sending them -1 for i in range(num_processors): tasks.put(-1) # Read calculation results num_finished_processes = 0 while True: # Read result #print("num fin", num_finished_processes) try: family_id, updated_instructions, new_fitness = results.get() instructions_dict[family_id] = (updated_instructions, new_fitness) except: # Process has finished num_finished_processes += 1 if num_finished_processes == num_processors: break for process in processes: process.join() pool.close()
6,456
38.371951
146
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_0.7/single_thread_annealing.py
import tequila as tq import copy from mutation_options import * def st_evolve_population(hamiltonian, type_energy_eval, cluster_circuit, num_offsprings, actions_ratio, tasks): """ This function carries a single step of the simulated annealing on a single member of the generation args: num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for mutations tasks: a tuple of (family_id, instructions and current_fitness) family_id: A unique identifier for each family instructions: An object consisting of the instructions in the quantum circuit current_fitness: Current fitness value of the circuit """ family_id, instructions, current_fitness = tasks #check if patience has been exhausted if instructions.patience == 0: if instructions.best_previous_instructions: instructions.reset_to_best() best_child = 0 best_energy = current_fitness new_generations = {} for off_id in range(1, num_offsprings+1): scheduled_ratio = schedule_actions_ratio(epoch=0, steady_ratio=actions_ratio) action = get_action(scheduled_ratio) updated_instructions = copy.deepcopy(instructions) updated_instructions.update_by_action(action) new_fitness, wfn = evaluate_fitness(updated_instructions, hamiltonian, type_energy_eval, cluster_circuit) updated_instructions.set_reference_wfn(wfn) prob_acceptance = get_prob_acceptance(current_fitness, new_fitness, updated_instructions.T, updated_instructions.reference_energy) # need to figure out in case we have two equals new_generations[str(off_id)] = updated_instructions if best_energy > new_fitness: # now two equals -> "first one" is picked best_child = off_id best_energy = new_fitness # decision = np.random.binomial(1, prob_acceptance) # if decision == 0: if best_child == 0: # Add result to the queue instructions.patience -= 1 #print('Reduced patience -- now ' + str(updated_instructions.patience)) if instructions.patience == 0: if instructions.best_previous_instructions: instructions.reset_to_best() else: instructions.update_T() results = ((family_id, instructions, current_fitness)) else: # Add result to the queue if (best_energy < current_fitness): new_generations[str(best_child)].update_best_previous_instructions() new_generations[str(best_child)].update_T() results = ((family_id, new_generations[str(best_child)], best_energy)) return results def st_evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, type_energy_eval='wfn', cluster_circuit=None): """ This function does a single threas mutation on all the members of the generation and updates the generation args: num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for sampling instructions_dict: A dictionary with the "Instructions" objects the corresponding fitness values as values """ for family_id in instructions_dict: task = (family_id, instructions_dict[family_id][0], instructions_dict[family_id][1]) results = st_evolve_population(hamiltonian, type_energy_eval, cluster_circuit, num_offsprings, actions_ratio, task) family_id, updated_instructions, new_fitness = results instructions_dict[family_id] = (updated_instructions, new_fitness)
4,005
40.298969
138
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_0.7/mutation_options.py
import argparse import numpy as np import random import copy import tequila as tq from typing import Union from collections import Counter from time import time from vqe_utils import convert_PQH_to_tq_QH, convert_tq_QH_to_PQH,\ fold_unitary_into_hamiltonian from energy_optimization import minimize_energy global_seed = 1 class Instructions: ''' TODO need to put some documentation here ''' def __init__(self, n_qubits, mu=2.0, sigma=0.4, alpha=0.9, T_0=1.0, beta=0.5, patience=10, max_non_cliffords=0, reference_energy=0., number=None): # hardcoded values for now self.num_non_cliffords = 0 self.max_non_cliffords = max_non_cliffords # ------------------------ self.starting_patience = patience self.patience = patience self.mu = mu self.sigma = sigma self.alpha = alpha self.beta = beta self.T_0 = T_0 self.T = T_0 self.gates = self.get_random_gates(number=number) self.n_qubits = n_qubits self.positions = self.get_random_positions() self.best_previous_instructions = {} self.reference_energy = reference_energy self.best_reference_wfn = None self.noncliff_replacements = {} def _str(self): print(self.gates) print(self.positions) def set_reference_wfn(self, reference_wfn): self.best_reference_wfn = reference_wfn def update_T(self, update_type: str = 'regular', best_temp=None): # Regular update if update_type.lower() == 'regular': self.T = self.alpha * self.T # Temperature update if patience ran out elif update_type.lower() == 'patience': self.T = self.beta*best_temp + (1-self.beta)*self.T_0 def get_random_gates(self, number=None): ''' Randomly generates a list of gates. number indicates the number of gates to generate otherwise, number will be drawn from a log normal distribution ''' mu, sigma = self.mu, self.sigma full_options = ['X','Y','Z','S','H','CX', 'CY', 'CZ','SWAP', 'UCC2c', 'UCC4c', 'UCC2', 'UCC4'] clifford_options = ['X','Y','Z','S','H','CX', 'CY', 'CZ','SWAP', 'UCC2c', 'UCC4c'] #non_clifford_options = ['UCC2', 'UCC4'] # Gate distribution, selecting number of gates to add k = np.random.lognormal(mu, sigma) k = np.int(k) if number is not None: k = number # Selecting gate types gates = None if self.num_non_cliffords < self.max_non_cliffords: gates = random.choices(full_options, k=k) # with replacement else: gates = random.choices(clifford_options, k=k) new_num_non_cliffords = 0 if "UCC2" in gates: new_num_non_cliffords += Counter(gates)["UCC2"] if "UCC4" in gates: new_num_non_cliffords += Counter(gates)["UCC4"] if (new_num_non_cliffords+self.num_non_cliffords) <= self.max_non_cliffords: self.num_non_cliffords += new_num_non_cliffords else: extra_cliffords = (new_num_non_cliffords+self.num_non_cliffords) - self.max_non_cliffords assert(extra_cliffords >= 0) new_gates = random.choices(clifford_options, k=extra_cliffords) for g in new_gates: try: gates[gates.index("UCC4")] = g except: gates[gates.index("UCC2")] = g self.num_non_cliffords = self.max_non_cliffords if k == 1: if gates == "UCC2c" or gates == "UCC4c": gates = get_string_Cliff_ucc(gates) if gates == "UCC2" or gates == "UCC4": gates = get_string_ucc(gates) else: for ind, gate in enumerate(gates): if gate == "UCC2c" or gate == "UCC4c": gates[ind] = get_string_Cliff_ucc(gate) if gate == "UCC2" or gate == "UCC4": gates[ind] = get_string_ucc(gate) return gates def get_random_positions(self, gates=None): ''' Randomly assign gates to qubits. ''' if gates is None: gates = self.gates n_qubits = self.n_qubits single_qubit = ['X','Y','Z','S','H'] # two_qubit = ['CX','CY','CZ', 'SWAP'] two_qubit = ['CX', 'CY', 'CZ', 'SWAP', 'UCC2c', 'UCC2'] four_qubit = ['UCC4c', 'UCC4'] qubits = list(range(0, n_qubits)) q_positions = [] for gate in gates: if gate in four_qubit: p = random.sample(qubits, k=4) if gate in two_qubit: p = random.sample(qubits, k=2) if gate in single_qubit: p = random.sample(qubits, k=1) if "UCC2" in gate: p = random.sample(qubits, k=2) if "UCC4" in gate: p = random.sample(qubits, k=4) q_positions.append(p) return q_positions def delete(self, number=None): ''' Randomly drops some gates from a clifford instruction set if not specified, the number of gates to drop is sampled from a uniform distribution over all the gates ''' gates = copy.deepcopy(self.gates) positions = copy.deepcopy(self.positions) n_qubits = self.n_qubits if number is not None: num_to_drop = number else: num_to_drop = random.sample(range(1,len(gates)-1), k=1)[0] action_indices = random.sample(range(0,len(gates)-1), k=num_to_drop) for index in sorted(action_indices, reverse=True): if "UCC2_" in str(gates[index]) or "UCC4_" in str(gates[index]): self.num_non_cliffords -= 1 del gates[index] del positions[index] self.gates = gates self.positions = positions #print ('deleted {} gates'.format(num_to_drop)) def add(self, number=None): ''' adds a random selection of clifford gates to the end of a clifford instruction set if number is not specified, the number of gates to add will be drawn from a log normal distribution ''' gates = copy.deepcopy(self.gates) positions = copy.deepcopy(self.positions) n_qubits = self.n_qubits added_instructions = self.get_new_instructions(number=number) gates.extend(added_instructions['gates']) positions.extend(added_instructions['positions']) self.gates = gates self.positions = positions #print ('added {} gates'.format(len(added_instructions['gates']))) def change(self, number=None): ''' change a random number of gates and qubit positions in a clifford instruction set if not specified, the number of gates to change is sampled from a uniform distribution over all the gates ''' gates = copy.deepcopy(self.gates) positions = copy.deepcopy(self.positions) n_qubits = self.n_qubits if number is not None: num_to_change = number else: num_to_change = random.sample(range(1,len(gates)), k=1)[0] action_indices = random.sample(range(0,len(gates)-1), k=num_to_change) added_instructions = self.get_new_instructions(number=num_to_change) for i in range(num_to_change): gates[action_indices[i]] = added_instructions['gates'][i] positions[action_indices[i]] = added_instructions['positions'][i] self.gates = gates self.positions = positions #print ('changed {} gates'.format(len(added_instructions['gates']))) # TODO to be debugged! def prune(self): ''' Prune instructions to remove redundant operations: --> first gate should go beyond subsystems (this assumes expressible enough subsystem-ciruits #TODO later -> this needs subsystem information in here! --> 2 subsequent gates that are their respective inverse can be removed #TODO this might change the number of qubits acted on in theory? ''' pass #print ("DEBUG PRUNE FUNCTION!") # gates = copy.deepcopy(self.gates) # positions = copy.deepcopy(self.positions) # for g_index in range(len(gates)-1): # if (gates[g_index] == gates[g_index+1] and not 'S' in gates[g_index])\ # or (gates[g_index] == 'S' and gates[g_index+1] == 'S-dag')\ # or (gates[g_index] == 'S-dag' and gates[g_index+1] == 'S'): # print(len(gates)) # if positions[g_index] == positions[g_index+1]: # self.gates.pop(g_index) # self.positions.pop(g_index) def update_by_action(self, action: str): ''' Updates instruction dictionary -> Either adds, deletes or changes gates ''' if action == 'delete': try: self.delete() # In case there are too few gates to delete except: pass elif action == 'add': self.add() elif action == 'change': self.change() else: raise Exception("Unknown action type " + action + ".") self.prune() def update_best_previous_instructions(self): ''' Overwrites the best previous instructions with the current ones. ''' self.best_previous_instructions['gates'] = copy.deepcopy(self.gates) self.best_previous_instructions['positions'] = copy.deepcopy(self.positions) self.best_previous_instructions['T'] = copy.deepcopy(self.T) def reset_to_best(self): ''' Overwrites the current instructions with best previous ones. ''' #print ('Patience ran out... resetting to best previous instructions.') self.gates = copy.deepcopy(self.best_previous_instructions['gates']) self.positions = copy.deepcopy(self.best_previous_instructions['positions']) self.patience = copy.deepcopy(self.starting_patience) self.update_T(update_type='patience', best_temp=copy.deepcopy(self.best_previous_instructions['T'])) def get_new_instructions(self, number=None): ''' Returns a a clifford instruction set, a dictionary of gates and qubit positions for building a clifford circuit ''' mu = self.mu sigma = self.sigma n_qubits = self.n_qubits instruction = {} gates = self.get_random_gates(number=number) q_positions = self.get_random_positions(gates) assert(len(q_positions) == len(gates)) instruction['gates'] = gates instruction['positions'] = q_positions # instruction['n_qubits'] = n_qubits # instruction['patience'] = patience # instruction['best_previous_options'] = {} return instruction def replace_cg_w_ncg(self, gate_id): ''' replaces a set of Clifford gates with corresponding non-Cliffords ''' print("gates before", self.gates, flush=True) gate = self.gates[gate_id] if gate == 'X': gate = "Rx" elif gate == 'Y': gate = "Ry" elif gate == 'Z': gate = "Rz" elif gate == 'S': gate = "S_nc" #gate = "Rz" elif gate == 'H': gate = "H_nc" # this does not work??????? # gate = "Ry" elif gate == 'CX': gate = "CRx" elif gate == 'CY': gate = "CRy" elif gate == 'CZ': gate = "CRz" elif gate == 'SWAP':#find a way to change this as well pass # gate = "SWAP" elif "UCC2c" in str(gate): pre_gate = gate.split("_")[0] mid_gate = gate.split("_")[-1] gate = pre_gate + "_" + "UCC2" + "_" +mid_gate elif "UCC4c" in str(gate): pre_gate = gate.split("_")[0] mid_gate = gate.split("_")[-1] gate = pre_gate + "_" + "UCC4" + "_" + mid_gate self.gates[gate_id] = gate print("gates after", self.gates, flush=True) def build_circuit(instructions): ''' constructs a tequila circuit from a clifford instruction set ''' gates = instructions.gates q_positions = instructions.positions init_angles = {} clifford_circuit = tq.QCircuit() # for i in range(1, len(gates)): # TODO len(q_positions) not == len(gates) for i in range(len(gates)): if len(q_positions[i]) == 2: q1, q2 = q_positions[i] elif len(q_positions[i]) == 1: q1 = q_positions[i] q2 = None elif not len(q_positions[i]) == 4: raise Exception("q_positions[i] must have length 1, 2 or 4...") if gates[i] == 'X': clifford_circuit += tq.gates.X(q1) if gates[i] == 'Y': clifford_circuit += tq.gates.Y(q1) if gates[i] == 'Z': clifford_circuit += tq.gates.Z(q1) if gates[i] == 'S': clifford_circuit += tq.gates.S(q1) if gates[i] == 'H': clifford_circuit += tq.gates.H(q1) if gates[i] == 'CX': clifford_circuit += tq.gates.CX(q1, q2) if gates[i] == 'CY': #using generators clifford_circuit += tq.gates.S(q2) clifford_circuit += tq.gates.CX(q1, q2) clifford_circuit += tq.gates.S(q2).dagger() if gates[i] == 'CZ': #using generators clifford_circuit += tq.gates.H(q2) clifford_circuit += tq.gates.CX(q1, q2) clifford_circuit += tq.gates.H(q2) if gates[i] == 'SWAP': clifford_circuit += tq.gates.CX(q1, q2) clifford_circuit += tq.gates.CX(q2, q1) clifford_circuit += tq.gates.CX(q1, q2) if "UCC2c" in str(gates[i]) or "UCC4c" in str(gates[i]): clifford_circuit += get_clifford_UCC_circuit(gates[i], q_positions[i]) # NON-CLIFFORD STUFF FROM HERE ON global global_seed if gates[i] == "S_nc": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.S(q1) clifford_circuit += tq.gates.Rz(angle=var_name, target=q1) if gates[i] == "H_nc": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.H(q1) clifford_circuit += tq.gates.Ry(angle=var_name, target=q1) if gates[i] == "Rx": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.X(q1) clifford_circuit += tq.gates.Rx(angle=var_name, target=q1) if gates[i] == "Ry": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.Y(q1) clifford_circuit += tq.gates.Ry(angle=var_name, target=q1) if gates[i] == "Rz": global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0 clifford_circuit += tq.gates.Z(q1) clifford_circuit += tq.gates.Rz(angle=var_name, target=q1) if gates[i] == "CRx": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = np.pi clifford_circuit += tq.gates.Rx(angle=var_name, target=q2, control=q1) if gates[i] == "CRy": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = np.pi clifford_circuit += tq.gates.Ry(angle=var_name, target=q2, control=q1) if gates[i] == "CRz": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = np.pi clifford_circuit += tq.gates.Rz(angle=var_name, target=q2, control=q1) def get_ucc_init_angles(gate): angle = None pre_gate = gate.split("_")[0] mid_gate = gate.split("_")[-1] if mid_gate == 'Z': angle = 0. elif mid_gate == 'S': angle = 0. elif mid_gate == 'S-dag': angle = 0. else: raise Exception("This should not happen -- center/mid gate should be Z,S,S_dag.") return angle if "UCC2_" in str(gates[i]) or "UCC4_" in str(gates[i]): uccc_circuit = get_non_clifford_UCC_circuit(gates[i], q_positions[i]) clifford_circuit += uccc_circuit try: var_name = uccc_circuit.extract_variables()[0] init_angles[var_name]= get_ucc_init_angles(gates[i]) except: init_angles = {} return clifford_circuit, init_angles def get_non_clifford_UCC_circuit(gate, positions): """ """ pre_cir_dic = {"X":tq.gates.X, "Y":tq.gates.Y, "H":tq.gates.H, "I":None} pre_gate = gate.split("_")[0] pre_gates = pre_gate.split(*"#") pre_circuit = tq.QCircuit() for i, pos in enumerate(positions): try: pre_circuit += pre_cir_dic[pre_gates[i]](pos) except: pass for i, pos in enumerate(positions[:-1]): pre_circuit += tq.gates.CX(pos, positions[i+1]) global global_seed mid_gate = gate.split("_")[-1] mid_circuit = tq.QCircuit() if mid_gate == "S": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit += tq.gates.S(positions[-1]) mid_circuit += tq.gates.Rz(angle=tq.Variable(var_name), target=positions[-1]) elif mid_gate == "S-dag": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit += tq.gates.S(positions[-1]).dagger() mid_circuit += tq.gates.Rz(angle=tq.Variable(var_name), target=positions[-1]) elif mid_gate == "Z": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit += tq.gates.Z(positions[-1]) mid_circuit += tq.gates.Rz(angle=tq.Variable(var_name), target=positions[-1]) return pre_circuit + mid_circuit + pre_circuit.dagger() def get_string_Cliff_ucc(gate): """ this function randomly sample basis change and mid circuit elements for a ucc-type clifford circuit and adds it to the gate """ pre_circ_comp = ["X", "Y", "H", "I"] mid_circ_comp = ["S", "S-dag", "Z"] p = None if "UCC2c" in gate: p = random.sample(pre_circ_comp, k=2) elif "UCC4c" in gate: p = random.sample(pre_circ_comp, k=4) pre_gate = "#".join([str(item) for item in p]) mid_gate = random.sample(mid_circ_comp, k=1)[0] return str(pre_gate + "_" + gate + "_" + mid_gate) def get_string_ucc(gate): """ this function randomly sample basis change and mid circuit elements for a ucc-type clifford circuit and adds it to the gate """ pre_circ_comp = ["X", "Y", "H", "I"] p = None if "UCC2" in gate: p = random.sample(pre_circ_comp, k=2) elif "UCC4" in gate: p = random.sample(pre_circ_comp, k=4) pre_gate = "#".join([str(item) for item in p]) mid_gate = str(random.random() * 2 * np.pi) return str(pre_gate + "_" + gate + "_" + mid_gate) def get_clifford_UCC_circuit(gate, positions): """ This function creates an approximate UCC excitation circuit using only clifford Gates """ #pre_circ_comp = ["X", "Y", "H", "I"] pre_cir_dic = {"X":tq.gates.X, "Y":tq.gates.Y, "H":tq.gates.H, "I":None} pre_gate = gate.split("_")[0] pre_gates = pre_gate.split(*"#") #pre_gates = [] #if gate == "UCC2": # pre_gates = random.choices(pre_circ_comp, k=2) #if gate == "UCC4": # pre_gates = random.choices(pre_circ_comp, k=4) pre_circuit = tq.QCircuit() for i, pos in enumerate(positions): try: pre_circuit += pre_cir_dic[pre_gates[i]](pos) except: pass for i, pos in enumerate(positions[:-1]): pre_circuit += tq.gates.CX(pos, positions[i+1]) #mid_circ_comp = ["S", "S-dag", "Z"] #mid_gate = random.sample(mid_circ_comp, k=1)[0] mid_gate = gate.split("_")[-1] mid_circuit = tq.QCircuit() if mid_gate == "S": mid_circuit += tq.gates.S(positions[-1]) elif mid_gate == "S-dag": mid_circuit += tq.gates.S(positions[-1]).dagger() elif mid_gate == "Z": mid_circuit += tq.gates.Z(positions[-1]) return pre_circuit + mid_circuit + pre_circuit.dagger() def get_UCC_circuit(gate, positions): """ This function creates an UCC excitation circuit """ #pre_circ_comp = ["X", "Y", "H", "I"] pre_cir_dic = {"X":tq.gates.X, "Y":tq.gates.Y, "H":tq.gates.H, "I":None} pre_gate = gate.split("_")[0] pre_gates = pre_gate.split(*"#") pre_circuit = tq.QCircuit() for i, pos in enumerate(positions): try: pre_circuit += pre_cir_dic[pre_gates[i]](pos) except: pass for i, pos in enumerate(positions[:-1]): pre_circuit += tq.gates.CX(pos, positions[i+1]) mid_gate_val = gate.split("_")[-1] global global_seed np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit = tq.gates.Rz(target=positions[-1], angle=tq.Variable(var_name)) # mid_circ_comp = ["S", "S-dag", "Z"] # mid_gate = random.sample(mid_circ_comp, k=1)[0] # mid_circuit = tq.QCircuit() # if mid_gate == "S": # mid_circuit += tq.gates.S(positions[-1]) # elif mid_gate == "S-dag": # mid_circuit += tq.gates.S(positions[-1]).dagger() # elif mid_gate == "Z": # mid_circuit += tq.gates.Z(positions[-1]) return pre_circuit + mid_circuit + pre_circuit.dagger() def schedule_actions_ratio(epoch: int, action_options: list = ['delete', 'change', 'add'], decay: int = 30, steady_ratio: Union[tuple, list] = [0.2, 0.6, 0.2]) -> list: delete, change, add = tuple(steady_ratio) actions_ratio = [] for action in action_options: if action == 'delete': actions_ratio += [ delete*(1-np.exp(-1*epoch / decay)) ] elif action == 'change': actions_ratio += [ change*(1-np.exp(-1*epoch / decay)) ] elif action == 'add': actions_ratio += [ (1-add)*np.exp(-1*epoch / decay) + add ] else: print('Action type ', action, ' not defined!') # unnecessary for current schedule # if not np.isclose(np.sum(actions_ratio), 1.0): # actions_ratio /= np.sum(actions_ratio) return actions_ratio def get_action(ratio: list = [0.20,0.60,0.20]): ''' randomly chooses an action from delete, change, add ratio denotes the multinomial probabilities ''' choice = np.random.multinomial(n=1, pvals = ratio, size = 1) index = np.where(choice[0] == 1) action_options = ['delete', 'change', 'add'] action = action_options[index[0].item()] return action def get_prob_acceptance(E_curr, E_prev, T, reference_energy): ''' Computes acceptance probability of a certain action based on change in energy ''' delta_E = E_curr - E_prev prob = 0 if delta_E < 0 and E_curr < reference_energy: prob = 1 else: if E_curr < reference_energy: prob = np.exp(-delta_E/T) else: prob = 0 return prob def perform_folding(hamiltonian, circuit): # QubitHamiltonian -> ParamQubitHamiltonian param_hamiltonian = convert_tq_QH_to_PQH(hamiltonian) gates = circuit.gates # Go backwards gates.reverse() for gate in gates: # print("\t folding", gate) param_hamiltonian = (fold_unitary_into_hamiltonian(gate, param_hamiltonian)) # hamiltonian = convert_PQH_to_tq_QH(param_hamiltonian)() hamiltonian = param_hamiltonian return hamiltonian def evaluate_fitness(instructions, hamiltonian: tq.QubitHamiltonian, type_energy_eval: str, cluster_circuit: tq.QCircuit=None) -> tuple: ''' Evaluates fitness=objective=energy given a system for a set of instructions ''' #print ("evaluating fitness") n_qubits = instructions.n_qubits clifford_circuit, init_angles = build_circuit(instructions) # tq.draw(clifford_circuit, backend="cirq") ## TODO check if cluster_circuit is parametrized t0 = time() t1 = None folded_hamiltonian = perform_folding(hamiltonian, clifford_circuit) t1 = time() #print ("\tfolding took ", t1-t0) parametrized = len(clifford_circuit.extract_variables()) > 0 initial_guess = None if not parametrized: folded_hamiltonian = (convert_PQH_to_tq_QH(folded_hamiltonian))() elif parametrized: # TODO clifford_circuit is both ref + rest; so nomenclature is shit here variables = [gate.extract_variables() for gate in clifford_circuit.gates\ if gate.extract_variables()] variables = np.array(variables).flatten().tolist() # TODO this initial_guess is absolutely useless rn and is just causing problems if called initial_guess = { k: 0.1 for k in variables } if instructions.best_reference_wfn is not None: initial_guess = instructions.best_reference_wfn E_new, optimal_state = minimize_energy(hamiltonian=folded_hamiltonian, n_qubits=n_qubits, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit, initial_guess=initial_guess,\ initial_mixed_angles=init_angles) t2 = time() #print ("evaluated fitness; comp was ", t2-t1) #print ("current fitness: ", E_new) return E_new, optimal_state
26,497
34.096689
191
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_0.7/hacked_openfermion_qubit_operator.py
import tequila as tq import sympy import copy #from param_hamiltonian import get_geometry, generate_ucc_ansatz from hacked_openfermion_symbolic_operator import SymbolicOperator # Define products of all Pauli operators for symbolic multiplication. _PAULI_OPERATOR_PRODUCTS = { ('I', 'I'): (1., 'I'), ('I', 'X'): (1., 'X'), ('X', 'I'): (1., 'X'), ('I', 'Y'): (1., 'Y'), ('Y', 'I'): (1., 'Y'), ('I', 'Z'): (1., 'Z'), ('Z', 'I'): (1., 'Z'), ('X', 'X'): (1., 'I'), ('Y', 'Y'): (1., 'I'), ('Z', 'Z'): (1., 'I'), ('X', 'Y'): (1.j, 'Z'), ('X', 'Z'): (-1.j, 'Y'), ('Y', 'X'): (-1.j, 'Z'), ('Y', 'Z'): (1.j, 'X'), ('Z', 'X'): (1.j, 'Y'), ('Z', 'Y'): (-1.j, 'X') } _clifford_h_products = { ('I') : (1., 'I'), ('X') : (1., 'Z'), ('Y') : (-1., 'Y'), ('Z') : (1., 'X') } _clifford_s_products = { ('I') : (1., 'I'), ('X') : (-1., 'Y'), ('Y') : (1., 'X'), ('Z') : (1., 'Z') } _clifford_s_dag_products = { ('I') : (1., 'I'), ('X') : (1., 'Y'), ('Y') : (-1., 'X'), ('Z') : (1., 'Z') } _clifford_cx_products = { ('I', 'I'): (1., 'I', 'I'), ('I', 'X'): (1., 'I', 'X'), ('I', 'Y'): (1., 'Z', 'Y'), ('I', 'Z'): (1., 'Z', 'Z'), ('X', 'I'): (1., 'X', 'X'), ('X', 'X'): (1., 'X', 'I'), ('X', 'Y'): (1., 'Y', 'Z'), ('X', 'Z'): (-1., 'Y', 'Y'), ('Y', 'I'): (1., 'Y', 'X'), ('Y', 'X'): (1., 'Y', 'I'), ('Y', 'Y'): (-1., 'X', 'Z'), ('Y', 'Z'): (1., 'X', 'Y'), ('Z', 'I'): (1., 'Z', 'I'), ('Z', 'X'): (1., 'Z', 'X'), ('Z', 'Y'): (1., 'I', 'Y'), ('Z', 'Z'): (1., 'I', 'Z'), } _clifford_cy_products = { ('I', 'I'): (1., 'I', 'I'), ('I', 'X'): (1., 'Z', 'X'), ('I', 'Y'): (1., 'I', 'Y'), ('I', 'Z'): (1., 'Z', 'Z'), ('X', 'I'): (1., 'X', 'Y'), ('X', 'X'): (-1., 'Y', 'Z'), ('X', 'Y'): (1., 'X', 'I'), ('X', 'Z'): (-1., 'Y', 'X'), ('Y', 'I'): (1., 'Y', 'Y'), ('Y', 'X'): (1., 'X', 'Z'), ('Y', 'Y'): (1., 'Y', 'I'), ('Y', 'Z'): (-1., 'X', 'X'), ('Z', 'I'): (1., 'Z', 'I'), ('Z', 'X'): (1., 'I', 'X'), ('Z', 'Y'): (1., 'Z', 'Y'), ('Z', 'Z'): (1., 'I', 'Z'), } _clifford_cz_products = { ('I', 'I'): (1., 'I', 'I'), ('I', 'X'): (1., 'Z', 'X'), ('I', 'Y'): (1., 'Z', 'Y'), ('I', 'Z'): (1., 'I', 'Z'), ('X', 'I'): (1., 'X', 'Z'), ('X', 'X'): (-1., 'Y', 'Y'), ('X', 'Y'): (-1., 'Y', 'X'), ('X', 'Z'): (1., 'X', 'I'), ('Y', 'I'): (1., 'Y', 'Z'), ('Y', 'X'): (-1., 'X', 'Y'), ('Y', 'Y'): (1., 'X', 'X'), ('Y', 'Z'): (1., 'Y', 'I'), ('Z', 'I'): (1., 'Z', 'I'), ('Z', 'X'): (1., 'I', 'X'), ('Z', 'Y'): (1., 'I', 'Y'), ('Z', 'Z'): (1., 'Z', 'Z'), } COEFFICIENT_TYPES = (int, float, complex, sympy.Expr, tq.Variable) class ParamQubitHamiltonian(SymbolicOperator): @property def actions(self): """The allowed actions.""" return ('X', 'Y', 'Z') @property def action_strings(self): """The string representations of the allowed actions.""" return ('X', 'Y', 'Z') @property def action_before_index(self): """Whether action comes before index in string representations.""" return True @property def different_indices_commute(self): """Whether factors acting on different indices commute.""" return True def renormalize(self): """Fix the trace norm of an operator to 1""" norm = self.induced_norm(2) if numpy.isclose(norm, 0.0): raise ZeroDivisionError('Cannot renormalize empty or zero operator') else: self /= norm def _simplify(self, term, coefficient=1.0): """Simplify a term using commutator and anti-commutator relations.""" if not term: return coefficient, term term = sorted(term, key=lambda factor: factor[0]) new_term = [] left_factor = term[0] for right_factor in term[1:]: left_index, left_action = left_factor right_index, right_action = right_factor # Still on the same qubit, keep simplifying. if left_index == right_index: new_coefficient, new_action = _PAULI_OPERATOR_PRODUCTS[ left_action, right_action] left_factor = (left_index, new_action) coefficient *= new_coefficient # Reached different qubit, save result and re-initialize. else: if left_action != 'I': new_term.append(left_factor) left_factor = right_factor # Save result of final iteration. if left_factor[1] != 'I': new_term.append(left_factor) return coefficient, tuple(new_term) def _clifford_simplify_h(self, qubit): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 for left, right in term: if left == qubit: coeff, new_pauli = _clifford_h_products[right] new_term.append(tuple((left, new_pauli))) else: new_term.append(tuple((left,right))) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self def _clifford_simplify_s(self, qubit): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 for left, right in term: if left == qubit: coeff, new_pauli = _clifford_s_products[right] new_term.append(tuple((left, new_pauli))) else: new_term.append(tuple((left,right))) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self def _clifford_simplify_s_dag(self, qubit): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 for left, right in term: if left == qubit: coeff, new_pauli = _clifford_s_dag_products[right] new_term.append(tuple((left, new_pauli))) else: new_term.append(tuple((left,right))) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self def _clifford_simplify_control_g(self, axis, control_q, target_q): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 target = "I" control = "I" for left, right in term: if left == control_q: control = right elif left == target_q: target = right else: new_term.append(tuple((left,right))) new_c = "I" new_t = "I" if not (target == "I" and control == "I"): if axis == "X": coeff, new_c, new_t = _clifford_cx_products[control, target] if axis == "Y": coeff, new_c, new_t = _clifford_cy_products[control, target] if axis == "Z": coeff, new_c, new_t = _clifford_cz_products[control, target] if new_c != "I": new_term.append(tuple((control_q, new_c))) if new_t != "I": new_term.append(tuple((target_q, new_t))) new_term = sorted(new_term, key=lambda factor: factor[0]) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self if __name__ == "__main__": """geometry = get_geometry("H2", 0.714) print(geometry) basis_set = 'sto-3g' ref_anz, uccsd_anz, ham = generate_ucc_ansatz(geometry, basis_set) print(ham) b_ham = tq.grouping.binary_rep.BinaryHamiltonian.init_from_qubit_hamiltonian(ham) c_ham = tq.grouping.binary_rep.BinaryHamiltonian.init_from_qubit_hamiltonian(ham) print(b_ham) print(b_ham.get_binary()) print(b_ham.get_coeff()) param = uccsd_anz.extract_variables() print(param) for term in b_ham.binary_terms: print(term.coeff) term.set_coeff(param[0]) print(term.coeff) print(b_ham.get_coeff()) d_ham = c_ham.to_qubit_hamiltonian() + b_ham.to_qubit_hamiltonian() """ term = [(2,'X'), (0,'Y'), (3, 'Z')] coeff = tq.Variable("a") coeff = coeff *2.j print(coeff) print(type(coeff)) print(coeff({"a":1})) ham = ParamQubitHamiltonian(term= term, coefficient=coeff) print(ham.terms) print(str(ham)) for term in ham.terms: print(ham.terms[term]({"a":1,"b":2})) term = [(2,'X'), (0,'Z'), (3, 'Z')] coeff = tq.Variable("b") print(coeff({"b":1})) b_ham = ParamQubitHamiltonian(term= term, coefficient=coeff) print(b_ham.terms) print(str(b_ham)) for term in b_ham.terms: print(b_ham.terms[term]({"a":1,"b":2})) coeff = tq.Variable("a")*tq.Variable("b") print(coeff) print(coeff({"a":1,"b":2})) ham *= b_ham print(ham.terms) print(str(ham)) for term in ham.terms: coeff = (ham.terms[term]) print(coeff) print(coeff({"a":1,"b":2})) ham = ham*2. print(ham.terms) print(str(ham))
9,918
29.614198
85
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_0.7/HEA.py
import tequila as tq import numpy as np from tequila import gates as tq_g from tequila.objective.objective import Variable def generate_HEA(num_qubits, circuit_id=11, num_layers=1): """ This function generates different types of hardware efficient circuits as in this paper https://onlinelibrary.wiley.com/doi/full/10.1002/qute.201900070 param: num_qubits (int) -> the number of qubits in the circuit param: circuit_id (int) -> the type of hardware efficient circuit param: num_layers (int) -> the number of layers of the HEA input: num_qubits -> 4 circuit_id -> 11 num_layers -> 1 returns: ansatz (tq.QCircuit()) -> a circuit as shown below 0: ───Ry(0.318309886183791*pi*f((y0,))_0)───Rz(0.318309886183791*pi*f((z0,))_1)───@───────────────────────────────────────────────────────────────────────────────────── │ 1: ───Ry(0.318309886183791*pi*f((y1,))_2)───Rz(0.318309886183791*pi*f((z1,))_3)───X───Ry(0.318309886183791*pi*f((y4,))_8)────Rz(0.318309886183791*pi*f((z4,))_9)────@─── │ 2: ───Ry(0.318309886183791*pi*f((y2,))_4)───Rz(0.318309886183791*pi*f((z2,))_5)───@───Ry(0.318309886183791*pi*f((y5,))_10)───Rz(0.318309886183791*pi*f((z5,))_11)───X─── │ 3: ───Ry(0.318309886183791*pi*f((y3,))_6)───Rz(0.318309886183791*pi*f((z3,))_7)───X───────────────────────────────────────────────────────────────────────────────────── """ circuit = tq.QCircuit() qubits = [i for i in range(num_qubits)] if circuit_id == 1: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 2: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.CNOT(target=qubit, control=qubits[ind]) return circuit elif circuit_id == 3: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=qubit, control=qubits[ind]) count += 1 return circuit elif circuit_id == 4: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=qubit, control=qubits[ind]) count += 1 return circuit elif circuit_id == 5: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): for target in qubits: if control != target: variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=target, control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 6: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=qubits[ind+1], control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=qubits[ind+1], control=control) count += 1 return circuit elif circuit_id == 7: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): for target in qubits: if control != target: variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=target, control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 8: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=qubits[ind+1], control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=qubits[ind+1], control=control) count += 1 return circuit elif circuit_id == 9: count = 0 for _ in range(num_layers): for qubit in qubits: circuit += tq_g.H(qubit) for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.Z(target=qubit, control=qubits[ind]) for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 10: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.Z(target=qubit, control=qubits[ind]) circuit += tq_g.Z(target=qubits[0], control=qubits[-1]) for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 11: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: circuit += tq_g.X(target=qubits[ind+1], control=control) for ind, qubit in enumerate(qubits[1:-1]): variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: circuit += tq_g.X(target=qubits[ind+1], control=control) return circuit elif circuit_id == 12: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: circuit += tq_g.Z(target=qubits[ind+1], control=control) for ind, control in enumerate(qubits[1:-1]): variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = control) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = control) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: circuit += tq_g.Z(target=qubits[ind+1], control=control) return circuit elif circuit_id == 13: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubit, control=qubits[ind]) count += 1 variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubits[0], control=qubits[-1]) count += 1 for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=qubit, target=qubits[ind]) count += 1 variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=qubits[0], target=qubits[-1]) count += 1 return circuit elif circuit_id == 14: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubit, control=qubits[ind]) count += 1 variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubits[0], control=qubits[-1]) count += 1 for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=qubit, target=qubits[ind]) count += 1 variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=qubits[0], target=qubits[-1]) count += 1 return circuit elif circuit_id == 15: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.X(target=qubit, control=qubits[ind]) circuit += tq_g.X(control=qubits[-1], target=qubits[0]) for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.X(control=qubit, target=qubits[ind]) circuit += tq_g.X(target=qubits[-1], control=qubits[0]) return circuit elif circuit_id == 16: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=control, target=qubits[ind+1]) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=control, target=qubits[ind+1]) count += 1 return circuit elif circuit_id == 17: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=control, target=qubits[ind+1]) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=control, target=qubits[ind+1]) count += 1 return circuit elif circuit_id == 18: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[:-1]): variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubit, control=qubits[ind+1]) count += 1 variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubits[-1], control=qubits[0]) count += 1 return circuit elif circuit_id == 19: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[:-1]): variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubit, control=qubits[ind+1]) count += 1 variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubits[-1], control=qubits[0]) count += 1 return circuit
18,425
45.530303
172
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_0.7/grad_hacked.py
from tequila.circuit.compiler import CircuitCompiler from tequila.objective.objective import Objective, ExpectationValueImpl, Variable, \ assign_variable, identity, FixedVariable from tequila import TequilaException from tequila.objective import QTensor from tequila.simulators.simulator_api import compile import typing from numpy import vectorize from tequila.autograd_imports import jax, __AUTOGRAD__BACKEND__ def grad(objective: typing.Union[Objective, QTensor], variable: Variable = None, no_compile=False, *args, **kwargs): ''' wrapper function for getting the gradients of Objectives,ExpectationValues, Unitaries (including single gates), and Transforms. :param obj (QCircuit,ParametrizedGateImpl,Objective,ExpectationValue,Transform,Variable): structure to be differentiated :param variables (list of Variable): parameter with respect to which obj should be differentiated. default None: total gradient. return: dictionary of Objectives, if called on gate, circuit, exp.value, or objective; if Variable or Transform, returns number. ''' if variable is None: # None means that all components are created variables = objective.extract_variables() result = {} if len(variables) == 0: raise TequilaException("Error in gradient: Objective has no variables") for k in variables: assert (k is not None) result[k] = grad(objective, k, no_compile=no_compile) return result else: variable = assign_variable(variable) if isinstance(objective, QTensor): f = lambda x: grad(objective=x, variable=variable, *args, **kwargs) ff = vectorize(f) return ff(objective) if variable not in objective.extract_variables(): return Objective() if no_compile: compiled = objective else: compiler = CircuitCompiler(multitarget=True, trotterized=True, hadamard_power=True, power=True, controlled_phase=True, controlled_rotation=True, gradient_mode=True) compiled = compiler(objective, variables=[variable]) if variable not in compiled.extract_variables(): raise TequilaException("Error in taking gradient. Objective does not depend on variable {} ".format(variable)) if isinstance(objective, ExpectationValueImpl): return __grad_expectationvalue(E=objective, variable=variable) elif objective.is_expectationvalue(): return __grad_expectationvalue(E=compiled.args[-1], variable=variable) elif isinstance(compiled, Objective) or (hasattr(compiled, "args") and hasattr(compiled, "transformation")): return __grad_objective(objective=compiled, variable=variable) else: raise TequilaException("Gradient not implemented for other types than ExpectationValue and Objective.") def __grad_objective(objective: Objective, variable: Variable): args = objective.args transformation = objective.transformation dO = None processed_expectationvalues = {} for i, arg in enumerate(args): if __AUTOGRAD__BACKEND__ == "jax": df = jax.grad(transformation, argnums=i, holomorphic=True) elif __AUTOGRAD__BACKEND__ == "autograd": df = jax.grad(transformation, argnum=i) else: raise TequilaException("Can't differentiate without autograd or jax") # We can detect one simple case where the outer derivative is const=1 if transformation is None or transformation == identity: outer = 1.0 else: outer = Objective(args=args, transformation=df) if hasattr(arg, "U"): # save redundancies if arg in processed_expectationvalues: inner = processed_expectationvalues[arg] else: inner = __grad_inner(arg=arg, variable=variable) processed_expectationvalues[arg] = inner else: # this means this inner derivative is purely variable dependent inner = __grad_inner(arg=arg, variable=variable) if inner == 0.0: # don't pile up zero expectationvalues continue if dO is None: dO = outer * inner else: dO = dO + outer * inner if dO is None: raise TequilaException("caught None in __grad_objective") return dO # def __grad_vector_objective(objective: Objective, variable: Variable): # argsets = objective.argsets # transformations = objective._transformations # outputs = [] # for pos in range(len(objective)): # args = argsets[pos] # transformation = transformations[pos] # dO = None # # processed_expectationvalues = {} # for i, arg in enumerate(args): # if __AUTOGRAD__BACKEND__ == "jax": # df = jax.grad(transformation, argnums=i) # elif __AUTOGRAD__BACKEND__ == "autograd": # df = jax.grad(transformation, argnum=i) # else: # raise TequilaException("Can't differentiate without autograd or jax") # # # We can detect one simple case where the outer derivative is const=1 # if transformation is None or transformation == identity: # outer = 1.0 # else: # outer = Objective(args=args, transformation=df) # # if hasattr(arg, "U"): # # save redundancies # if arg in processed_expectationvalues: # inner = processed_expectationvalues[arg] # else: # inner = __grad_inner(arg=arg, variable=variable) # processed_expectationvalues[arg] = inner # else: # # this means this inner derivative is purely variable dependent # inner = __grad_inner(arg=arg, variable=variable) # # if inner == 0.0: # # don't pile up zero expectationvalues # continue # # if dO is None: # dO = outer * inner # else: # dO = dO + outer * inner # # if dO is None: # dO = Objective() # outputs.append(dO) # if len(outputs) == 1: # return outputs[0] # return outputs def __grad_inner(arg, variable): ''' a modified loop over __grad_objective, which gets derivatives all the way down to variables, return 1 or 0 when a variable is (isnt) identical to var. :param arg: a transform or variable object, to be differentiated :param variable: the Variable with respect to which par should be differentiated. :ivar var: the string representation of variable ''' assert (isinstance(variable, Variable)) if isinstance(arg, Variable): if arg == variable: return 1.0 else: return 0.0 elif isinstance(arg, FixedVariable): return 0.0 elif isinstance(arg, ExpectationValueImpl): return __grad_expectationvalue(arg, variable=variable) elif hasattr(arg, "abstract_expectationvalue"): E = arg.abstract_expectationvalue dE = __grad_expectationvalue(E, variable=variable) return compile(dE, **arg._input_args) else: return __grad_objective(objective=arg, variable=variable) def __grad_expectationvalue(E: ExpectationValueImpl, variable: Variable): ''' implements the analytic partial derivative of a unitary as it would appear in an expectation value. See the paper. :param unitary: the unitary whose gradient should be obtained :param variables (list, dict, str): the variables with respect to which differentiation should be performed. :return: vector (as dict) of dU/dpi as Objective (without hamiltonian) ''' hamiltonian = E.H unitary = E.U if not (unitary.verify()): raise TequilaException("error in grad_expectationvalue unitary is {}".format(unitary)) # fast return if possible if variable not in unitary.extract_variables(): return 0.0 param_gates = unitary._parameter_map[variable] dO = Objective() for idx_g in param_gates: idx, g = idx_g dOinc = __grad_shift_rule(unitary, g, idx, variable, hamiltonian) dO += dOinc assert dO is not None return dO def __grad_shift_rule(unitary, g, i, variable, hamiltonian): ''' function for getting the gradients of directly differentiable gates. Expects precompiled circuits. :param unitary: QCircuit: the QCircuit object containing the gate to be differentiated :param g: a parametrized: the gate being differentiated :param i: Int: the position in unitary at which g appears :param variable: Variable or String: the variable with respect to which gate g is being differentiated :param hamiltonian: the hamiltonian with respect to which unitary is to be measured, in the case that unitary is contained within an ExpectationValue :return: an Objective, whose calculation yields the gradient of g w.r.t variable ''' # possibility for overwride in custom gate construction if hasattr(g, "shifted_gates"): inner_grad = __grad_inner(g.parameter, variable) shifted = g.shifted_gates() dOinc = Objective() for x in shifted: w, g = x Ux = unitary.replace_gates(positions=[i], circuits=[g]) wx = w * inner_grad Ex = Objective.ExpectationValue(U=Ux, H=hamiltonian) dOinc += wx * Ex return dOinc else: raise TequilaException('No shift found for gate {}\nWas the compiler called?'.format(g))
9,886
38.548
132
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_0.7/vqe_utils.py
import tequila as tq import numpy as np from hacked_openfermion_qubit_operator import ParamQubitHamiltonian from openfermion import QubitOperator from HEA import * def get_ansatz_circuit(ansatz_type, geometry, basis_set=None, trotter_steps = 1, name=None, circuit_id=None,num_layers=1): """ This function generates the ansatz for the molecule and the Hamiltonian param: ansatz_type (str) -> the type of the ansatz ('UCCSD, UpCCGSD, SPA, HEA') param: geometry (str) -> the geometry of the molecule param: basis_set (str) -> the basis set for wchich the ansatz has to generated param: trotter_steps (int) -> the number of trotter step to be used in the trotter decomposition param: name (str) -> the name for the madness molecule param: circuit_id (int) -> the type of hardware efficient ansatz param: num_layers (int) -> the number of layers of the HEA e.g.: input: ansatz_type -> "UCCSD" geometry -> "H 0.0 0.0 0.0\nH 0.0 0.0 0.714" basis_set -> 'sto-3g' trotter_steps -> 1 name -> None circuit_id -> None num_layers -> 1 returns: ucc_ansatz (tq.QCircuit()) -> a circuit printed below: circuit: FermionicExcitation(target=(0, 1, 2, 3), control=(), parameter=Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = []) FermionicExcitation(target=(0, 1, 2, 3), control=(), parameter=Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = []) Hamiltonian (tq.QubitHamiltonian()) -> -0.0621+0.1755Z(0)+0.1755Z(1)-0.2358Z(2)-0.2358Z(3)+0.1699Z(0)Z(1) +0.0449Y(0)X(1)X(2)Y(3)-0.0449Y(0)Y(1)X(2)X(3)-0.0449X(0)X(1)Y(2)Y(3) +0.0449X(0)Y(1)Y(2)X(3)+0.1221Z(0)Z(2)+0.1671Z(0)Z(3)+0.1671Z(1)Z(2) +0.1221Z(1)Z(3)+0.1756Z(2)Z(3) fci_ener (float) -> """ ham = tq.QubitHamiltonian() fci_ener = 0.0 ansatz = tq.QCircuit() if ansatz_type == "UCCSD": molecule = tq.Molecule(geometry=geometry, basis_set=basis_set) ansatz = molecule.make_uccsd_ansatz(trotter_steps) ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy(method="fci") elif ansatz_type == "UCCS": molecule = tq.Molecule(geometry=geometry, basis_set=basis_set, backend='psi4') ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy("fci") indices = molecule.make_upccgsd_indices(key='UCCS') print("indices are:", indices) ansatz = molecule.make_upccgsd_layer(indices=indices, include_singles=True, include_doubles=False) elif ansatz_type == "UpCCGSD": molecule = tq.Molecule(name=name, geometry=geometry, n_pno=None) ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy("fci") ansatz = molecule.make_upccgsd_ansatz() elif ansatz_type == "SPA": molecule = tq.Molecule(name=name, geometry=geometry, n_pno=None) ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy("fci") ansatz = molecule.make_upccgsd_ansatz(name="SPA") elif ansatz_type == "HEA": molecule = tq.Molecule(geometry=geometry, basis_set=basis_set) ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy(method="fci") ansatz = generate_HEA(molecule.n_orbitals * 2, circuit_id) else: raise Exception("not implemented any other ansatz, please choose from 'UCCSD, UpCCGSD, SPA, HEA'") return ansatz, ham, fci_ener def get_generator_for_gates(unitary): """ This function takes a unitary gate and returns the generator of the the gate so that it can be padded to the Hamiltonian param: unitary (tq.QGateImpl()) -> the unitary circuit element that has to be converted to a paulistring e.g.: input: unitary -> a FermionicGateImpl object as the one printed below FermionicExcitation(target=(0, 1, 2, 3), control=(), parameter=Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = []) returns: parameter (tq.Variable()) -> (1, 0, 1, 0) generator (tq.QubitHamiltonian()) -> -0.1250Y(0)Y(1)Y(2)X(3)+0.1250Y(0)X(1)Y(2)Y(3) +0.1250X(0)X(1)Y(2)X(3)+0.1250X(0)Y(1)Y(2)Y(3) -0.1250Y(0)X(1)X(2)X(3)-0.1250Y(0)Y(1)X(2)Y(3) -0.1250X(0)Y(1)X(2)X(3)+0.1250X(0)X(1)X(2)Y(3) null_proj (tq.QubitHamiltonian()) -> -0.1250Z(0)Z(1)+0.1250Z(1)Z(3)+0.1250Z(0)Z(3) +0.1250Z(1)Z(2)+0.1250Z(0)Z(2)-0.1250Z(2)Z(3) -0.1250Z(0)Z(1)Z(2)Z(3) """ try: parameter = None generator = None null_proj = None if isinstance(unitary, tq.quantumchemistry.qc_base.FermionicGateImpl): parameter = unitary.extract_variables() generator = unitary.generator null_proj = unitary.p0 else: #getting parameter if unitary.is_parametrized(): parameter = unitary.extract_variables() else: parameter = [None] try: generator = unitary.make_generator(include_controls=True) except: generator = unitary.generator() """if len(parameter) == 0: parameter = [tq.objective.objective.assign_variable(unitary.parameter)]""" return parameter[0], generator, null_proj except Exception as e: print("An Exception happened, details :",e) pass def fold_unitary_into_hamiltonian(unitary, Hamiltonian): """ This function return a list of the resulting Hamiltonian terms after folding the paulistring correspondig to the unitary into the Hamiltonian param: unitary (tq.QGateImpl()) -> the unitary to be folded into the Hamiltonian param: Hamiltonian (ParamQubitHamiltonian()) -> the Hamiltonian of the system e.g.: input: unitary -> a FermionicGateImpl object as the one printed below FermionicExcitation(target=(0, 1, 2, 3), control=(), parameter=Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = []) Hamiltonian -> -0.06214952615456104 [] + -0.044941923860490916 [X0 X1 Y2 Y3] + 0.044941923860490916 [X0 Y1 Y2 X3] + 0.044941923860490916 [Y0 X1 X2 Y3] + -0.044941923860490916 [Y0 Y1 X2 X3] + 0.17547360045040505 [Z0] + 0.16992958569230643 [Z0 Z1] + 0.12212314332112947 [Z0 Z2] + 0.1670650671816204 [Z0 Z3] + 0.17547360045040508 [Z1] + 0.1670650671816204 [Z1 Z2] + 0.12212314332112947 [Z1 Z3] + -0.23578915712819945 [Z2] + 0.17561918557144712 [Z2 Z3] + -0.23578915712819945 [Z3] returns: folded_hamiltonian (ParamQubitHamiltonian()) -> Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [X0 X1 X2 X3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [X0 X1 Y2 Y3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [X0 Y1 X2 Y3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [X0 Y1 Y2 X3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Y0 X1 X2 Y3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Y0 X1 Y2 X3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Y0 Y1 X2 X3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Y0 Y1 Y2 Y3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z1] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z1 Z2] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z1 Z2 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z1 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z2] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z2 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z1] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z1 Z2] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z1 Z2 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z1 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z2] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z2 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z3] """ folded_hamiltonian = ParamQubitHamiltonian() if isinstance(unitary, tq.circuit._gates_impl.DifferentiableGateImpl) and not isinstance(unitary, tq.circuit._gates_impl.PhaseGateImpl): variable, generator, null_proj = get_generator_for_gates(unitary) # print(generator) # print(null_proj) #converting into ParamQubitHamiltonian() c_generator = convert_tq_QH_to_PQH(generator) """c_null_proj = convert_tq_QH_to_PQH(null_proj) print(variable) prod1 = (null_proj*ham*generator - generator*ham*null_proj) print(prod1) #print((Hamiltonian*c_generator)) prod2 = convert_PQH_to_tq_QH(c_null_proj*Hamiltonian*c_generator - c_generator*Hamiltonian*c_null_proj)({var:0.1 for var in variable.extract_variables()}) print(prod2) assert prod1 ==prod2 raise Exception("testing")""" #print("starting", flush=True) #handling the parameterize gates if variable is not None: #print("folding generator") # adding the term: cos^2(\theta)*H temp_ham = ParamQubitHamiltonian().identity() temp_ham *= Hamiltonian temp_ham *= (variable.apply(tq.numpy.cos)**2) #print(convert_PQH_to_tq_QH(temp_ham)({var:1. for var in variable.extract_variables()})) folded_hamiltonian += temp_ham #print("step1 done", flush=True) # adding the term: sin^2(\theta)*G*H*G temp_ham = ParamQubitHamiltonian().identity() temp_ham *= c_generator temp_ham *= Hamiltonian temp_ham *= c_generator temp_ham *= (variable.apply(tq.numpy.sin)**2) #print(convert_PQH_to_tq_QH(temp_ham)({var:1. for var in variable.extract_variables()})) folded_hamiltonian += temp_ham #print("step2 done", flush=True) # adding the term: i*cos^2(\theta)8sin^2(\theta)*(G*H -H*G) temp_ham1 = ParamQubitHamiltonian().identity() temp_ham1 *= c_generator temp_ham1 *= Hamiltonian temp_ham2 = ParamQubitHamiltonian().identity() temp_ham2 *= Hamiltonian temp_ham2 *= c_generator temp_ham = temp_ham1 - temp_ham2 temp_ham *= 1.0j temp_ham *= variable.apply(tq.numpy.sin) * variable.apply(tq.numpy.cos) #print(convert_PQH_to_tq_QH(temp_ham)({var:1. for var in variable.extract_variables()})) folded_hamiltonian += temp_ham #print("step3 done", flush=True) #handling the non-paramterized gates else: raise Exception("This function is not implemented yet") # adding the term: G*H*G folded_hamiltonian += c_generator*Hamiltonian*c_generator #print("Halfway there", flush=True) #handle the FermionicGateImpl gates if null_proj is not None: print("folding null projector") c_null_proj = convert_tq_QH_to_PQH(null_proj) #print("step4 done", flush=True) # adding the term: (1-cos(\theta))^2*P0*H*P0 temp_ham = ParamQubitHamiltonian().identity() temp_ham *= c_null_proj temp_ham *= Hamiltonian temp_ham *= c_null_proj temp_ham *= ((1-variable.apply(tq.numpy.cos))**2) folded_hamiltonian += temp_ham #print("step5 done", flush=True) # adding the term: 2*cos(\theta)*(1-cos(\theta))*(P0*H +H*P0) temp_ham1 = ParamQubitHamiltonian().identity() temp_ham1 *= c_null_proj temp_ham1 *= Hamiltonian temp_ham2 = ParamQubitHamiltonian().identity() temp_ham2 *= Hamiltonian temp_ham2 *= c_null_proj temp_ham = temp_ham1 + temp_ham2 temp_ham *= (variable.apply(tq.numpy.cos)*(1-variable.apply(tq.numpy.cos))) folded_hamiltonian += temp_ham #print("step6 done", flush=True) # adding the term: i*sin(\theta)*(1-cos(\theta))*(G*H*P0 - P0*H*G) temp_ham1 = ParamQubitHamiltonian().identity() temp_ham1 *= c_generator temp_ham1 *= Hamiltonian temp_ham1 *= c_null_proj temp_ham2 = ParamQubitHamiltonian().identity() temp_ham2 *= c_null_proj temp_ham2 *= Hamiltonian temp_ham2 *= c_generator temp_ham = temp_ham1 - temp_ham2 temp_ham *= 1.0j temp_ham *= (variable.apply(tq.numpy.sin)*(1-variable.apply(tq.numpy.cos))) folded_hamiltonian += temp_ham #print("step7 done", flush=True) elif isinstance(unitary, tq.circuit._gates_impl.PhaseGateImpl): if np.isclose(unitary.parameter, np.pi/2.0): return Hamiltonian._clifford_simplify_s(unitary.qubits[0]) elif np.isclose(unitary.parameter, -1.*np.pi/2.0): return Hamiltonian._clifford_simplify_s_dag(unitary.qubits[0]) else: raise Exception("Only DifferentiableGateImpl, PhaseGateImpl(S), Pauligate(X,Y,Z), Controlled(X,Y,Z) and Hadamrd(H) implemented yet") elif isinstance(unitary, tq.circuit._gates_impl.QGateImpl): if unitary.is_controlled(): if unitary.name == "X": return Hamiltonian._clifford_simplify_control_g("X", unitary.control[0], unitary.target[0]) elif unitary.name == "Y": return Hamiltonian._clifford_simplify_control_g("Y", unitary.control[0], unitary.target[0]) elif unitary.name == "Z": return Hamiltonian._clifford_simplify_control_g("Z", unitary.control[0], unitary.target[0]) else: raise Exception("Only DifferentiableGateImpl, PhaseGateImpl(S), Pauligate(X,Y,Z), Controlled(X,Y,Z) and Hadamrd(H) implemented yet") else: if unitary.name == "X": gate = convert_tq_QH_to_PQH(tq.paulis.X(unitary.qubits[0])) return gate*Hamiltonian*gate elif unitary.name == "Y": gate = convert_tq_QH_to_PQH(tq.paulis.Y(unitary.qubits[0])) return gate*Hamiltonian*gate elif unitary.name == "Z": gate = convert_tq_QH_to_PQH(tq.paulis.Z(unitary.qubits[0])) return gate*Hamiltonian*gate elif unitary.name == "H": return Hamiltonian._clifford_simplify_h(unitary.qubits[0]) else: raise Exception("Only DifferentiableGateImpl, PhaseGateImpl(S), Pauligate(X,Y,Z), Controlled(X,Y,Z) and Hadamrd(H) implemented yet") else: raise Exception("Only DifferentiableGateImpl, PhaseGateImpl(S), Pauligate(X,Y,Z), Controlled(X,Y,Z) and Hadamrd(H) implemented yet") return folded_hamiltonian def convert_tq_QH_to_PQH(Hamiltonian): """ This function takes the tequila QubitHamiltonian object and converts into a ParamQubitHamiltonian object. param: Hamiltonian (tq.QubitHamiltonian()) -> the Hamiltonian to be converted e.g: input: Hamiltonian -> -0.0621+0.1755Z(0)+0.1755Z(1)-0.2358Z(2)-0.2358Z(3)+0.1699Z(0)Z(1) +0.0449Y(0)X(1)X(2)Y(3)-0.0449Y(0)Y(1)X(2)X(3)-0.0449X(0)X(1)Y(2)Y(3) +0.0449X(0)Y(1)Y(2)X(3)+0.1221Z(0)Z(2)+0.1671Z(0)Z(3)+0.1671Z(1)Z(2) +0.1221Z(1)Z(3)+0.1756Z(2)Z(3) returns: param_hamiltonian (ParamQubitHamiltonian()) -> -0.06214952615456104 [] + -0.044941923860490916 [X0 X1 Y2 Y3] + 0.044941923860490916 [X0 Y1 Y2 X3] + 0.044941923860490916 [Y0 X1 X2 Y3] + -0.044941923860490916 [Y0 Y1 X2 X3] + 0.17547360045040505 [Z0] + 0.16992958569230643 [Z0 Z1] + 0.12212314332112947 [Z0 Z2] + 0.1670650671816204 [Z0 Z3] + 0.17547360045040508 [Z1] + 0.1670650671816204 [Z1 Z2] + 0.12212314332112947 [Z1 Z3] + -0.23578915712819945 [Z2] + 0.17561918557144712 [Z2 Z3] + -0.23578915712819945 [Z3] """ param_hamiltonian = ParamQubitHamiltonian() Hamiltonian = Hamiltonian.to_openfermion() for term in Hamiltonian.terms: param_hamiltonian += ParamQubitHamiltonian(term = term, coefficient = Hamiltonian.terms[term]) return param_hamiltonian class convert_PQH_to_tq_QH: def __init__(self, Hamiltonian): self.param_hamiltonian = Hamiltonian def __call__(self,variables=None): """ This function takes the ParamQubitHamiltonian object and converts into a tequila QubitHamiltonian object. param: param_hamiltonian (ParamQubitHamiltonian()) -> the Hamiltonian to be converted param: variables (dict) -> a dictionary with the values of the variables in the Hamiltonian coefficient e.g: input: param_hamiltonian -> a [Y0 X2 Z3] + b [Z0 X2 Z3] variables -> {"a":1,"b":2} returns: Hamiltonian (tq.QubitHamiltonian()) -> +1.0000Y(0)X(2)Z(3)+2.0000Z(0)X(2)Z(3) """ Hamiltonian = tq.QubitHamiltonian() for term in self.param_hamiltonian.terms: val = self.param_hamiltonian.terms[term]# + self.param_hamiltonian.imag_terms[term]*1.0j if isinstance(val, tq.Variable) or isinstance(val, tq.objective.objective.Objective): try: for key in variables.keys(): variables[key] = variables[key] #print(variables) val = val(variables) #print(val) except Exception as e: print(e) raise Exception("You forgot to pass the dictionary with the values of the variables") Hamiltonian += tq.QubitHamiltonian(QubitOperator(term=term, coefficient=val)) return Hamiltonian def _construct_derivatives(self, variables=None): """ """ derivatives = {} variable_names = [] for term in self.param_hamiltonian.terms: val = self.param_hamiltonian.terms[term]# + self.param_hamiltonian.imag_terms[term]*1.0j #print(val) if isinstance(val, tq.Variable) or isinstance(val, tq.objective.objective.Objective): variable = val.extract_variables() for var in list(variable): from grad_hacked import grad derivative = ParamQubitHamiltonian(term = term, coefficient = grad(val, var)) if var not in variable_names: variable_names.append(var) if var not in list(derivatives.keys()): derivatives[var] = derivative else: derivatives[var] += derivative return variable_names, derivatives def get_geometry(name, b_l): """ This is utility fucntion that generates tehe geometry string of a Molecule param: name (str) -> name of the molecule param: b_l (float) -> the bond length of the molecule e.g.: input: name -> "H2" b_l -> 0.714 returns: geo_str (str) -> "H 0.0 0.0 0.0\nH 0.0 0.0 0.714" """ geo_str = None if name == "LiH": geo_str = "H 0.0 0.0 0.0\nLi 0.0 0.0 {0}".format(b_l) elif name == "H2": geo_str = "H 0.0 0.0 0.0\nH 0.0 0.0 {0}".format(b_l) elif name == "BeH2": geo_str = "H 0.0 0.0 {0}\nH 0.0 0.0 {1}\nBe 0.0 0.0 0.0".format(b_l,-1*b_l) elif name == "N2": geo_str = "N 0.0 0.0 0.0\nN 0.0 0.0 {0}".format(b_l) elif name == "H4": geo_str = "H 0.0 0.0 0.0\nH 0.0 0.0 {0}\nH 0.0 0.0 {1}\nH 0.0 0.0 {2}".format(b_l,-1*b_l,2*b_l) return geo_str
27,934
51.807183
162
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_0.7/hacked_openfermion_symbolic_operator.py
import abc import copy import itertools import re import warnings import sympy import tequila as tq from tequila.objective.objective import Objective, Variable from openfermion.config import EQ_TOLERANCE COEFFICIENT_TYPES = (int, float, complex, sympy.Expr, Variable, Objective) class SymbolicOperator(metaclass=abc.ABCMeta): """Base class for FermionOperator and QubitOperator. A SymbolicOperator stores an object which represents a weighted sum of terms; each term is a product of individual factors of the form (`index`, `action`), where `index` is a nonnegative integer and the possible values for `action` are determined by the subclass. For instance, for the subclass FermionOperator, `action` can be 1 or 0, indicating raising or lowering, and for QubitOperator, `action` is from the set {'X', 'Y', 'Z'}. The coefficients of the terms are stored in a dictionary whose keys are the terms. SymbolicOperators of the same type can be added or multiplied together. Note: Adding SymbolicOperators is faster using += (as this is done by in-place addition). Specifying the coefficient during initialization is faster than multiplying a SymbolicOperator with a scalar. Attributes: actions (tuple): A tuple of objects representing the possible actions. e.g. for FermionOperator, this is (1, 0). action_strings (tuple): A tuple of string representations of actions. These should be in one-to-one correspondence with actions and listed in the same order. e.g. for FermionOperator, this is ('^', ''). action_before_index (bool): A boolean indicating whether in string representations, the action should come before the index. different_indices_commute (bool): A boolean indicating whether factors acting on different indices commute. terms (dict): **key** (tuple of tuples): A dictionary storing the coefficients of the terms in the operator. The keys are the terms. A term is a product of individual factors; each factor is represented by a tuple of the form (`index`, `action`), and these tuples are collected into a larger tuple which represents the term as the product of its factors. """ @staticmethod def _issmall(val, tol=EQ_TOLERANCE): '''Checks whether a value is near-zero Parses the allowed coefficients above for near-zero tests. Args: val (COEFFICIENT_TYPES) -- the value to be tested tol (float) -- tolerance for inequality ''' if isinstance(val, sympy.Expr): if sympy.simplify(abs(val) < tol) == True: return True return False if isinstance(val, tq.Variable) or isinstance(val, tq.objective.objective.Objective): return False if abs(val) < tol: return True return False @abc.abstractproperty def actions(self): """The allowed actions. Returns a tuple of objects representing the possible actions. """ pass @abc.abstractproperty def action_strings(self): """The string representations of the allowed actions. Returns a tuple containing string representations of the possible actions, in the same order as the `actions` property. """ pass @abc.abstractproperty def action_before_index(self): """Whether action comes before index in string representations. Example: For QubitOperator, the actions are ('X', 'Y', 'Z') and the string representations look something like 'X0 Z2 Y3'. So the action comes before the index, and this function should return True. For FermionOperator, the string representations look like '0^ 1 2^ 3'. The action comes after the index, so this function should return False. """ pass @abc.abstractproperty def different_indices_commute(self): """Whether factors acting on different indices commute.""" pass __hash__ = None def __init__(self, term=None, coefficient=1.): if not isinstance(coefficient, COEFFICIENT_TYPES): raise ValueError('Coefficient must be a numeric type.') # Initialize the terms dictionary self.terms = {} # Detect if the input is the string representation of a sum of terms; # if so, initialization needs to be handled differently if isinstance(term, str) and '[' in term: self._long_string_init(term, coefficient) return # Zero operator: leave the terms dictionary empty if term is None: return # Parse the term # Sequence input if isinstance(term, (list, tuple)): term = self._parse_sequence(term) # String input elif isinstance(term, str): term = self._parse_string(term) # Invalid input type else: raise ValueError('term specified incorrectly.') # Simplify the term coefficient, term = self._simplify(term, coefficient=coefficient) # Add the term to the dictionary self.terms[term] = coefficient def _long_string_init(self, long_string, coefficient): r""" Initialization from a long string representation. e.g. For FermionOperator: '1.5 [2^ 3] + 1.4 [3^ 0]' """ pattern = r'(.*?)\[(.*?)\]' # regex for a term for match in re.findall(pattern, long_string, flags=re.DOTALL): # Determine the coefficient for this term coef_string = re.sub(r"\s+", "", match[0]) if coef_string and coef_string[0] == '+': coef_string = coef_string[1:].strip() if coef_string == '': coef = 1.0 elif coef_string == '-': coef = -1.0 else: try: if 'j' in coef_string: if coef_string[0] == '-': coef = -complex(coef_string[1:]) else: coef = complex(coef_string) else: coef = float(coef_string) except ValueError: raise ValueError( 'Invalid coefficient {}.'.format(coef_string)) coef *= coefficient # Parse the term, simpify it and add to the dict term = self._parse_string(match[1]) coef, term = self._simplify(term, coefficient=coef) if term not in self.terms: self.terms[term] = coef else: self.terms[term] += coef def _validate_factor(self, factor): """Check that a factor of a term is valid.""" if len(factor) != 2: raise ValueError('Invalid factor {}.'.format(factor)) index, action = factor if action not in self.actions: raise ValueError('Invalid action in factor {}. ' 'Valid actions are: {}'.format( factor, self.actions)) if not isinstance(index, int) or index < 0: raise ValueError('Invalid index in factor {}. ' 'The index should be a non-negative ' 'integer.'.format(factor)) def _simplify(self, term, coefficient=1.0): """Simplifies a term.""" if self.different_indices_commute: term = sorted(term, key=lambda factor: factor[0]) return coefficient, tuple(term) def _parse_sequence(self, term): """Parse a term given as a sequence type (i.e., list, tuple, etc.). e.g. For QubitOperator: [('X', 2), ('Y', 0), ('Z', 3)] -> (('Y', 0), ('X', 2), ('Z', 3)) """ if not term: # Empty sequence return () elif isinstance(term[0], int): # Single factor self._validate_factor(term) return (tuple(term),) else: # Check that all factors in the term are valid for factor in term: self._validate_factor(factor) # Return a tuple return tuple(term) def _parse_string(self, term): """Parse a term given as a string. e.g. For FermionOperator: "2^ 3" -> ((2, 1), (3, 0)) """ factors = term.split() # Convert the string representations of the factors to tuples processed_term = [] for factor in factors: # Get the index and action string if self.action_before_index: # The index is at the end of the string; find where it starts. if not factor[-1].isdigit(): raise ValueError('Invalid factor {}.'.format(factor)) index_start = len(factor) - 1 while index_start > 0 and factor[index_start - 1].isdigit(): index_start -= 1 if factor[index_start - 1] == '-': raise ValueError('Invalid index in factor {}. ' 'The index should be a non-negative ' 'integer.'.format(factor)) index = int(factor[index_start:]) action_string = factor[:index_start] else: # The index is at the beginning of the string; find where # it ends if factor[0] == '-': raise ValueError('Invalid index in factor {}. ' 'The index should be a non-negative ' 'integer.'.format(factor)) if not factor[0].isdigit(): raise ValueError('Invalid factor {}.'.format(factor)) index_end = 1 while (index_end <= len(factor) - 1 and factor[index_end].isdigit()): index_end += 1 index = int(factor[:index_end]) action_string = factor[index_end:] # Convert the action string to an action if action_string in self.action_strings: action = self.actions[self.action_strings.index(action_string)] else: raise ValueError('Invalid action in factor {}. ' 'Valid actions are: {}'.format( factor, self.action_strings)) # Add the factor to the list as a tuple processed_term.append((index, action)) # Return a tuple return tuple(processed_term) @property def constant(self): """The value of the constant term.""" return self.terms.get((), 0.0) @constant.setter def constant(self, value): self.terms[()] = value @classmethod def zero(cls): """ Returns: additive_identity (SymbolicOperator): A symbolic operator o with the property that o+x = x+o = x for all operators x of the same class. """ return cls(term=None) @classmethod def identity(cls): """ Returns: multiplicative_identity (SymbolicOperator): A symbolic operator u with the property that u*x = x*u = x for all operators x of the same class. """ return cls(term=()) def __str__(self): """Return an easy-to-read string representation.""" if not self.terms: return '0' string_rep = '' for term, coeff in sorted(self.terms.items()): if self._issmall(coeff): continue tmp_string = '{} ['.format(coeff) for factor in term: index, action = factor action_string = self.action_strings[self.actions.index(action)] if self.action_before_index: tmp_string += '{}{} '.format(action_string, index) else: tmp_string += '{}{} '.format(index, action_string) string_rep += '{}] +\n'.format(tmp_string.strip()) return string_rep[:-3] def __repr__(self): return str(self) def __imul__(self, multiplier): """In-place multiply (*=) with scalar or operator of the same type. Default implementation is to multiply coefficients and concatenate terms. Args: multiplier(complex float, or SymbolicOperator): multiplier Returns: product (SymbolicOperator): Mutated self. """ # Handle scalars. if isinstance(multiplier, COEFFICIENT_TYPES): for term in self.terms: self.terms[term] *= multiplier return self # Handle operator of the same type elif isinstance(multiplier, self.__class__): result_terms = dict() for left_term in self.terms: for right_term in multiplier.terms: left_coefficient = self.terms[left_term] right_coefficient = multiplier.terms[right_term] new_coefficient = left_coefficient * right_coefficient new_term = left_term + right_term new_coefficient, new_term = self._simplify( new_term, coefficient=new_coefficient) # Update result dict. if new_term in result_terms: result_terms[new_term] += new_coefficient else: result_terms[new_term] = new_coefficient self.terms = result_terms return self # Invalid multiplier type else: raise TypeError('Cannot multiply {} with {}'.format( self.__class__.__name__, multiplier.__class__.__name__)) def __mul__(self, multiplier): """Return self * multiplier for a scalar, or a SymbolicOperator. Args: multiplier: A scalar, or a SymbolicOperator. Returns: product (SymbolicOperator) Raises: TypeError: Invalid type cannot be multiply with SymbolicOperator. """ if isinstance(multiplier, COEFFICIENT_TYPES + (type(self),)): product = copy.deepcopy(self) product *= multiplier return product else: raise TypeError('Object of invalid type cannot multiply with ' + type(self) + '.') def __iadd__(self, addend): """In-place method for += addition of SymbolicOperator. Args: addend (SymbolicOperator, or scalar): The operator to add. If scalar, adds to the constant term Returns: sum (SymbolicOperator): Mutated self. Raises: TypeError: Cannot add invalid type. """ if isinstance(addend, type(self)): for term in addend.terms: self.terms[term] = (self.terms.get(term, 0.0) + addend.terms[term]) if self._issmall(self.terms[term]): del self.terms[term] elif isinstance(addend, COEFFICIENT_TYPES): self.constant += addend else: raise TypeError('Cannot add invalid type to {}.'.format(type(self))) return self def __add__(self, addend): """ Args: addend (SymbolicOperator): The operator to add. Returns: sum (SymbolicOperator) """ summand = copy.deepcopy(self) summand += addend return summand def __radd__(self, addend): """ Args: addend (SymbolicOperator): The operator to add. Returns: sum (SymbolicOperator) """ return self + addend def __isub__(self, subtrahend): """In-place method for -= subtraction of SymbolicOperator. Args: subtrahend (A SymbolicOperator, or scalar): The operator to subtract if scalar, subtracts from the constant term. Returns: difference (SymbolicOperator): Mutated self. Raises: TypeError: Cannot subtract invalid type. """ if isinstance(subtrahend, type(self)): for term in subtrahend.terms: self.terms[term] = (self.terms.get(term, 0.0) - subtrahend.terms[term]) if self._issmall(self.terms[term]): del self.terms[term] elif isinstance(subtrahend, COEFFICIENT_TYPES): self.constant -= subtrahend else: raise TypeError('Cannot subtract invalid type from {}.'.format( type(self))) return self def __sub__(self, subtrahend): """ Args: subtrahend (SymbolicOperator): The operator to subtract. Returns: difference (SymbolicOperator) """ minuend = copy.deepcopy(self) minuend -= subtrahend return minuend def __rsub__(self, subtrahend): """ Args: subtrahend (SymbolicOperator): The operator to subtract. Returns: difference (SymbolicOperator) """ return -1 * self + subtrahend def __rmul__(self, multiplier): """ Return multiplier * self for a scalar. We only define __rmul__ for scalars because the left multiply exist for SymbolicOperator and left multiply is also queried as the default behavior. Args: multiplier: A scalar to multiply by. Returns: product: A new instance of SymbolicOperator. Raises: TypeError: Object of invalid type cannot multiply SymbolicOperator. """ if not isinstance(multiplier, COEFFICIENT_TYPES): raise TypeError('Object of invalid type cannot multiply with ' + type(self) + '.') return self * multiplier def __truediv__(self, divisor): """ Return self / divisor for a scalar. Note: This is always floating point division. Args: divisor: A scalar to divide by. Returns: A new instance of SymbolicOperator. Raises: TypeError: Cannot divide local operator by non-scalar type. """ if not isinstance(divisor, COEFFICIENT_TYPES): raise TypeError('Cannot divide ' + type(self) + ' by non-scalar type.') return self * (1.0 / divisor) def __div__(self, divisor): """ For compatibility with Python 2. """ return self.__truediv__(divisor) def __itruediv__(self, divisor): if not isinstance(divisor, COEFFICIENT_TYPES): raise TypeError('Cannot divide ' + type(self) + ' by non-scalar type.') self *= (1.0 / divisor) return self def __idiv__(self, divisor): """ For compatibility with Python 2. """ return self.__itruediv__(divisor) def __neg__(self): """ Returns: negation (SymbolicOperator) """ return -1 * self def __pow__(self, exponent): """Exponentiate the SymbolicOperator. Args: exponent (int): The exponent with which to raise the operator. Returns: exponentiated (SymbolicOperator) Raises: ValueError: Can only raise SymbolicOperator to non-negative integer powers. """ # Handle invalid exponents. if not isinstance(exponent, int) or exponent < 0: raise ValueError( 'exponent must be a non-negative int, but was {} {}'.format( type(exponent), repr(exponent))) # Initialized identity. exponentiated = self.__class__(()) # Handle non-zero exponents. for _ in range(exponent): exponentiated *= self return exponentiated def __eq__(self, other): """Approximate numerical equality (not true equality).""" return self.isclose(other) def __ne__(self, other): return not (self == other) def __iter__(self): self._iter = iter(self.terms.items()) return self def __next__(self): term, coefficient = next(self._iter) return self.__class__(term=term, coefficient=coefficient) def isclose(self, other, tol=EQ_TOLERANCE): """Check if other (SymbolicOperator) is close to self. Comparison is done for each term individually. Return True if the difference between each term in self and other is less than EQ_TOLERANCE Args: other(SymbolicOperator): SymbolicOperator to compare against. """ if not isinstance(self, type(other)): return NotImplemented # terms which are in both: for term in set(self.terms).intersection(set(other.terms)): a = self.terms[term] b = other.terms[term] if not (isinstance(a, sympy.Expr) or isinstance(b, sympy.Expr)): tol *= max(1, abs(a), abs(b)) if self._issmall(a - b, tol) is False: return False # terms only in one (compare to 0.0 so only abs_tol) for term in set(self.terms).symmetric_difference(set(other.terms)): if term in self.terms: if self._issmall(self.terms[term], tol) is False: return False else: if self._issmall(other.terms[term], tol) is False: return False return True def compress(self, abs_tol=EQ_TOLERANCE): """ Eliminates all terms with coefficients close to zero and removes small imaginary and real parts. Args: abs_tol(float): Absolute tolerance, must be at least 0.0 """ new_terms = {} for term in self.terms: coeff = self.terms[term] if isinstance(coeff, sympy.Expr): if sympy.simplify(sympy.im(coeff) <= abs_tol) == True: coeff = sympy.re(coeff) if sympy.simplify(sympy.re(coeff) <= abs_tol) == True: coeff = 1j * sympy.im(coeff) if (sympy.simplify(abs(coeff) <= abs_tol) != True): new_terms[term] = coeff continue if isinstance(val, tq.Variable) or isinstance(val, tq.objective.objective.Objective): continue # Remove small imaginary and real parts if abs(coeff.imag) <= abs_tol: coeff = coeff.real if abs(coeff.real) <= abs_tol: coeff = 1.j * coeff.imag # Add the term if the coefficient is large enough if abs(coeff) > abs_tol: new_terms[term] = coeff self.terms = new_terms def induced_norm(self, order=1): r""" Compute the induced p-norm of the operator. If we represent an operator as :math: `\sum_{j} w_j H_j` where :math: `w_j` are scalar coefficients then this norm is :math: `\left(\sum_{j} \| w_j \|^p \right)^{\frac{1}{p}} where :math: `p` is the order of the induced norm Args: order(int): the order of the induced norm. """ norm = 0. for coefficient in self.terms.values(): norm += abs(coefficient)**order return norm**(1. / order) def many_body_order(self): """Compute the many-body order of a SymbolicOperator. The many-body order of a SymbolicOperator is the maximum length of a term with nonzero coefficient. Returns: int """ if not self.terms: # Zero operator return 0 else: return max( len(term) for term, coeff in self.terms.items() if (self._issmall(coeff) is False)) @classmethod def accumulate(cls, operators, start=None): """Sums over SymbolicOperators.""" total = copy.deepcopy(start or cls.zero()) for operator in operators: total += operator return total def get_operators(self): """Gets a list of operators with a single term. Returns: operators([self.__class__]): A generator of the operators in self. """ for term, coefficient in self.terms.items(): yield self.__class__(term, coefficient) def get_operator_groups(self, num_groups): """Gets a list of operators with a few terms. Args: num_groups(int): How many operators to get in the end. Returns: operators([self.__class__]): A list of operators summing up to self. """ if num_groups < 1: warnings.warn('Invalid num_groups {} < 1.'.format(num_groups), RuntimeWarning) num_groups = 1 operators = self.get_operators() num_groups = min(num_groups, len(self.terms)) for i in range(num_groups): yield self.accumulate( itertools.islice(operators, len(range(i, len(self.terms), num_groups))))
25,797
35.697013
97
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.1/main.py
import tequila as tq import numpy as np from tequila.objective.objective import Variable import openfermion from typing import Union from vqe_utils import convert_PQH_to_tq_QH, convert_tq_QH_to_PQH,\ fold_unitary_into_hamiltonian from energy_optimization import * from do_annealing import * import random # guess we could substitute that with numpy.random #TODO import argparse import pickle as pk import matplotlib.pyplot as plt # Main hyperparameters mu = 2.0 # lognormal dist mean sigma = 0.4 # lognormal dist std T_0 = 1.0 # T_0, initial starting temperature # max_epochs = 25 # num_epochs, max number of iterations max_epochs = 20 # num_epochs, max number of iterations min_epochs = 2 # num_epochs, max number of iterations5 # min_epochs = 20 # num_epochs, max number of iterations tol = 1e-6 # minimum change in energy required, otherwise terminate optimization actions_ratio = [.15, .6, .25] patience = 100 beta = 0.5 max_non_cliffords = 0 type_energy_eval='wfn' num_population = 24 num_offsprings = 20 num_processors = 8 #tuning, input as lists. # parser.add_argument('--alphas', type = float, nargs = '+', help='alpha, temperature decay', required=True) alphas = [0.9] # alpha, temperature decay' #Required be = False h2 = True n2 = False name_prefix = '../../data/' # Construct qubit-Hamiltonian #num_active = 3 #active_orbitals = list(range(num_active)) if be: R1 = rrrr R2 = 1.1 geometry = "be 0.0 0.0 0.0\nh 0.0 0.0 {R1}\nh 0.0 0.0 -{R2}" name = "/h/292/philipps/software/moldata/beh2/beh2_{R1:2.2f}_{R2:2.2f}_180" # adapt of you move data mol = tq.Molecule(name=name.format(R1=R1, R2=R2), geometry=geometry.format(R1=R1,R2=R2), n_pno=None) lqm = mol.local_qubit_map(hcb=False) H = mol.make_hamiltonian().map_qubits(lqm).simplify() #print("FCI ENERGY: ", mol.compute_energy(method="fci")) U_spa = mol.make_upccgsd_ansatz(name="SPA").map_qubits(lqm) U = U_spa elif n2: R1 = rrrr geometry = "N 0.0 0.0 0.0\nN 0.0 0.0 {R1}" # name = "/home/abhinav/matter_lab/moldata/n2/n2_{R1:2.2f}" # adapt of you move data name = "/h/292/philipps/software/moldata/n2/n2_{R1:2.2f}" # adapt of you move data mol = tq.Molecule(name=name.format(R1=R1), geometry=geometry.format(R1=R1), n_pno=None) lqm = mol.local_qubit_map(hcb=False) H = mol.make_hamiltonian().map_qubits(lqm).simplify() # print("FCI ENERGY: ", mol.compute_energy(method="fci")) print("Skip FCI calculation, take old data...") U_spa = mol.make_upccgsd_ansatz(name="SPA").map_qubits(lqm) U = U_spa elif h2: active_orbitals = list(range(3)) mol = tq.Molecule(geometry='H 0.0 0.0 0.0\n H 0.0 0.0 1.1', basis_set='6-31g', active_orbitals=active_orbitals, backend='psi4') H = mol.make_hamiltonian().simplify() print("FCI ENERGY: ", mol.compute_energy(method="fci")) U = mol.make_uccsd_ansatz(trotter_steps=1) # Alternatively, get qubit-Hamiltonian from openfermion/externally # with open("ham_6qubits.txt") as hamstring_file: """if be: with open("ham_beh2_3_3.txt") as hamstring_file: hamstring = hamstring_file.read() #print(hamstring) H = tq.QubitHamiltonian().from_string(string=hamstring, openfermion_format=True) elif h2: with open("ham_6qubits.txt") as hamstring_file: hamstring = hamstring_file.read() #print(hamstring) H = tq.QubitHamiltonian().from_string(string=hamstring, openfermion_format=True)""" n_qubits = len(H.qubits) ''' Option 'wfn': "Shortcut" via wavefunction-optimization using MPO-rep of Hamiltonian Option 'qc': Need to input a proper quantum circuit ''' # Clifford optimization in the context of reduced-size quantum circuits starting_E = 123.456 reference = True if reference: if type_energy_eval.lower() == 'wfn': starting_E, _ = minimize_energy(hamiltonian=H, n_qubits=n_qubits, type_energy_eval='wfn') print('starting energy wfn: {:.5f}'.format(starting_E), flush=True) elif type_energy_eval.lower() == 'qc': starting_E, _ = minimize_energy(hamiltonian=H, n_qubits=n_qubits, type_energy_eval='qc', cluster_circuit=U) print('starting energy spa: {:.5f}'.format(starting_E)) else: raise Exception("type_energy_eval must be either 'wfn' or 'qc', but is", type_energy_eval) starting_E, _ = minimize_energy(hamiltonian=H, n_qubits=n_qubits, type_energy_eval='wfn') """for alpha in alphas: print('Starting optimization, alpha = {:3f}'.format(alpha)) # print('Energy to beat', minimize_energy(H, n_qubits, 'wfn')[0]) simulated_annealing(hamiltonian=H, num_population=num_population, num_offsprings=num_offsprings, num_processors=num_processors, tol=tol, max_epochs=max_epochs, min_epochs=min_epochs, T_0=T_0, alpha=alpha, actions_ratio=actions_ratio, max_non_cliffords=max_non_cliffords, verbose=True, patience=patience, beta=beta, type_energy_eval=type_energy_eval.lower(), cluster_circuit=U, starting_energy=starting_E)""" alter_cliffords = True if alter_cliffords: print("starting to replace cliffords with non-clifford gates to see if that improves the current fitness") replace_cliff_with_non_cliff(hamiltonian=H, num_population=num_population, num_offsprings=num_offsprings, num_processors=num_processors, tol=tol, max_epochs=max_epochs, min_epochs=min_epochs, T_0=T_0, alpha=alphas[0], actions_ratio=actions_ratio, max_non_cliffords=max_non_cliffords, verbose=True, patience=patience, beta=beta, type_energy_eval=type_energy_eval.lower(), cluster_circuit=U, starting_energy=starting_E) # accepted_E, tested_E, decisions, instructions_list, best_instructions, temp, best_E = simulated_annealing(hamiltonian=H, # population=4, # num_mutations=2, # num_processors=1, # tol=opt.tol, max_epochs=opt.max_epochs, # min_epochs=opt.min_epochs, T_0=opt.T_0, alpha=alpha, # mu=opt.mu, sigma=opt.sigma, verbose=True, prev_E = starting_E, patience = 10, beta = 0.5, # energy_eval='qc', # eval_circuit=U # print(best_E) # print(best_instructions) # print(len(accepted_E)) # plt.plot(accepted_E) # plt.show() # #pickling data # data = {'accepted_energies': accepted_E, 'tested_energies': tested_E, # 'decisions': decisions, 'instructions': instructions_list, # 'best_instructions': best_instructions, 'temperature': temp, # 'best_energy': best_E} # f_name = '{}{}_alpha_{:.2f}.pk'.format(opt.name_prefix, r, alpha) # pk.dump(data, open(f_name, 'wb')) # print('Finished optimization, data saved in {}'.format(f_name))
7,368
40.869318
129
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.1/my_mpo.py
import numpy as np import tensornetwork as tn from tensornetwork.backends.abstract_backend import AbstractBackend tn.set_default_backend("pytorch") #tn.set_default_backend("numpy") from typing import List, Union, Text, Optional, Any, Type Tensor = Any import tequila as tq import torch EPS = 1e-12 class SubOperator: """ This is just a helper class to store coefficient, operators and positions in an intermediate format """ def __init__(self, coefficient: float, operators: List, positions: List ): self._coefficient = coefficient self._operators = operators self._positions = positions @property def coefficient(self): return self._coefficient @property def operators(self): return self._operators @property def positions(self): return self._positions class MPOContainer: """ Class that handles the MPO. Is able to set values at certain positions, update containers (wannabe-equivalent to dynamic arrays) and compress the MPO """ def __init__(self, n_qubits: int, ): self.n_qubits = n_qubits self.container = [ np.zeros((1,1,2,2), dtype=np.complex) for q in range(self.n_qubits) ] def get_dim(self): """ Returns max dimension of container """ d = 1 for q in range(len(self.container)): d = max(d, self.container[q].shape[0]) return d def set_tensor(self, qubit: int, set_at: list, add_operator: Union[np.ndarray, float]): """ set_at: where to put data """ # Set a matrix if len(set_at) == 2: self.container[qubit][set_at[0],set_at[1],:,:] = add_operator[:,:] # Set specific values elif len(set_at) == 4: self.container[qubit][set_at[0],set_at[1],set_at[2],set_at[3]] =\ add_operator else: raise Exception("set_at needs to be either of length 2 or 4") def update_container(self, qubit: int, update_dir: list, add_operator: np.ndarray): """ This should mimick a dynamic array update_dir: e.g. [1,1,0,0] -> extend dimension along where there's a 1 the last two dimensions are always 2x2 only """ old_shape = self.container[qubit].shape # print(old_shape) if not len(update_dir) == 4: if len(update_dir) == 2: update_dir += [0, 0] else: raise Exception("update_dir needs to be either of length 2 or 4") if update_dir[2] or update_dir[3]: raise Exception("Last two dims must be zero.") new_shape = tuple(update_dir[i]+old_shape[i] for i in range(len(update_dir))) new_tensor = np.zeros(new_shape, dtype=np.complex) # Copy old values new_tensor[:old_shape[0],:old_shape[1],:,:] = self.container[qubit][:,:,:,:] # Add new values new_tensor[new_shape[0]-1,new_shape[1]-1,:,:] = add_operator[:,:] # Overwrite container self.container[qubit] = new_tensor def compress_mpo(self): """ Compression of MPO via SVD """ n_qubits = len(self.container) for q in range(n_qubits): my_shape = self.container[q].shape self.container[q] =\ self.container[q].reshape((my_shape[0], my_shape[1], -1)) # Go forwards for q in range(n_qubits-1): # Apply permutation [0 1 2] -> [0 2 1] my_tensor = np.swapaxes(self.container[q], 1, 2) my_tensor = my_tensor.reshape((-1, my_tensor.shape[2])) # full_matrices flag corresponds to 'econ' -> no zero-singular values u, s, vh = np.linalg.svd(my_tensor, full_matrices=False) # Count the non-zero singular values num_nonzeros = len(np.argwhere(s>EPS)) # Construct matrix from square root of singular values s = np.diag(np.sqrt(s[:num_nonzeros])) u = u[:,:num_nonzeros] vh = vh[:num_nonzeros,:] # Distribute weights to left- and right singular vectors (@ = np.matmul) u = u @ s vh = s @ vh # Apply permutation [0 1 2] -> [0 2 1] u = u.reshape((self.container[q].shape[0],\ self.container[q].shape[2], -1)) self.container[q] = np.swapaxes(u, 1, 2) self.container[q+1] = tn.ncon([vh, self.container[q+1]], [(-1, 1),(1, -2, -3)]) # Go backwards for q in range(n_qubits-1, 0, -1): my_tensor = self.container[q] my_tensor = my_tensor.reshape((self.container[q].shape[0], -1)) # full_matrices flag corresponds to 'econ' -> no zero-singular values u, s, vh = np.linalg.svd(my_tensor, full_matrices=False) # Count the non-zero singular values num_nonzeros = len(np.argwhere(s>EPS)) # Construct matrix from square root of singular values s = np.diag(np.sqrt(s[:num_nonzeros])) u = u[:,:num_nonzeros] vh = vh[:num_nonzeros,:] # Distribute weights to left- and right singular vectors u = u @ s vh = s @ vh self.container[q] = np.reshape(vh, (num_nonzeros, self.container[q].shape[1], self.container[q].shape[2])) self.container[q-1] = tn.ncon([self.container[q-1], u], [(-1, 1, -3),(1, -2)]) for q in range(n_qubits): my_shape = self.container[q].shape self.container[q] = self.container[q].reshape((my_shape[0],\ my_shape[1],2,2)) # TODO maybe make subclass of tn.FiniteMPO if it makes sense #class my_MPO(tn.FiniteMPO): class MyMPO: """ Class building up on tensornetwork FiniteMPO to handle MPO-Hamiltonians """ def __init__(self, hamiltonian: Union[tq.QubitHamiltonian, Text], # tensors: List[Tensor], backend: Optional[Union[AbstractBackend, Text]] = None, n_qubits: Optional[int] = None, name: Optional[Text] = None, maxdim: Optional[int] = 10000) -> None: # TODO: modifiy docstring """ Initialize a finite MPO object Args: tensors: The mpo tensors. backend: An optional backend. Defaults to the defaulf backend of TensorNetwork. name: An optional name for the MPO. """ self.hamiltonian = hamiltonian self.maxdim = maxdim if n_qubits: self._n_qubits = n_qubits else: self._n_qubits = self.get_n_qubits() @property def n_qubits(self): return self._n_qubits def make_mpo_from_hamiltonian(self): intermediate = self.openfermion_to_intermediate() # for i in range(len(intermediate)): # print(intermediate[i].coefficient) # print(intermediate[i].operators) # print(intermediate[i].positions) self.mpo = self.intermediate_to_mpo(intermediate) def openfermion_to_intermediate(self): # Here, have either a QubitHamiltonian or a file with a of-operator # Start with Qubithamiltonian def get_pauli_matrix(string): pauli_matrices = { 'I': np.array([[1, 0], [0, 1]], dtype=np.complex), 'Z': np.array([[1, 0], [0, -1]], dtype=np.complex), 'X': np.array([[0, 1], [1, 0]], dtype=np.complex), 'Y': np.array([[0, -1j], [1j, 0]], dtype=np.complex) } return pauli_matrices[string.upper()] intermediate = [] first = True # Store all paulistrings in intermediate format for paulistring in self.hamiltonian.paulistrings: coefficient = paulistring.coeff # print(coefficient) operators = [] positions = [] # Only first one should be identity -> distribute over all if first and not paulistring.items(): positions += [] operators += [] first = False elif not first and not paulistring.items(): raise Exception("Only first Pauli should be identity.") # Get operators and where they act for k,v in paulistring.items(): positions += [k] operators += [get_pauli_matrix(v)] tmp_op = SubOperator(coefficient=coefficient, operators=operators, positions=positions) intermediate += [tmp_op] # print("len intermediate = num Pauli strings", len(intermediate)) return intermediate def build_single_mpo(self, intermediate, j): # Set MPO Container n_qubits = self._n_qubits mpo = MPOContainer(n_qubits=n_qubits) # *********************************************************************** # Set first entries (of which we know that they are 2x2-matrices) # Typically, this is an identity my_coefficient = intermediate[j].coefficient my_positions = intermediate[j].positions my_operators = intermediate[j].operators for q in range(n_qubits): if not q in my_positions: mpo.set_tensor(qubit=q, set_at=[0,0], add_operator=np.complex(my_coefficient)**(1/n_qubits)* np.eye(2)) elif q in my_positions: my_pos_index = my_positions.index(q) mpo.set_tensor(qubit=q, set_at=[0,0], add_operator=np.complex(my_coefficient)**(1/n_qubits)* my_operators[my_pos_index]) # *********************************************************************** # All other entries # while (j smaller than number of intermediates left) and mpo.dim() <= self.maxdim # Re-write this based on positions keyword! j += 1 while j < len(intermediate) and mpo.get_dim() < self.maxdim: # """ my_coefficient = intermediate[j].coefficient my_positions = intermediate[j].positions my_operators = intermediate[j].operators for q in range(n_qubits): # It is guaranteed that every index appears only once in positions if q == 0: update_dir = [0,1] elif q == n_qubits-1: update_dir = [1,0] else: update_dir = [1,1] # If there's an operator on my position, add that if q in my_positions: my_pos_index = my_positions.index(q) mpo.update_container(qubit=q, update_dir=update_dir, add_operator= np.complex(my_coefficient)**(1/n_qubits)* my_operators[my_pos_index]) # Else add an identity else: mpo.update_container(qubit=q, update_dir=update_dir, add_operator= np.complex(my_coefficient)**(1/n_qubits)* np.eye(2)) if not j % 100: mpo.compress_mpo() #print("\t\tAt iteration ", j, " MPO has dimension ", mpo.get_dim()) j += 1 mpo.compress_mpo() #print("\tAt final iteration ", j-1, " MPO has dimension ", mpo.get_dim()) return mpo, j def intermediate_to_mpo(self, intermediate): n_qubits = self._n_qubits # TODO Change to multiple MPOs mpo_list = [] j_global = 0 num_mpos = 0 # Start with 0, then final one is correct while j_global < len(intermediate): current_mpo, j_global = self.build_single_mpo(intermediate, j_global) mpo_list += [current_mpo] num_mpos += 1 return mpo_list def construct_matrix(self): # TODO extend to lists of MPOs ''' Recover matrix, e.g. to compare with Hamiltonian that we get from tq ''' mpo = self.mpo # Contract over all bond indices # mpo.container has indices [bond, bond, physical, physical] n_qubits = self._n_qubits d = int(2**(n_qubits/2)) first = True H = None #H = np.zeros((d,d,d,d), dtype='complex') # Define network nodes # | | | | # -O--O--...--O--O- # | | | | for m in mpo: assert(n_qubits == len(m.container)) nodes = [tn.Node(m.container[q], name=str(q)) for q in range(n_qubits)] # Connect network (along double -- above) for q in range(n_qubits-1): nodes[q][1] ^ nodes[q+1][0] # Collect dangling edges (free indices) edges = [] # Left dangling edge edges += [nodes[0].get_edge(0)] # Right dangling edge edges += [nodes[-1].get_edge(1)] # Upper dangling edges for q in range(n_qubits): edges += [nodes[q].get_edge(2)] # Lower dangling edges for q in range(n_qubits): edges += [nodes[q].get_edge(3)] # Contract between all nodes along non-dangling edges res = tn.contractors.auto(nodes, output_edge_order=edges) # Reshape to get tensor of order 4 (get rid of left- and right open indices # and combine top&bottom into one) if isinstance(res.tensor, torch.Tensor): H_m = res.tensor.numpy() if not first: H += H_m else: H = H_m first = False return H.reshape((d,d,d,d))
14,354
36.480418
99
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.1/do_annealing.py
import tequila as tq import numpy as np import pickle from pathos.multiprocessing import ProcessingPool as Pool from parallel_annealing import * #from dummy_par import * from mutation_options import * from single_thread_annealing import * def find_best_instructions(instructions_dict): """ This function finds the instruction with the best fitness args: instructions_dict: A dictionary with the "Instructions" objects the corresponding fitness values as values """ best_instructions = None best_fitness = 10000000 for key in instructions_dict: if instructions_dict[key][1] <= best_fitness: best_instructions = instructions_dict[key][0] best_fitness = instructions_dict[key][1] return best_instructions, best_fitness def simulated_annealing(num_population, num_offsprings, actions_ratio, hamiltonian, max_epochs=100, min_epochs=1, tol=1e-6, type_energy_eval="wfn", cluster_circuit=None, patience = 20, num_processors=4, T_0=1.0, alpha=0.9, max_non_cliffords=0, verbose=False, beta=0.5, starting_energy=None): """ this function tries to find the clifford circuit that best lowers the energy of the hamiltonian using simulated annealing. params: - num_population = number of members in a generation - num_offsprings = number of mutations carried on every member - num_processors = number of processors to use for parallelization - T_0 = initial temperature - alpha = temperature decay - beta = parameter to adjust temperature on resetting after running out of patience - max_epochs = max iterations for optimizing - min_epochs = min iterations for optimizing - tol = minimum change in energy required, otherwise terminate optimization - verbose = display energies/decisions at iterations of not - hamiltonian = original hamiltonian - actions_ratio = The ratio of the different actions for mutations - type_energy_eval = keyword specifying the type of optimization method to use for energy minimization - cluster_circuit = the reference circuit to which clifford gates are added - patience = the number of epochs before resetting the optimization """ if verbose: print("Starting to Optimize Cluster circuit", flush=True) num_qubits = len(hamiltonian.qubits) if verbose: print("Initializing Generation", flush=True) # restart = False if previous_instructions is None\ # else True restart = False instructions_dict = {} instructions_list = [] current_fitness_list = [] fitness, wfn = None, None # pre-initialize with None for instruction_id in range(num_population): instructions = None if restart: try: instructions = Instructions(n_qubits=num_qubits, alpha=alpha, T_0=T_0, beta=beta, patience=patience, max_non_cliffords=max_non_cliffords, reference_energy=starting_energy) instructions.gates = pickle.load(open("instruct_gates.pickle", "rb")) instructions.positions = pickle.load(open("instruct_positions.pickle", "rb")) instructions.best_reference_wfn = pickle.load(open("best_reference_wfn.pickle", "rb")) print("Added a guess from previous runs", flush=True) fitness, wfn = evaluate_fitness(instructions=instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) except Exception as e: print(e) raise Exception("Did not find a guess from previous runs") # pass restart = False #print(instructions._str()) else: failed = True while failed: instructions = Instructions(n_qubits=num_qubits, alpha=alpha, T_0=T_0, beta=beta, patience=patience, max_non_cliffords=max_non_cliffords, reference_energy=starting_energy) instructions.prune() fitness, wfn = evaluate_fitness(instructions=instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) # if fitness <= starting_energy: failed = False instructions.set_reference_wfn(wfn) current_fitness_list.append(fitness) instructions_list.append(instructions) instructions_dict[instruction_id] = (instructions, fitness) if verbose: print("First Generation details: \n", flush=True) for key in instructions_dict: print("Initial Instructions number: ", key, flush=True) instructions_dict[key][0]._str() print("Initial fitness values: ", instructions_dict[key][1], flush=True) best_instructions, best_energy = find_best_instructions(instructions_dict) if verbose: print("Best member of the Generation: \n", flush=True) print("Instructions: ", flush=True) best_instructions._str() print("fitness value: ", best_energy, flush=True) pickle.dump(best_instructions.gates, open("instruct_gates.pickle", "wb")) pickle.dump(best_instructions.positions, open("instruct_positions.pickle", "wb")) pickle.dump(best_instructions.best_reference_wfn, open("best_reference_wfn.pickle", "wb")) epoch = 0 previous_best_energy = best_energy converged = False has_improved_before = False dts = [] #pool = multiprocessing.Pool(processes=num_processors) while (epoch < max_epochs): print("Epoch: ", epoch, flush=True) import time t0 = time.time() if num_processors == 1: st_evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, type_energy_eval, cluster_circuit) else: evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, num_processors, type_energy_eval, cluster_circuit) t1 = time.time() dts += [t1-t0] best_instructions, best_energy = find_best_instructions(instructions_dict) if verbose: print("Best member of the Generation: \n", flush=True) print("Instructions: ", flush=True) best_instructions._str() print("fitness value: ", best_energy, flush=True) # A bit confusing, but: # Want that current best energy has improved something previous, is better than # some starting energy and achieves some convergence criterion has_improved_before = True if np.abs(best_energy - previous_best_energy) < 0\ else False if np.abs(best_energy - previous_best_energy) < tol and has_improved_before: if starting_energy is not None: converged = True if best_energy < starting_energy else False else: converged = True else: converged = False if best_energy < previous_best_energy: previous_best_energy = best_energy epoch += 1 pickle.dump(best_instructions.gates, open("instruct_gates.pickle", "wb")) pickle.dump(best_instructions.positions, open("instruct_positions.pickle", "wb")) pickle.dump(best_instructions.best_reference_wfn, open("best_reference_wfn.pickle", "wb")) #pool.close() if converged: print("Converged after ", epoch, " iterations.", flush=True) print("Best energy:", best_energy, flush=True) print("\t with instructions", best_instructions.gates, best_instructions.positions, flush=True) print("\t optimal parameters", best_instructions.best_reference_wfn, flush=True) print("average time: ", np.average(dts), flush=True) print("overall time: ", np.sum(dts), flush=True) # best_instructions.replace_UCCXc_with_UCC(number=max_non_cliffords) pickle.dump(best_instructions.gates, open("instruct_gates.pickle", "wb")) pickle.dump(best_instructions.positions, open("instruct_positions.pickle", "wb")) pickle.dump(best_instructions.best_reference_wfn, open("best_reference_wfn.pickle", "wb")) def replace_cliff_with_non_cliff(num_population, num_offsprings, actions_ratio, hamiltonian, max_epochs=100, min_epochs=1, tol=1e-6, type_energy_eval="wfn", cluster_circuit=None, patience = 20, num_processors=4, T_0=1.0, alpha=0.9, max_non_cliffords=0, verbose=False, beta=0.5, starting_energy=None): """ this function tries to find the clifford circuit that best lowers the energy of the hamiltonian using simulated annealing. params: - num_population = number of members in a generation - num_offsprings = number of mutations carried on every member - num_processors = number of processors to use for parallelization - T_0 = initial temperature - alpha = temperature decay - beta = parameter to adjust temperature on resetting after running out of patience - max_epochs = max iterations for optimizing - min_epochs = min iterations for optimizing - tol = minimum change in energy required, otherwise terminate optimization - verbose = display energies/decisions at iterations of not - hamiltonian = original hamiltonian - actions_ratio = The ratio of the different actions for mutations - type_energy_eval = keyword specifying the type of optimization method to use for energy minimization - cluster_circuit = the reference circuit to which clifford gates are added - patience = the number of epochs before resetting the optimization """ if verbose: print("Starting to replace clifford gates Cluster circuit with non-clifford gates one at a time", flush=True) num_qubits = len(hamiltonian.qubits) #get the best clifford object instructions = Instructions(n_qubits=num_qubits, alpha=alpha, T_0=T_0, beta=beta, patience=patience, max_non_cliffords=max_non_cliffords, reference_energy=starting_energy) instructions.gates = pickle.load(open("instruct_gates.pickle", "rb")) instructions.positions = pickle.load(open("instruct_positions.pickle", "rb")) instructions.best_reference_wfn = pickle.load(open("best_reference_wfn.pickle", "rb")) fitness, wfn = evaluate_fitness(instructions=instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) if verbose: print("Initial energy after previous Clifford optimization is",\ fitness, flush=True) print("Starting with instructions", instructions.gates, instructions.positions, flush=True) instructions_dict = {} instructions_dict[0] = (instructions, fitness) for gate_id, (gate, position) in enumerate(zip(instructions.gates, instructions.positions)): print(gate) altered_instructions = copy.deepcopy(instructions) # skip if controlled rotation if gate[0]=='C': continue altered_instructions.replace_cg_w_ncg(gate_id) # altered_instructions.max_non_cliffords = 1 # TODO why is this set to 1?? altered_instructions.max_non_cliffords = max_non_cliffords #clifford_circuit, init_angles = build_circuit(instructions) #print(clifford_circuit, init_angles) #folded_hamiltonian = perform_folding(hamiltonian, clifford_circuit) #folded_hamiltonian2 = (convert_PQH_to_tq_QH(folded_hamiltonian))() #print(folded_hamiltonian) #clifford_circuit, init_angles = build_circuit(altered_instructions) #print(clifford_circuit, init_angles) #folded_hamiltonian = perform_folding(hamiltonian, clifford_circuit) #folded_hamiltonian1 = (convert_PQH_to_tq_QH(folded_hamiltonian))(init_angles) #print(folded_hamiltonian1 - folded_hamiltonian2) #print(folded_hamiltonian) #raise Exception("teste") counter = 0 success = False while not success: counter += 1 try: fitness, wfn = evaluate_fitness(instructions=altered_instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) success = True except Exception as e: print(e) if counter > 5: print("This replacement failed more than 5 times") success = True instructions_dict[gate_id+1] = (altered_instructions, fitness) #circuit = build_circuit(altered_instructions) #tq.draw(circuit,backend="cirq") best_instructions, best_energy = find_best_instructions(instructions_dict) print("best instrucitons after the non-clifford opimizaton") print("Best energy:", best_energy, flush=True) print("\t with instructions", best_instructions.gates, best_instructions.positions, flush=True)
13,155
46.154122
187
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.1/scipy_optimizer.py
import numpy, copy, scipy, typing, numbers from tequila import BitString, BitNumbering, BitStringLSB from tequila.utils.keymap import KeyMapRegisterToSubregister from tequila.circuit.compiler import change_basis from tequila.utils import to_float import tequila as tq from tequila.objective import Objective from tequila.optimizers.optimizer_scipy import OptimizerSciPy, SciPyResults from tequila.objective.objective import assign_variable, Variable, format_variable_dictionary, format_variable_list from tequila.circuit.noise import NoiseModel #from tequila.optimizers._containers import _EvalContainer, _GradContainer, _HessContainer, _QngContainer from vqe_utils import * class _EvalContainer: """ Overwrite the call function Container Class to access scipy and keep the optimization history. This class is used by the SciPy optimizer and should not be used elsewhere. Attributes --------- objective: the objective to evaluate. param_keys: the dictionary mapping parameter keys to positions in a numpy array. samples: the number of samples to evaluate objective with. save_history: whether or not to save, in a history, information about each time __call__ occurs. print_level dictates the verbosity of printing during call. N: the length of param_keys. history: if save_history, a list of energies received from every __call__ history_angles: if save_history, a list of angles sent to __call__. """ def __init__(self, Hamiltonian, unitary, param_keys, Ham_derivatives= None, Eval=None, passive_angles=None, samples=1024, save_history=True, print_level: int = 3): self.Hamiltonian = Hamiltonian self.unitary = unitary self.samples = samples self.param_keys = param_keys self.N = len(param_keys) self.save_history = save_history self.print_level = print_level self.passive_angles = passive_angles self.Eval = Eval self.infostring = None self.Ham_derivatives = Ham_derivatives if save_history: self.history = [] self.history_angles = [] def __call__(self, p, *args, **kwargs): """ call a wrapped objective. Parameters ---------- p: numpy array: Parameters with which to call the objective. args kwargs Returns ------- numpy.array: value of self.objective with p translated into variables, as a numpy array. """ angles = {}#dict((self.param_keys[i], p[i]) for i in range(self.N)) for i in range(self.N): if self.param_keys[i] in self.unitary.extract_variables(): angles[self.param_keys[i]] = p[i] else: angles[self.param_keys[i]] = complex(p[i]) if self.passive_angles is not None: angles = {**angles, **self.passive_angles} vars = format_variable_dictionary(angles) Hamiltonian = self.Hamiltonian(vars) #print(Hamiltonian) #print(self.unitary) #print(vars) Expval = tq.ExpectationValue(H=Hamiltonian, U=self.unitary) #print(Expval) E = tq.simulate(Expval, vars, backend='qulacs', samples=self.samples) self.infostring = "{:15} : {} expectationvalues\n".format("Objective", Expval.count_expectationvalues()) if self.print_level > 2: print("E={:+2.8f}".format(E), " angles=", angles, " samples=", self.samples) elif self.print_level > 1: print("E={:+2.8f}".format(E)) if self.save_history: self.history.append(E) self.history_angles.append(angles) return complex(E) # jax types confuses optimizers class _GradContainer(_EvalContainer): """ Overwrite the call function Container Class to access scipy and keep the optimization history. This class is used by the SciPy optimizer and should not be used elsewhere. see _EvalContainer for details. """ def __call__(self, p, *args, **kwargs): """ call the wrapped qng. Parameters ---------- p: numpy array: Parameters with which to call gradient args kwargs Returns ------- numpy.array: value of self.objective with p translated into variables, as a numpy array. """ Ham_derivatives = self.Ham_derivatives Hamiltonian = self.Hamiltonian unitary = self.unitary dE_vec = numpy.zeros(self.N) memory = dict() #variables = dict((self.param_keys[i], p[i]) for i in range(len(self.param_keys))) variables = {}#dict((self.param_keys[i], p[i]) for i in range(self.N)) for i in range(len(self.param_keys)): if self.param_keys[i] in self.unitary.extract_variables(): variables[self.param_keys[i]] = p[i] else: variables[self.param_keys[i]] = complex(p[i]) if self.passive_angles is not None: variables = {**variables, **self.passive_angles} vars = format_variable_dictionary(variables) expvals = 0 for i in range(self.N): derivative = 0.0 if self.param_keys[i] in list(unitary.extract_variables()): Ham = Hamiltonian(vars) Expval = tq.ExpectationValue(H=Ham, U=unitary) temp_derivative = tq.compile(objective = tq.grad(objective = Expval, variable = self.param_keys[i]),backend='qulacs') expvals += temp_derivative.count_expectationvalues() derivative += temp_derivative if self.param_keys[i] in list(Ham_derivatives.keys()): #print(self.param_keys[i]) Ham = Ham_derivatives[self.param_keys[i]] Ham = convert_PQH_to_tq_QH(Ham) H = Ham(vars) #print(H) #raise Exception("testing") Expval = tq.ExpectationValue(H=H, U=unitary) expvals += Expval.count_expectationvalues() derivative += tq.simulate(Expval, vars, backend='qulacs', samples=self.samples) #print(derivative) #print(type(H)) if isinstance(derivative, float) or isinstance(derivative, numpy.complex64) : dE_vec[i] = derivative else: dE_vec[i] = derivative(variables=variables, samples=self.samples) memory[self.param_keys[i]] = dE_vec[i] self.infostring = "{:15} : {} expectationvalues\n".format("gradient", expvals) self.history.append(memory) return numpy.asarray(dE_vec, dtype=numpy.complex64) class optimize_scipy(OptimizerSciPy): """ overwrite the expectation and gradient container objects """ def initialize_variables(self, all_variables, initial_values, variables): """ Convenience function to format the variables of some objective recieved in calls to optimzers. Parameters ---------- objective: Objective: the objective being optimized. initial_values: dict or string: initial values for the variables of objective, as a dictionary. if string: can be `zero` or `random` if callable: custom function that initializes when keys are passed if None: random initialization between 0 and 2pi (not recommended) variables: list: the variables being optimized over. Returns ------- tuple: active_angles, a dict of those variables being optimized. passive_angles, a dict of those variables NOT being optimized. variables: formatted list of the variables being optimized. """ # bring into right format variables = format_variable_list(variables) initial_values = format_variable_dictionary(initial_values) all_variables = all_variables if variables is None: variables = all_variables if initial_values is None: initial_values = {k: numpy.random.uniform(0, 2 * numpy.pi) for k in all_variables} elif hasattr(initial_values, "lower"): if initial_values.lower() == "zero": initial_values = {k:0.0 for k in all_variables} elif initial_values.lower() == "random": initial_values = {k: numpy.random.uniform(0, 2 * numpy.pi) for k in all_variables} else: raise TequilaOptimizerException("unknown initialization instruction: {}".format(initial_values)) elif callable(initial_values): initial_values = {k: initial_values(k) for k in all_variables} elif isinstance(initial_values, numbers.Number): initial_values = {k: initial_values for k in all_variables} else: # autocomplete initial values, warn if you did detected = False for k in all_variables: if k not in initial_values: initial_values[k] = 0.0 detected = True if detected and not self.silent: warnings.warn("initial_variables given but not complete: Autocompleted with zeroes", TequilaWarning) active_angles = {} for v in variables: active_angles[v] = initial_values[v] passive_angles = {} for k, v in initial_values.items(): if k not in active_angles.keys(): passive_angles[k] = v return active_angles, passive_angles, variables def __call__(self, Hamiltonian, unitary, variables: typing.List[Variable] = None, initial_values: typing.Dict[Variable, numbers.Real] = None, gradient: typing.Dict[Variable, Objective] = None, hessian: typing.Dict[typing.Tuple[Variable, Variable], Objective] = None, reset_history: bool = True, *args, **kwargs) -> SciPyResults: """ Perform optimization using scipy optimizers. Parameters ---------- objective: Objective: the objective to optimize. variables: list, optional: the variables of objective to optimize. If None: optimize all. initial_values: dict, optional: a starting point from which to begin optimization. Will be generated if None. gradient: optional: Information or object used to calculate the gradient of objective. Defaults to None: get analytically. hessian: optional: Information or object used to calculate the hessian of objective. Defaults to None: get analytically. reset_history: bool: Default = True: whether or not to reset all history before optimizing. args kwargs Returns ------- ScipyReturnType: the results of optimization. """ H = convert_PQH_to_tq_QH(Hamiltonian) Ham_variables, Ham_derivatives = H._construct_derivatives() #print("hamvars",Ham_variables) all_variables = copy.deepcopy(Ham_variables) #print(all_variables) for var in unitary.extract_variables(): all_variables.append(var) #print(all_variables) infostring = "{:15} : {}\n".format("Method", self.method) #infostring += "{:15} : {} expectationvalues\n".format("Objective", objective.count_expectationvalues()) if self.save_history and reset_history: self.reset_history() active_angles, passive_angles, variables = self.initialize_variables(all_variables, initial_values, variables) #print(active_angles, passive_angles, variables) # Transform the initial value directory into (ordered) arrays param_keys, param_values = zip(*active_angles.items()) param_values = numpy.array(param_values) # process and initialize scipy bounds bounds = None if self.method_bounds is not None: bounds = {k: None for k in active_angles} for k, v in self.method_bounds.items(): if k in bounds: bounds[k] = v infostring += "{:15} : {}\n".format("bounds", self.method_bounds) names, bounds = zip(*bounds.items()) assert (names == param_keys) # make sure the bounds are not shuffled #print(param_keys, param_values) # do the compilation here to avoid costly recompilation during the optimization #compiled_objective = self.compile_objective(objective=objective, *args, **kwargs) E = _EvalContainer(Hamiltonian = H, unitary = unitary, Eval=None, param_keys=param_keys, samples=self.samples, passive_angles=passive_angles, save_history=self.save_history, print_level=self.print_level) E.print_level = 0 (E(param_values)) E.print_level = self.print_level infostring += E.infostring if gradient is not None: infostring += "{:15} : {}\n".format("grad instr", gradient) if hessian is not None: infostring += "{:15} : {}\n".format("hess_instr", hessian) compile_gradient = self.method in (self.gradient_based_methods + self.hessian_based_methods) compile_hessian = self.method in self.hessian_based_methods dE = None ddE = None # detect if numerical gradients shall be used # switch off compiling if so if isinstance(gradient, str): if gradient.lower() == 'qng': compile_gradient = False if compile_hessian: raise TequilaException('Sorry, QNG and hessian not yet tested together.') combos = get_qng_combos(objective, initial_values=initial_values, backend=self.backend, samples=self.samples, noise=self.noise) dE = _QngContainer(combos=combos, param_keys=param_keys, passive_angles=passive_angles) infostring += "{:15} : QNG {}\n".format("gradient", dE) else: dE = gradient compile_gradient = False if compile_hessian: compile_hessian = False if hessian is None: hessian = gradient infostring += "{:15} : scipy numerical {}\n".format("gradient", dE) infostring += "{:15} : scipy numerical {}\n".format("hessian", ddE) if isinstance(gradient,dict): if gradient['method'] == 'qng': func = gradient['function'] compile_gradient = False if compile_hessian: raise TequilaException('Sorry, QNG and hessian not yet tested together.') combos = get_qng_combos(objective,func=func, initial_values=initial_values, backend=self.backend, samples=self.samples, noise=self.noise) dE = _QngContainer(combos=combos, param_keys=param_keys, passive_angles=passive_angles) infostring += "{:15} : QNG {}\n".format("gradient", dE) if isinstance(hessian, str): ddE = hessian compile_hessian = False if compile_gradient: dE =_GradContainer(Ham_derivatives = Ham_derivatives, unitary = unitary, Hamiltonian = H, Eval= E, param_keys=param_keys, samples=self.samples, passive_angles=passive_angles, save_history=self.save_history, print_level=self.print_level) dE.print_level = 0 (dE(param_values)) dE.print_level = self.print_level infostring += dE.infostring if self.print_level > 0: print(self) print(infostring) print("{:15} : {}\n".format("active variables", len(active_angles))) Es = [] optimizer_instance = self class SciPyCallback: energies = [] gradients = [] hessians = [] angles = [] real_iterations = 0 def __call__(self, *args, **kwargs): self.energies.append(E.history[-1]) self.angles.append(E.history_angles[-1]) if dE is not None and not isinstance(dE, str): self.gradients.append(dE.history[-1]) if ddE is not None and not isinstance(ddE, str): self.hessians.append(ddE.history[-1]) self.real_iterations += 1 if 'callback' in optimizer_instance.kwargs: optimizer_instance.kwargs['callback'](E.history_angles[-1]) callback = SciPyCallback() res = scipy.optimize.minimize(E, x0=param_values, jac=dE, hess=ddE, args=(Es,), method=self.method, tol=self.tol, bounds=bounds, constraints=self.method_constraints, options=self.method_options, callback=callback) # failsafe since callback is not implemented everywhere if callback.real_iterations == 0: real_iterations = range(len(E.history)) if self.save_history: self.history.energies = callback.energies self.history.energy_evaluations = E.history self.history.angles = callback.angles self.history.angles_evaluations = E.history_angles self.history.gradients = callback.gradients self.history.hessians = callback.hessians if dE is not None and not isinstance(dE, str): self.history.gradients_evaluations = dE.history if ddE is not None and not isinstance(ddE, str): self.history.hessians_evaluations = ddE.history # some methods like "cobyla" do not support callback functions if len(self.history.energies) == 0: self.history.energies = E.history self.history.angles = E.history_angles # some scipy methods always give back the last value and not the minimum (e.g. cobyla) ea = sorted(zip(E.history, E.history_angles), key=lambda x: x[0]) E_final = ea[0][0] angles_final = ea[0][1] #dict((param_keys[i], res.x[i]) for i in range(len(param_keys))) angles_final = {**angles_final, **passive_angles} return SciPyResults(energy=E_final, history=self.history, variables=format_variable_dictionary(angles_final), scipy_result=res) def minimize(Hamiltonian, unitary, gradient: typing.Union[str, typing.Dict[Variable, Objective]] = None, hessian: typing.Union[str, typing.Dict[typing.Tuple[Variable, Variable], Objective]] = None, initial_values: typing.Dict[typing.Hashable, numbers.Real] = None, variables: typing.List[typing.Hashable] = None, samples: int = None, maxiter: int = 100, backend: str = None, backend_options: dict = None, noise: NoiseModel = None, device: str = None, method: str = "BFGS", tol: float = 1.e-3, method_options: dict = None, method_bounds: typing.Dict[typing.Hashable, numbers.Real] = None, method_constraints=None, silent: bool = False, save_history: bool = True, *args, **kwargs) -> SciPyResults: """ calls the local optimize_scipy scipy funtion instead and pass down the objective construction down Parameters ---------- objective: Objective : The tequila objective to optimize gradient: typing.Union[str, typing.Dict[Variable, Objective], None] : Default value = None): '2-point', 'cs' or '3-point' for numerical gradient evaluation (does not work in combination with all optimizers), dictionary of variables and tequila objective to define own gradient, None for automatic construction (default) Other options include 'qng' to use the quantum natural gradient. hessian: typing.Union[str, typing.Dict[Variable, Objective], None], optional: '2-point', 'cs' or '3-point' for numerical gradient evaluation (does not work in combination with all optimizers), dictionary (keys:tuple of variables, values:tequila objective) to define own gradient, None for automatic construction (default) initial_values: typing.Dict[typing.Hashable, numbers.Real], optional: Initial values as dictionary of Hashable types (variable keys) and floating point numbers. If given None they will all be set to zero variables: typing.List[typing.Hashable], optional: List of Variables to optimize samples: int, optional: samples/shots to take in every run of the quantum circuits (None activates full wavefunction simulation) maxiter: int : (Default value = 100): max iters to use. backend: str, optional: Simulator backend, will be automatically chosen if set to None backend_options: dict, optional: Additional options for the backend Will be unpacked and passed to the compiled objective in every call noise: NoiseModel, optional: a NoiseModel to apply to all expectation values in the objective. method: str : (Default = "BFGS"): Optimization method (see scipy documentation, or 'available methods') tol: float : (Default = 1.e-3): Convergence tolerance for optimization (see scipy documentation) method_options: dict, optional: Dictionary of options (see scipy documentation) method_bounds: typing.Dict[typing.Hashable, typing.Tuple[float, float]], optional: bounds for the variables (see scipy documentation) method_constraints: optional: (see scipy documentation silent: bool : No printout if True save_history: bool: Save the history throughout the optimization Returns ------- SciPyReturnType: the results of optimization """ if isinstance(gradient, dict) or hasattr(gradient, "items"): if all([isinstance(x, Objective) for x in gradient.values()]): gradient = format_variable_dictionary(gradient) if isinstance(hessian, dict) or hasattr(hessian, "items"): if all([isinstance(x, Objective) for x in hessian.values()]): hessian = {(assign_variable(k[0]), assign_variable([k[1]])): v for k, v in hessian.items()} method_bounds = format_variable_dictionary(method_bounds) # set defaults optimizer = optimize_scipy(save_history=save_history, maxiter=maxiter, method=method, method_options=method_options, method_bounds=method_bounds, method_constraints=method_constraints, silent=silent, backend=backend, backend_options=backend_options, device=device, samples=samples, noise_model=noise, tol=tol, *args, **kwargs) if initial_values is not None: initial_values = {assign_variable(k): v for k, v in initial_values.items()} return optimizer(Hamiltonian, unitary, gradient=gradient, hessian=hessian, initial_values=initial_values, variables=variables, *args, **kwargs)
24,489
42.732143
144
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.1/energy_optimization.py
import tequila as tq import numpy as np from tequila.objective.objective import Variable import openfermion from hacked_openfermion_qubit_operator import ParamQubitHamiltonian from typing import Union from vqe_utils import convert_PQH_to_tq_QH, convert_tq_QH_to_PQH,\ fold_unitary_into_hamiltonian from grad_hacked import grad from scipy_optimizer import minimize import scipy import random # guess we could substitute that with numpy.random #TODO import argparse import pickle as pk import sys sys.path.insert(0, '../../../') #sys.path.insert(0, '../') # This needs to be properly integrated somewhere else at some point # from tn_update.qq import contract_energy, optimize_wavefunctions from tn_update.my_mpo import * from tn_update.wfn_optimization import contract_energy_mpo, optimize_wavefunctions_mpo, initialize_wfns_randomly def energy_from_wfn_opti(hamiltonian: tq.QubitHamiltonian, n_qubits: int, guess_wfns=None, TOL=1e-4) -> tuple: ''' Get energy using a tensornetwork based method ~ power method (here as blackbox) ''' d = int(2**(n_qubits/2)) # Build MPO h_mpo = MyMPO(hamiltonian=hamiltonian, n_qubits=n_qubits, maxdim=500) h_mpo.make_mpo_from_hamiltonian() # Optimize wavefunctions based on random guess out = None it = 0 while out is None: # Set up random initial guesses for subsystems it += 1 if guess_wfns is None: psiL_rand = initialize_wfns_randomly(d, n_qubits//2) psiR_rand = initialize_wfns_randomly(d, n_qubits//2) else: psiL_rand = guess_wfns[0] psiR_rand = guess_wfns[1] out = optimize_wavefunctions_mpo(h_mpo, psiL_rand, psiR_rand, TOL=TOL, silent=True) energy_rand = out[0] optimal_wfns = [out[1], out[2]] return energy_rand, optimal_wfns def combine_two_clusters(H: tq.QubitHamiltonian, subsystems: list, circ_list: list) -> float: ''' E = nuc_rep + \sum_j c_j <0_A | U_A+ sigma_j|A U_A | 0_A><0_B | U_B+ sigma_j|B U_B | 0_B> i ) Split up Hamiltonian into vector c = [c_j], all sigmas of system A and system B ii ) Two vectors of ExpectationValues E_A=[E(U_A, sigma_j|A)], E_B=[E(U_B, sigma_j|B)] iii) Minimize vectors from ii) iv ) Perform weighted sum \sum_j c_[j] E_A[j] E_B[j] result = nuc_rep + iv) Finishing touch inspired by private tequila-repo / pair-separated objective This is still rather inefficient/unoptimized Can still prune out near-zero coefficients c_j ''' objective = 0.0 n_subsystems = len(subsystems) # Over all Paulistrings in the Hamiltonian for p_index, pauli in enumerate(H.paulistrings): # Gather coefficient coeff = pauli.coeff.real # Empty dictionary for operations: # to be filled with another dictionary per subsystem, where then # e.g. X(0)Z(1)Y(2)X(4) and subsystems=[[0,1,2],[3,4,5]] # -> ops={ 0: {0: 'X', 1: 'Z', 2: 'Y'}, 1: {4: 'X'} } ops = {} for s_index, sys in enumerate(subsystems): for k, v in pauli.items(): if k in sys: if s_index in ops: ops[s_index][k] = v else: ops[s_index] = {k: v} # If no ops gathered -> identity -> nuclear repulsion if len(ops) == 0: #print ("this should only happen ONCE") objective += coeff # If not just identity: # add objective += c_j * prod_subsys( < Paulistring_j_subsys >_{U_subsys} ) elif len(ops) > 0: obj_tmp = coeff for s_index, sys_pauli in ops.items(): #print (s_index, sys_pauli) H_tmp = QubitHamiltonian.from_paulistrings(PauliString(data=sys_pauli)) E_tmp = ExpectationValue(U=circ_list[s_index], H=H_tmp) obj_tmp *= E_tmp objective += obj_tmp initial_values = {k: 0.0 for k in objective.extract_variables()} random_initial_values = {k: 1e-2*np.random.uniform(-1, 1) for k in objective.extract_variables()} method = 'bfgs' # 'bfgs' # 'l-bfgs-b' # 'cobyla' # 'slsqp' curr_res = tq.minimize(method=method, objective=objective, initial_values=initial_values, gradient='two-point', backend='qulacs', method_options={"finite_diff_rel_step": 1e-3}) return curr_res.energy def energy_from_tq_qcircuit(hamiltonian: Union[tq.QubitHamiltonian, ParamQubitHamiltonian], n_qubits: int, circuit = Union[list, tq.QCircuit], subsystems: list = [[0,1,2,3,4,5]], initial_guess = None)-> tuple: ''' Get minimal energy using tequila ''' result = None # If only one circuit handed over, just run simple VQE if isinstance(circuit, list) and len(circuit) == 1: circuit = circuit[0] if isinstance(circuit, tq.QCircuit): if isinstance(hamiltonian, tq.QubitHamiltonian): E = tq.ExpectationValue(H=hamiltonian, U=circuit) if initial_guess is None: initial_angles = {k: 0.0 for k in E.extract_variables()} else: initial_angles = initial_guess #print ("optimizing non-param...") result = tq.minimize(objective=E, method='l-bfgs-b', silent=True, backend='qulacs', initial_values=initial_angles) #gradient='two-point', backend='qulacs', #method_options={"finite_diff_rel_step": 1e-4}) elif isinstance(hamiltonian, ParamQubitHamiltonian): if initial_guess is None: raise Exception("Need to provide initial guess for this to work.") initial_angles = None else: initial_angles = initial_guess #print ("optimizing param...") result = minimize(hamiltonian, circuit, method='bfgs', initial_values=initial_angles, backend="qulacs", silent=True) # If more circuits handed over, assume subsystems else: # TODO!! implement initial guess for the combine_two_clusters thing #print ("Should not happen for now...") result = combine_two_clusters(hamiltonian, subsystems, circuit) return result.energy, result.angles def mixed_optimization(hamiltonian: ParamQubitHamiltonian, n_qubits: int, initial_guess: Union[dict, list]=None, init_angles: list=None): ''' Minimizes energy using wfn opti and a parametrized Hamiltonian min_{psi, theta fixed} <psi | H(theta) | psi> --> min_{t, p fixed} <p | H(t) | p> ^---------------------------------------------------^ until convergence ''' energy, optimal_state = None, None H_qh = convert_PQH_to_tq_QH(hamiltonian) var_keys, H_derivs = H_qh._construct_derivatives() print("var keys", var_keys, flush=True) print('var dict', init_angles, flush=True) # if not init_angles: # var_vals = [0. for i in range(len(var_keys))] # initialize with 0 # else: # var_vals = init_angles def build_variable_dict(keys, values): assert(len(keys)==len(values)) out = dict() for idx, key in enumerate(keys): out[key] = complex(values[idx]) return out var_dict = init_angles var_vals = [*init_angles.values()] assert(build_variable_dict(var_keys, var_vals) == var_dict) def wrap_energy_eval(psi): ''' like energy_from_wfn_opti but instead of optimize get inner product ''' def energy_eval_fn(x): var_dict = build_variable_dict(var_keys, x) H_qh_fix = H_qh(var_dict) H_mpo = MyMPO(hamiltonian=H_qh_fix, n_qubits=n_qubits, maxdim=500) H_mpo.make_mpo_from_hamiltonian() return contract_energy_mpo(H_mpo, psi[0], psi[1]) return energy_eval_fn def wrap_gradient_eval(psi): ''' call derivatives with updated variable list ''' def gradient_eval_fn(x): variables = build_variable_dict(var_keys, x) deriv_expectations = H_derivs.values() # list of ParamQubitHamiltonian's deriv_qhs = [convert_PQH_to_tq_QH(d) for d in deriv_expectations] deriv_qhs = [d(variables) for d in deriv_qhs] # list of tq.QubitHamiltonian's # print(deriv_qhs) deriv_mpos = [MyMPO(hamiltonian=d, n_qubits=n_qubits, maxdim=500)\ for d in deriv_qhs] # print(deriv_mpos[0].n_qubits) for d in deriv_mpos: d.make_mpo_from_hamiltonian() # deriv_mpos = [d.make_mpo_from_hamiltonian() for d in deriv_mpos] return np.asarray([contract_energy_mpo(d, psi[0], psi[1]) for d in deriv_mpos]) return gradient_eval_fn def do_wfn_opti(values, guess_wfns, TOL): # H_qh = H_qh(H_vars) var_dict = build_variable_dict(var_keys, values) en, psi = energy_from_wfn_opti(H_qh(var_dict), n_qubits=n_qubits, guess_wfns=guess_wfns, TOL=TOL) return en, psi def do_param_opti(psi, x0): result = scipy.optimize.minimize(fun=wrap_energy_eval(psi), jac=wrap_gradient_eval(psi), method='bfgs', x0=x0, options={'maxiter': 4}) # print(result) return result e_prev, psi_prev = 123., None # print("iguess", initial_guess) e_curr, psi_curr = do_wfn_opti(var_vals, initial_guess, 1e-5) print('first eval', e_curr, flush=True) def converged(e_prev, e_curr, TOL=1e-4): return True if np.abs(e_prev-e_curr) < TOL else False it = 0 var_prev = var_vals print("vars before comp", var_prev, flush=True) while not converged(e_prev, e_curr) and it < 50: e_prev, psi_prev = e_curr, psi_curr # print('before param opti') res = do_param_opti(psi_curr, var_prev) var_curr = res['x'] print('curr vars', var_curr, flush=True) e_curr = res['fun'] print('en before wfn opti', e_curr, flush=True) # print("iiiiiguess", psi_prev) e_curr, psi_curr = do_wfn_opti(var_curr, psi_prev, 1e-3) print('en after wfn opti', e_curr, flush=True) it += 1 print('at iteration', it, flush=True) return e_curr, psi_curr # optimize parameters with fixed wavefunction # define/wrap energy function - given |p>, evaluate <p|H(t)|p> ''' def wrap_gradient(objective: typing.Union[Objective, QTensor], no_compile=False, *args, **kwargs): def gradient_fn(variable: Variable = None): return grad(objective: typing.Union[Objective, QTensor], variable: Variable = None, no_compile=False, *args, **kwargs) return grad_fn ''' def minimize_energy(hamiltonian: Union[ParamQubitHamiltonian, tq.QubitHamiltonian], n_qubits: int, type_energy_eval: str='wfn', cluster_circuit: tq.QCircuit=None, initial_guess=None, initial_mixed_angles: dict=None) -> float: ''' Minimizes energy functional either according a power-method inspired shortcut ('wfn') or using a unitary circuit ('qc') ''' if type_energy_eval == 'wfn': if isinstance(hamiltonian, tq.QubitHamiltonian): energy, optimal_state = energy_from_wfn_opti(hamiltonian, n_qubits, initial_guess) elif isinstance(hamiltonian, ParamQubitHamiltonian): init_angles = initial_mixed_angles energy, optimal_state = mixed_optimization(hamiltonian=hamiltonian, n_qubits=n_qubits, initial_guess=initial_guess, init_angles=init_angles) elif type_energy_eval == 'qc': if cluster_circuit is None: raise Exception("Need to hand over circuit!") energy, optimal_state = energy_from_tq_qcircuit(hamiltonian, n_qubits, cluster_circuit, [[0,1,2,3],[4,5,6,7]], initial_guess) else: raise Exception("Option not implemented!") return energy, optimal_state
12,457
43.021201
225
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.1/parallel_annealing.py
import tequila as tq import multiprocessing import copy from time import sleep from mutation_options import * from pathos.multiprocessing import ProcessingPool as Pool def evolve_population(hamiltonian, type_energy_eval, cluster_circuit, process_id, num_offsprings, actions_ratio, tasks, results): """ This function carries a single step of the simulated annealing on a single member of the generation args: process_id: A unique identifier for each process num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for mutations tasks: multiprocessing queue to pass family_id, instructions and current_fitness family_id: A unique identifier for each family instructions: An object consisting of the instructions in the quantum circuit current_fitness: Current fitness value of the circuit results: multiprocessing queue to pass results back """ #print('[%s] evaluation routine starts' % process_id) while True: try: #getting parameters for mutation and carrying it family_id, instructions, current_fitness = tasks.get() #check if patience has been exhausted if instructions.patience == 0: instructions.reset_to_best() best_child = 0 best_energy = current_fitness new_generations = {} for off_id in range(1, num_offsprings+1): scheduled_ratio = schedule_actions_ratio(epoch=0, steady_ratio=actions_ratio) action = get_action(scheduled_ratio) updated_instructions = copy.deepcopy(instructions) updated_instructions.update_by_action(action) new_fitness, wfn = evaluate_fitness(updated_instructions, hamiltonian, type_energy_eval, cluster_circuit) updated_instructions.set_reference_wfn(wfn) prob_acceptance = get_prob_acceptance(current_fitness, new_fitness, updated_instructions.T, updated_instructions.reference_energy) # need to figure out in case we have two equals new_generations[str(off_id)] = updated_instructions if best_energy > new_fitness: # now two equals -> "first one" is picked best_child = off_id best_energy = new_fitness # decision = np.random.binomial(1, prob_acceptance) # if decision == 0: if best_child == 0: # Add result to the queue instructions.patience -= 1 #print('Reduced patience -- now ' + str(updated_instructions.patience)) if instructions.patience == 0: if instructions.best_previous_instructions: instructions.reset_to_best() else: instructions.update_T() results.put((family_id, instructions, current_fitness)) else: # Add result to the queue if (best_energy < current_fitness): new_generations[str(best_child)].update_best_previous_instructions() new_generations[str(best_child)].update_T() results.put((family_id, new_generations[str(best_child)], best_energy)) except Exception as eeee: #print('[%s] evaluation routine quits' % process_id) #print(eeee) # Indicate finished results.put(-1) break return def evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, num_processors=4, type_energy_eval='wfn', cluster_circuit=None): """ This function does parallel mutation on all the members of the generation and updates the generation args: num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for sampling instructions_dict: A dictionary with the "Instructions" objects the corresponding fitness values as values num_processors: Number of processors to use for parallel run """ # Define IPC manager manager = multiprocessing.Manager() # Define a list (queue) for tasks and computation results tasks = manager.Queue() results = manager.Queue() processes = [] pool = Pool(processes=num_processors) for i in range(num_processors): process_id = 'P%i' % i # Create the process, and connect it to the worker function new_process = multiprocessing.Process(target=evolve_population, args=(hamiltonian, type_energy_eval, cluster_circuit, process_id, num_offsprings, actions_ratio, tasks, results)) # Add new process to the list of processes processes.append(new_process) # Start the process new_process.start() #print("putting tasks") for family_id in instructions_dict: single_task = (family_id, instructions_dict[family_id][0], instructions_dict[family_id][1]) tasks.put(single_task) # Wait while the workers process - change it to something for our case later # sleep(5) multiprocessing.Barrier(num_processors) #print("after barrier") # Quit the worker processes by sending them -1 for i in range(num_processors): tasks.put(-1) # Read calculation results num_finished_processes = 0 while True: # Read result #print("num fin", num_finished_processes) try: family_id, updated_instructions, new_fitness = results.get() instructions_dict[family_id] = (updated_instructions, new_fitness) except: # Process has finished num_finished_processes += 1 if num_finished_processes == num_processors: break for process in processes: process.join() pool.close()
6,456
38.371951
146
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.1/single_thread_annealing.py
import tequila as tq import copy from mutation_options import * def st_evolve_population(hamiltonian, type_energy_eval, cluster_circuit, num_offsprings, actions_ratio, tasks): """ This function carries a single step of the simulated annealing on a single member of the generation args: num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for mutations tasks: a tuple of (family_id, instructions and current_fitness) family_id: A unique identifier for each family instructions: An object consisting of the instructions in the quantum circuit current_fitness: Current fitness value of the circuit """ family_id, instructions, current_fitness = tasks #check if patience has been exhausted if instructions.patience == 0: if instructions.best_previous_instructions: instructions.reset_to_best() best_child = 0 best_energy = current_fitness new_generations = {} for off_id in range(1, num_offsprings+1): scheduled_ratio = schedule_actions_ratio(epoch=0, steady_ratio=actions_ratio) action = get_action(scheduled_ratio) updated_instructions = copy.deepcopy(instructions) updated_instructions.update_by_action(action) new_fitness, wfn = evaluate_fitness(updated_instructions, hamiltonian, type_energy_eval, cluster_circuit) updated_instructions.set_reference_wfn(wfn) prob_acceptance = get_prob_acceptance(current_fitness, new_fitness, updated_instructions.T, updated_instructions.reference_energy) # need to figure out in case we have two equals new_generations[str(off_id)] = updated_instructions if best_energy > new_fitness: # now two equals -> "first one" is picked best_child = off_id best_energy = new_fitness # decision = np.random.binomial(1, prob_acceptance) # if decision == 0: if best_child == 0: # Add result to the queue instructions.patience -= 1 #print('Reduced patience -- now ' + str(updated_instructions.patience)) if instructions.patience == 0: if instructions.best_previous_instructions: instructions.reset_to_best() else: instructions.update_T() results = ((family_id, instructions, current_fitness)) else: # Add result to the queue if (best_energy < current_fitness): new_generations[str(best_child)].update_best_previous_instructions() new_generations[str(best_child)].update_T() results = ((family_id, new_generations[str(best_child)], best_energy)) return results def st_evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, type_energy_eval='wfn', cluster_circuit=None): """ This function does a single threas mutation on all the members of the generation and updates the generation args: num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for sampling instructions_dict: A dictionary with the "Instructions" objects the corresponding fitness values as values """ for family_id in instructions_dict: task = (family_id, instructions_dict[family_id][0], instructions_dict[family_id][1]) results = st_evolve_population(hamiltonian, type_energy_eval, cluster_circuit, num_offsprings, actions_ratio, task) family_id, updated_instructions, new_fitness = results instructions_dict[family_id] = (updated_instructions, new_fitness)
4,005
40.298969
138
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.1/mutation_options.py
import argparse import numpy as np import random import copy import tequila as tq from typing import Union from collections import Counter from time import time from vqe_utils import convert_PQH_to_tq_QH, convert_tq_QH_to_PQH,\ fold_unitary_into_hamiltonian from energy_optimization import minimize_energy global_seed = 1 class Instructions: ''' TODO need to put some documentation here ''' def __init__(self, n_qubits, mu=2.0, sigma=0.4, alpha=0.9, T_0=1.0, beta=0.5, patience=10, max_non_cliffords=0, reference_energy=0., number=None): # hardcoded values for now self.num_non_cliffords = 0 self.max_non_cliffords = max_non_cliffords # ------------------------ self.starting_patience = patience self.patience = patience self.mu = mu self.sigma = sigma self.alpha = alpha self.beta = beta self.T_0 = T_0 self.T = T_0 self.gates = self.get_random_gates(number=number) self.n_qubits = n_qubits self.positions = self.get_random_positions() self.best_previous_instructions = {} self.reference_energy = reference_energy self.best_reference_wfn = None self.noncliff_replacements = {} def _str(self): print(self.gates) print(self.positions) def set_reference_wfn(self, reference_wfn): self.best_reference_wfn = reference_wfn def update_T(self, update_type: str = 'regular', best_temp=None): # Regular update if update_type.lower() == 'regular': self.T = self.alpha * self.T # Temperature update if patience ran out elif update_type.lower() == 'patience': self.T = self.beta*best_temp + (1-self.beta)*self.T_0 def get_random_gates(self, number=None): ''' Randomly generates a list of gates. number indicates the number of gates to generate otherwise, number will be drawn from a log normal distribution ''' mu, sigma = self.mu, self.sigma full_options = ['X','Y','Z','S','H','CX', 'CY', 'CZ','SWAP', 'UCC2c', 'UCC4c', 'UCC2', 'UCC4'] clifford_options = ['X','Y','Z','S','H','CX', 'CY', 'CZ','SWAP', 'UCC2c', 'UCC4c'] #non_clifford_options = ['UCC2', 'UCC4'] # Gate distribution, selecting number of gates to add k = np.random.lognormal(mu, sigma) k = np.int(k) if number is not None: k = number # Selecting gate types gates = None if self.num_non_cliffords < self.max_non_cliffords: gates = random.choices(full_options, k=k) # with replacement else: gates = random.choices(clifford_options, k=k) new_num_non_cliffords = 0 if "UCC2" in gates: new_num_non_cliffords += Counter(gates)["UCC2"] if "UCC4" in gates: new_num_non_cliffords += Counter(gates)["UCC4"] if (new_num_non_cliffords+self.num_non_cliffords) <= self.max_non_cliffords: self.num_non_cliffords += new_num_non_cliffords else: extra_cliffords = (new_num_non_cliffords+self.num_non_cliffords) - self.max_non_cliffords assert(extra_cliffords >= 0) new_gates = random.choices(clifford_options, k=extra_cliffords) for g in new_gates: try: gates[gates.index("UCC4")] = g except: gates[gates.index("UCC2")] = g self.num_non_cliffords = self.max_non_cliffords if k == 1: if gates == "UCC2c" or gates == "UCC4c": gates = get_string_Cliff_ucc(gates) if gates == "UCC2" or gates == "UCC4": gates = get_string_ucc(gates) else: for ind, gate in enumerate(gates): if gate == "UCC2c" or gate == "UCC4c": gates[ind] = get_string_Cliff_ucc(gate) if gate == "UCC2" or gate == "UCC4": gates[ind] = get_string_ucc(gate) return gates def get_random_positions(self, gates=None): ''' Randomly assign gates to qubits. ''' if gates is None: gates = self.gates n_qubits = self.n_qubits single_qubit = ['X','Y','Z','S','H'] # two_qubit = ['CX','CY','CZ', 'SWAP'] two_qubit = ['CX', 'CY', 'CZ', 'SWAP', 'UCC2c', 'UCC2'] four_qubit = ['UCC4c', 'UCC4'] qubits = list(range(0, n_qubits)) q_positions = [] for gate in gates: if gate in four_qubit: p = random.sample(qubits, k=4) if gate in two_qubit: p = random.sample(qubits, k=2) if gate in single_qubit: p = random.sample(qubits, k=1) if "UCC2" in gate: p = random.sample(qubits, k=2) if "UCC4" in gate: p = random.sample(qubits, k=4) q_positions.append(p) return q_positions def delete(self, number=None): ''' Randomly drops some gates from a clifford instruction set if not specified, the number of gates to drop is sampled from a uniform distribution over all the gates ''' gates = copy.deepcopy(self.gates) positions = copy.deepcopy(self.positions) n_qubits = self.n_qubits if number is not None: num_to_drop = number else: num_to_drop = random.sample(range(1,len(gates)-1), k=1)[0] action_indices = random.sample(range(0,len(gates)-1), k=num_to_drop) for index in sorted(action_indices, reverse=True): if "UCC2_" in str(gates[index]) or "UCC4_" in str(gates[index]): self.num_non_cliffords -= 1 del gates[index] del positions[index] self.gates = gates self.positions = positions #print ('deleted {} gates'.format(num_to_drop)) def add(self, number=None): ''' adds a random selection of clifford gates to the end of a clifford instruction set if number is not specified, the number of gates to add will be drawn from a log normal distribution ''' gates = copy.deepcopy(self.gates) positions = copy.deepcopy(self.positions) n_qubits = self.n_qubits added_instructions = self.get_new_instructions(number=number) gates.extend(added_instructions['gates']) positions.extend(added_instructions['positions']) self.gates = gates self.positions = positions #print ('added {} gates'.format(len(added_instructions['gates']))) def change(self, number=None): ''' change a random number of gates and qubit positions in a clifford instruction set if not specified, the number of gates to change is sampled from a uniform distribution over all the gates ''' gates = copy.deepcopy(self.gates) positions = copy.deepcopy(self.positions) n_qubits = self.n_qubits if number is not None: num_to_change = number else: num_to_change = random.sample(range(1,len(gates)), k=1)[0] action_indices = random.sample(range(0,len(gates)-1), k=num_to_change) added_instructions = self.get_new_instructions(number=num_to_change) for i in range(num_to_change): gates[action_indices[i]] = added_instructions['gates'][i] positions[action_indices[i]] = added_instructions['positions'][i] self.gates = gates self.positions = positions #print ('changed {} gates'.format(len(added_instructions['gates']))) # TODO to be debugged! def prune(self): ''' Prune instructions to remove redundant operations: --> first gate should go beyond subsystems (this assumes expressible enough subsystem-ciruits #TODO later -> this needs subsystem information in here! --> 2 subsequent gates that are their respective inverse can be removed #TODO this might change the number of qubits acted on in theory? ''' pass #print ("DEBUG PRUNE FUNCTION!") # gates = copy.deepcopy(self.gates) # positions = copy.deepcopy(self.positions) # for g_index in range(len(gates)-1): # if (gates[g_index] == gates[g_index+1] and not 'S' in gates[g_index])\ # or (gates[g_index] == 'S' and gates[g_index+1] == 'S-dag')\ # or (gates[g_index] == 'S-dag' and gates[g_index+1] == 'S'): # print(len(gates)) # if positions[g_index] == positions[g_index+1]: # self.gates.pop(g_index) # self.positions.pop(g_index) def update_by_action(self, action: str): ''' Updates instruction dictionary -> Either adds, deletes or changes gates ''' if action == 'delete': try: self.delete() # In case there are too few gates to delete except: pass elif action == 'add': self.add() elif action == 'change': self.change() else: raise Exception("Unknown action type " + action + ".") self.prune() def update_best_previous_instructions(self): ''' Overwrites the best previous instructions with the current ones. ''' self.best_previous_instructions['gates'] = copy.deepcopy(self.gates) self.best_previous_instructions['positions'] = copy.deepcopy(self.positions) self.best_previous_instructions['T'] = copy.deepcopy(self.T) def reset_to_best(self): ''' Overwrites the current instructions with best previous ones. ''' #print ('Patience ran out... resetting to best previous instructions.') self.gates = copy.deepcopy(self.best_previous_instructions['gates']) self.positions = copy.deepcopy(self.best_previous_instructions['positions']) self.patience = copy.deepcopy(self.starting_patience) self.update_T(update_type='patience', best_temp=copy.deepcopy(self.best_previous_instructions['T'])) def get_new_instructions(self, number=None): ''' Returns a a clifford instruction set, a dictionary of gates and qubit positions for building a clifford circuit ''' mu = self.mu sigma = self.sigma n_qubits = self.n_qubits instruction = {} gates = self.get_random_gates(number=number) q_positions = self.get_random_positions(gates) assert(len(q_positions) == len(gates)) instruction['gates'] = gates instruction['positions'] = q_positions # instruction['n_qubits'] = n_qubits # instruction['patience'] = patience # instruction['best_previous_options'] = {} return instruction def replace_cg_w_ncg(self, gate_id): ''' replaces a set of Clifford gates with corresponding non-Cliffords ''' print("gates before", self.gates, flush=True) gate = self.gates[gate_id] if gate == 'X': gate = "Rx" elif gate == 'Y': gate = "Ry" elif gate == 'Z': gate = "Rz" elif gate == 'S': gate = "S_nc" #gate = "Rz" elif gate == 'H': gate = "H_nc" # this does not work??????? # gate = "Ry" elif gate == 'CX': gate = "CRx" elif gate == 'CY': gate = "CRy" elif gate == 'CZ': gate = "CRz" elif gate == 'SWAP':#find a way to change this as well pass # gate = "SWAP" elif "UCC2c" in str(gate): pre_gate = gate.split("_")[0] mid_gate = gate.split("_")[-1] gate = pre_gate + "_" + "UCC2" + "_" +mid_gate elif "UCC4c" in str(gate): pre_gate = gate.split("_")[0] mid_gate = gate.split("_")[-1] gate = pre_gate + "_" + "UCC4" + "_" + mid_gate self.gates[gate_id] = gate print("gates after", self.gates, flush=True) def build_circuit(instructions): ''' constructs a tequila circuit from a clifford instruction set ''' gates = instructions.gates q_positions = instructions.positions init_angles = {} clifford_circuit = tq.QCircuit() # for i in range(1, len(gates)): # TODO len(q_positions) not == len(gates) for i in range(len(gates)): if len(q_positions[i]) == 2: q1, q2 = q_positions[i] elif len(q_positions[i]) == 1: q1 = q_positions[i] q2 = None elif not len(q_positions[i]) == 4: raise Exception("q_positions[i] must have length 1, 2 or 4...") if gates[i] == 'X': clifford_circuit += tq.gates.X(q1) if gates[i] == 'Y': clifford_circuit += tq.gates.Y(q1) if gates[i] == 'Z': clifford_circuit += tq.gates.Z(q1) if gates[i] == 'S': clifford_circuit += tq.gates.S(q1) if gates[i] == 'H': clifford_circuit += tq.gates.H(q1) if gates[i] == 'CX': clifford_circuit += tq.gates.CX(q1, q2) if gates[i] == 'CY': #using generators clifford_circuit += tq.gates.S(q2) clifford_circuit += tq.gates.CX(q1, q2) clifford_circuit += tq.gates.S(q2).dagger() if gates[i] == 'CZ': #using generators clifford_circuit += tq.gates.H(q2) clifford_circuit += tq.gates.CX(q1, q2) clifford_circuit += tq.gates.H(q2) if gates[i] == 'SWAP': clifford_circuit += tq.gates.CX(q1, q2) clifford_circuit += tq.gates.CX(q2, q1) clifford_circuit += tq.gates.CX(q1, q2) if "UCC2c" in str(gates[i]) or "UCC4c" in str(gates[i]): clifford_circuit += get_clifford_UCC_circuit(gates[i], q_positions[i]) # NON-CLIFFORD STUFF FROM HERE ON global global_seed if gates[i] == "S_nc": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.S(q1) clifford_circuit += tq.gates.Rz(angle=var_name, target=q1) if gates[i] == "H_nc": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.H(q1) clifford_circuit += tq.gates.Ry(angle=var_name, target=q1) if gates[i] == "Rx": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.X(q1) clifford_circuit += tq.gates.Rx(angle=var_name, target=q1) if gates[i] == "Ry": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.Y(q1) clifford_circuit += tq.gates.Ry(angle=var_name, target=q1) if gates[i] == "Rz": global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0 clifford_circuit += tq.gates.Z(q1) clifford_circuit += tq.gates.Rz(angle=var_name, target=q1) if gates[i] == "CRx": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = np.pi clifford_circuit += tq.gates.Rx(angle=var_name, target=q2, control=q1) if gates[i] == "CRy": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = np.pi clifford_circuit += tq.gates.Ry(angle=var_name, target=q2, control=q1) if gates[i] == "CRz": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = np.pi clifford_circuit += tq.gates.Rz(angle=var_name, target=q2, control=q1) def get_ucc_init_angles(gate): angle = None pre_gate = gate.split("_")[0] mid_gate = gate.split("_")[-1] if mid_gate == 'Z': angle = 0. elif mid_gate == 'S': angle = 0. elif mid_gate == 'S-dag': angle = 0. else: raise Exception("This should not happen -- center/mid gate should be Z,S,S_dag.") return angle if "UCC2_" in str(gates[i]) or "UCC4_" in str(gates[i]): uccc_circuit = get_non_clifford_UCC_circuit(gates[i], q_positions[i]) clifford_circuit += uccc_circuit try: var_name = uccc_circuit.extract_variables()[0] init_angles[var_name]= get_ucc_init_angles(gates[i]) except: init_angles = {} return clifford_circuit, init_angles def get_non_clifford_UCC_circuit(gate, positions): """ """ pre_cir_dic = {"X":tq.gates.X, "Y":tq.gates.Y, "H":tq.gates.H, "I":None} pre_gate = gate.split("_")[0] pre_gates = pre_gate.split(*"#") pre_circuit = tq.QCircuit() for i, pos in enumerate(positions): try: pre_circuit += pre_cir_dic[pre_gates[i]](pos) except: pass for i, pos in enumerate(positions[:-1]): pre_circuit += tq.gates.CX(pos, positions[i+1]) global global_seed mid_gate = gate.split("_")[-1] mid_circuit = tq.QCircuit() if mid_gate == "S": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit += tq.gates.S(positions[-1]) mid_circuit += tq.gates.Rz(angle=tq.Variable(var_name), target=positions[-1]) elif mid_gate == "S-dag": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit += tq.gates.S(positions[-1]).dagger() mid_circuit += tq.gates.Rz(angle=tq.Variable(var_name), target=positions[-1]) elif mid_gate == "Z": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit += tq.gates.Z(positions[-1]) mid_circuit += tq.gates.Rz(angle=tq.Variable(var_name), target=positions[-1]) return pre_circuit + mid_circuit + pre_circuit.dagger() def get_string_Cliff_ucc(gate): """ this function randomly sample basis change and mid circuit elements for a ucc-type clifford circuit and adds it to the gate """ pre_circ_comp = ["X", "Y", "H", "I"] mid_circ_comp = ["S", "S-dag", "Z"] p = None if "UCC2c" in gate: p = random.sample(pre_circ_comp, k=2) elif "UCC4c" in gate: p = random.sample(pre_circ_comp, k=4) pre_gate = "#".join([str(item) for item in p]) mid_gate = random.sample(mid_circ_comp, k=1)[0] return str(pre_gate + "_" + gate + "_" + mid_gate) def get_string_ucc(gate): """ this function randomly sample basis change and mid circuit elements for a ucc-type clifford circuit and adds it to the gate """ pre_circ_comp = ["X", "Y", "H", "I"] p = None if "UCC2" in gate: p = random.sample(pre_circ_comp, k=2) elif "UCC4" in gate: p = random.sample(pre_circ_comp, k=4) pre_gate = "#".join([str(item) for item in p]) mid_gate = str(random.random() * 2 * np.pi) return str(pre_gate + "_" + gate + "_" + mid_gate) def get_clifford_UCC_circuit(gate, positions): """ This function creates an approximate UCC excitation circuit using only clifford Gates """ #pre_circ_comp = ["X", "Y", "H", "I"] pre_cir_dic = {"X":tq.gates.X, "Y":tq.gates.Y, "H":tq.gates.H, "I":None} pre_gate = gate.split("_")[0] pre_gates = pre_gate.split(*"#") #pre_gates = [] #if gate == "UCC2": # pre_gates = random.choices(pre_circ_comp, k=2) #if gate == "UCC4": # pre_gates = random.choices(pre_circ_comp, k=4) pre_circuit = tq.QCircuit() for i, pos in enumerate(positions): try: pre_circuit += pre_cir_dic[pre_gates[i]](pos) except: pass for i, pos in enumerate(positions[:-1]): pre_circuit += tq.gates.CX(pos, positions[i+1]) #mid_circ_comp = ["S", "S-dag", "Z"] #mid_gate = random.sample(mid_circ_comp, k=1)[0] mid_gate = gate.split("_")[-1] mid_circuit = tq.QCircuit() if mid_gate == "S": mid_circuit += tq.gates.S(positions[-1]) elif mid_gate == "S-dag": mid_circuit += tq.gates.S(positions[-1]).dagger() elif mid_gate == "Z": mid_circuit += tq.gates.Z(positions[-1]) return pre_circuit + mid_circuit + pre_circuit.dagger() def get_UCC_circuit(gate, positions): """ This function creates an UCC excitation circuit """ #pre_circ_comp = ["X", "Y", "H", "I"] pre_cir_dic = {"X":tq.gates.X, "Y":tq.gates.Y, "H":tq.gates.H, "I":None} pre_gate = gate.split("_")[0] pre_gates = pre_gate.split(*"#") pre_circuit = tq.QCircuit() for i, pos in enumerate(positions): try: pre_circuit += pre_cir_dic[pre_gates[i]](pos) except: pass for i, pos in enumerate(positions[:-1]): pre_circuit += tq.gates.CX(pos, positions[i+1]) mid_gate_val = gate.split("_")[-1] global global_seed np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit = tq.gates.Rz(target=positions[-1], angle=tq.Variable(var_name)) # mid_circ_comp = ["S", "S-dag", "Z"] # mid_gate = random.sample(mid_circ_comp, k=1)[0] # mid_circuit = tq.QCircuit() # if mid_gate == "S": # mid_circuit += tq.gates.S(positions[-1]) # elif mid_gate == "S-dag": # mid_circuit += tq.gates.S(positions[-1]).dagger() # elif mid_gate == "Z": # mid_circuit += tq.gates.Z(positions[-1]) return pre_circuit + mid_circuit + pre_circuit.dagger() def schedule_actions_ratio(epoch: int, action_options: list = ['delete', 'change', 'add'], decay: int = 30, steady_ratio: Union[tuple, list] = [0.2, 0.6, 0.2]) -> list: delete, change, add = tuple(steady_ratio) actions_ratio = [] for action in action_options: if action == 'delete': actions_ratio += [ delete*(1-np.exp(-1*epoch / decay)) ] elif action == 'change': actions_ratio += [ change*(1-np.exp(-1*epoch / decay)) ] elif action == 'add': actions_ratio += [ (1-add)*np.exp(-1*epoch / decay) + add ] else: print('Action type ', action, ' not defined!') # unnecessary for current schedule # if not np.isclose(np.sum(actions_ratio), 1.0): # actions_ratio /= np.sum(actions_ratio) return actions_ratio def get_action(ratio: list = [0.20,0.60,0.20]): ''' randomly chooses an action from delete, change, add ratio denotes the multinomial probabilities ''' choice = np.random.multinomial(n=1, pvals = ratio, size = 1) index = np.where(choice[0] == 1) action_options = ['delete', 'change', 'add'] action = action_options[index[0].item()] return action def get_prob_acceptance(E_curr, E_prev, T, reference_energy): ''' Computes acceptance probability of a certain action based on change in energy ''' delta_E = E_curr - E_prev prob = 0 if delta_E < 0 and E_curr < reference_energy: prob = 1 else: if E_curr < reference_energy: prob = np.exp(-delta_E/T) else: prob = 0 return prob def perform_folding(hamiltonian, circuit): # QubitHamiltonian -> ParamQubitHamiltonian param_hamiltonian = convert_tq_QH_to_PQH(hamiltonian) gates = circuit.gates # Go backwards gates.reverse() for gate in gates: # print("\t folding", gate) param_hamiltonian = (fold_unitary_into_hamiltonian(gate, param_hamiltonian)) # hamiltonian = convert_PQH_to_tq_QH(param_hamiltonian)() hamiltonian = param_hamiltonian return hamiltonian def evaluate_fitness(instructions, hamiltonian: tq.QubitHamiltonian, type_energy_eval: str, cluster_circuit: tq.QCircuit=None) -> tuple: ''' Evaluates fitness=objective=energy given a system for a set of instructions ''' #print ("evaluating fitness") n_qubits = instructions.n_qubits clifford_circuit, init_angles = build_circuit(instructions) # tq.draw(clifford_circuit, backend="cirq") ## TODO check if cluster_circuit is parametrized t0 = time() t1 = None folded_hamiltonian = perform_folding(hamiltonian, clifford_circuit) t1 = time() #print ("\tfolding took ", t1-t0) parametrized = len(clifford_circuit.extract_variables()) > 0 initial_guess = None if not parametrized: folded_hamiltonian = (convert_PQH_to_tq_QH(folded_hamiltonian))() elif parametrized: # TODO clifford_circuit is both ref + rest; so nomenclature is shit here variables = [gate.extract_variables() for gate in clifford_circuit.gates\ if gate.extract_variables()] variables = np.array(variables).flatten().tolist() # TODO this initial_guess is absolutely useless rn and is just causing problems if called initial_guess = { k: 0.1 for k in variables } if instructions.best_reference_wfn is not None: initial_guess = instructions.best_reference_wfn E_new, optimal_state = minimize_energy(hamiltonian=folded_hamiltonian, n_qubits=n_qubits, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit, initial_guess=initial_guess,\ initial_mixed_angles=init_angles) t2 = time() #print ("evaluated fitness; comp was ", t2-t1) #print ("current fitness: ", E_new) return E_new, optimal_state
26,497
34.096689
191
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.1/hacked_openfermion_qubit_operator.py
import tequila as tq import sympy import copy #from param_hamiltonian import get_geometry, generate_ucc_ansatz from hacked_openfermion_symbolic_operator import SymbolicOperator # Define products of all Pauli operators for symbolic multiplication. _PAULI_OPERATOR_PRODUCTS = { ('I', 'I'): (1., 'I'), ('I', 'X'): (1., 'X'), ('X', 'I'): (1., 'X'), ('I', 'Y'): (1., 'Y'), ('Y', 'I'): (1., 'Y'), ('I', 'Z'): (1., 'Z'), ('Z', 'I'): (1., 'Z'), ('X', 'X'): (1., 'I'), ('Y', 'Y'): (1., 'I'), ('Z', 'Z'): (1., 'I'), ('X', 'Y'): (1.j, 'Z'), ('X', 'Z'): (-1.j, 'Y'), ('Y', 'X'): (-1.j, 'Z'), ('Y', 'Z'): (1.j, 'X'), ('Z', 'X'): (1.j, 'Y'), ('Z', 'Y'): (-1.j, 'X') } _clifford_h_products = { ('I') : (1., 'I'), ('X') : (1., 'Z'), ('Y') : (-1., 'Y'), ('Z') : (1., 'X') } _clifford_s_products = { ('I') : (1., 'I'), ('X') : (-1., 'Y'), ('Y') : (1., 'X'), ('Z') : (1., 'Z') } _clifford_s_dag_products = { ('I') : (1., 'I'), ('X') : (1., 'Y'), ('Y') : (-1., 'X'), ('Z') : (1., 'Z') } _clifford_cx_products = { ('I', 'I'): (1., 'I', 'I'), ('I', 'X'): (1., 'I', 'X'), ('I', 'Y'): (1., 'Z', 'Y'), ('I', 'Z'): (1., 'Z', 'Z'), ('X', 'I'): (1., 'X', 'X'), ('X', 'X'): (1., 'X', 'I'), ('X', 'Y'): (1., 'Y', 'Z'), ('X', 'Z'): (-1., 'Y', 'Y'), ('Y', 'I'): (1., 'Y', 'X'), ('Y', 'X'): (1., 'Y', 'I'), ('Y', 'Y'): (-1., 'X', 'Z'), ('Y', 'Z'): (1., 'X', 'Y'), ('Z', 'I'): (1., 'Z', 'I'), ('Z', 'X'): (1., 'Z', 'X'), ('Z', 'Y'): (1., 'I', 'Y'), ('Z', 'Z'): (1., 'I', 'Z'), } _clifford_cy_products = { ('I', 'I'): (1., 'I', 'I'), ('I', 'X'): (1., 'Z', 'X'), ('I', 'Y'): (1., 'I', 'Y'), ('I', 'Z'): (1., 'Z', 'Z'), ('X', 'I'): (1., 'X', 'Y'), ('X', 'X'): (-1., 'Y', 'Z'), ('X', 'Y'): (1., 'X', 'I'), ('X', 'Z'): (-1., 'Y', 'X'), ('Y', 'I'): (1., 'Y', 'Y'), ('Y', 'X'): (1., 'X', 'Z'), ('Y', 'Y'): (1., 'Y', 'I'), ('Y', 'Z'): (-1., 'X', 'X'), ('Z', 'I'): (1., 'Z', 'I'), ('Z', 'X'): (1., 'I', 'X'), ('Z', 'Y'): (1., 'Z', 'Y'), ('Z', 'Z'): (1., 'I', 'Z'), } _clifford_cz_products = { ('I', 'I'): (1., 'I', 'I'), ('I', 'X'): (1., 'Z', 'X'), ('I', 'Y'): (1., 'Z', 'Y'), ('I', 'Z'): (1., 'I', 'Z'), ('X', 'I'): (1., 'X', 'Z'), ('X', 'X'): (-1., 'Y', 'Y'), ('X', 'Y'): (-1., 'Y', 'X'), ('X', 'Z'): (1., 'X', 'I'), ('Y', 'I'): (1., 'Y', 'Z'), ('Y', 'X'): (-1., 'X', 'Y'), ('Y', 'Y'): (1., 'X', 'X'), ('Y', 'Z'): (1., 'Y', 'I'), ('Z', 'I'): (1., 'Z', 'I'), ('Z', 'X'): (1., 'I', 'X'), ('Z', 'Y'): (1., 'I', 'Y'), ('Z', 'Z'): (1., 'Z', 'Z'), } COEFFICIENT_TYPES = (int, float, complex, sympy.Expr, tq.Variable) class ParamQubitHamiltonian(SymbolicOperator): @property def actions(self): """The allowed actions.""" return ('X', 'Y', 'Z') @property def action_strings(self): """The string representations of the allowed actions.""" return ('X', 'Y', 'Z') @property def action_before_index(self): """Whether action comes before index in string representations.""" return True @property def different_indices_commute(self): """Whether factors acting on different indices commute.""" return True def renormalize(self): """Fix the trace norm of an operator to 1""" norm = self.induced_norm(2) if numpy.isclose(norm, 0.0): raise ZeroDivisionError('Cannot renormalize empty or zero operator') else: self /= norm def _simplify(self, term, coefficient=1.0): """Simplify a term using commutator and anti-commutator relations.""" if not term: return coefficient, term term = sorted(term, key=lambda factor: factor[0]) new_term = [] left_factor = term[0] for right_factor in term[1:]: left_index, left_action = left_factor right_index, right_action = right_factor # Still on the same qubit, keep simplifying. if left_index == right_index: new_coefficient, new_action = _PAULI_OPERATOR_PRODUCTS[ left_action, right_action] left_factor = (left_index, new_action) coefficient *= new_coefficient # Reached different qubit, save result and re-initialize. else: if left_action != 'I': new_term.append(left_factor) left_factor = right_factor # Save result of final iteration. if left_factor[1] != 'I': new_term.append(left_factor) return coefficient, tuple(new_term) def _clifford_simplify_h(self, qubit): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 for left, right in term: if left == qubit: coeff, new_pauli = _clifford_h_products[right] new_term.append(tuple((left, new_pauli))) else: new_term.append(tuple((left,right))) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self def _clifford_simplify_s(self, qubit): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 for left, right in term: if left == qubit: coeff, new_pauli = _clifford_s_products[right] new_term.append(tuple((left, new_pauli))) else: new_term.append(tuple((left,right))) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self def _clifford_simplify_s_dag(self, qubit): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 for left, right in term: if left == qubit: coeff, new_pauli = _clifford_s_dag_products[right] new_term.append(tuple((left, new_pauli))) else: new_term.append(tuple((left,right))) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self def _clifford_simplify_control_g(self, axis, control_q, target_q): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 target = "I" control = "I" for left, right in term: if left == control_q: control = right elif left == target_q: target = right else: new_term.append(tuple((left,right))) new_c = "I" new_t = "I" if not (target == "I" and control == "I"): if axis == "X": coeff, new_c, new_t = _clifford_cx_products[control, target] if axis == "Y": coeff, new_c, new_t = _clifford_cy_products[control, target] if axis == "Z": coeff, new_c, new_t = _clifford_cz_products[control, target] if new_c != "I": new_term.append(tuple((control_q, new_c))) if new_t != "I": new_term.append(tuple((target_q, new_t))) new_term = sorted(new_term, key=lambda factor: factor[0]) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self if __name__ == "__main__": """geometry = get_geometry("H2", 0.714) print(geometry) basis_set = 'sto-3g' ref_anz, uccsd_anz, ham = generate_ucc_ansatz(geometry, basis_set) print(ham) b_ham = tq.grouping.binary_rep.BinaryHamiltonian.init_from_qubit_hamiltonian(ham) c_ham = tq.grouping.binary_rep.BinaryHamiltonian.init_from_qubit_hamiltonian(ham) print(b_ham) print(b_ham.get_binary()) print(b_ham.get_coeff()) param = uccsd_anz.extract_variables() print(param) for term in b_ham.binary_terms: print(term.coeff) term.set_coeff(param[0]) print(term.coeff) print(b_ham.get_coeff()) d_ham = c_ham.to_qubit_hamiltonian() + b_ham.to_qubit_hamiltonian() """ term = [(2,'X'), (0,'Y'), (3, 'Z')] coeff = tq.Variable("a") coeff = coeff *2.j print(coeff) print(type(coeff)) print(coeff({"a":1})) ham = ParamQubitHamiltonian(term= term, coefficient=coeff) print(ham.terms) print(str(ham)) for term in ham.terms: print(ham.terms[term]({"a":1,"b":2})) term = [(2,'X'), (0,'Z'), (3, 'Z')] coeff = tq.Variable("b") print(coeff({"b":1})) b_ham = ParamQubitHamiltonian(term= term, coefficient=coeff) print(b_ham.terms) print(str(b_ham)) for term in b_ham.terms: print(b_ham.terms[term]({"a":1,"b":2})) coeff = tq.Variable("a")*tq.Variable("b") print(coeff) print(coeff({"a":1,"b":2})) ham *= b_ham print(ham.terms) print(str(ham)) for term in ham.terms: coeff = (ham.terms[term]) print(coeff) print(coeff({"a":1,"b":2})) ham = ham*2. print(ham.terms) print(str(ham))
9,918
29.614198
85
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.1/HEA.py
import tequila as tq import numpy as np from tequila import gates as tq_g from tequila.objective.objective import Variable def generate_HEA(num_qubits, circuit_id=11, num_layers=1): """ This function generates different types of hardware efficient circuits as in this paper https://onlinelibrary.wiley.com/doi/full/10.1002/qute.201900070 param: num_qubits (int) -> the number of qubits in the circuit param: circuit_id (int) -> the type of hardware efficient circuit param: num_layers (int) -> the number of layers of the HEA input: num_qubits -> 4 circuit_id -> 11 num_layers -> 1 returns: ansatz (tq.QCircuit()) -> a circuit as shown below 0: ───Ry(0.318309886183791*pi*f((y0,))_0)───Rz(0.318309886183791*pi*f((z0,))_1)───@───────────────────────────────────────────────────────────────────────────────────── │ 1: ───Ry(0.318309886183791*pi*f((y1,))_2)───Rz(0.318309886183791*pi*f((z1,))_3)───X───Ry(0.318309886183791*pi*f((y4,))_8)────Rz(0.318309886183791*pi*f((z4,))_9)────@─── │ 2: ───Ry(0.318309886183791*pi*f((y2,))_4)───Rz(0.318309886183791*pi*f((z2,))_5)───@───Ry(0.318309886183791*pi*f((y5,))_10)───Rz(0.318309886183791*pi*f((z5,))_11)───X─── │ 3: ───Ry(0.318309886183791*pi*f((y3,))_6)───Rz(0.318309886183791*pi*f((z3,))_7)───X───────────────────────────────────────────────────────────────────────────────────── """ circuit = tq.QCircuit() qubits = [i for i in range(num_qubits)] if circuit_id == 1: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 2: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.CNOT(target=qubit, control=qubits[ind]) return circuit elif circuit_id == 3: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=qubit, control=qubits[ind]) count += 1 return circuit elif circuit_id == 4: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=qubit, control=qubits[ind]) count += 1 return circuit elif circuit_id == 5: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): for target in qubits: if control != target: variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=target, control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 6: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=qubits[ind+1], control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=qubits[ind+1], control=control) count += 1 return circuit elif circuit_id == 7: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): for target in qubits: if control != target: variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=target, control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 8: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=qubits[ind+1], control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=qubits[ind+1], control=control) count += 1 return circuit elif circuit_id == 9: count = 0 for _ in range(num_layers): for qubit in qubits: circuit += tq_g.H(qubit) for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.Z(target=qubit, control=qubits[ind]) for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 10: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.Z(target=qubit, control=qubits[ind]) circuit += tq_g.Z(target=qubits[0], control=qubits[-1]) for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 11: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: circuit += tq_g.X(target=qubits[ind+1], control=control) for ind, qubit in enumerate(qubits[1:-1]): variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: circuit += tq_g.X(target=qubits[ind+1], control=control) return circuit elif circuit_id == 12: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: circuit += tq_g.Z(target=qubits[ind+1], control=control) for ind, control in enumerate(qubits[1:-1]): variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = control) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = control) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: circuit += tq_g.Z(target=qubits[ind+1], control=control) return circuit elif circuit_id == 13: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubit, control=qubits[ind]) count += 1 variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubits[0], control=qubits[-1]) count += 1 for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=qubit, target=qubits[ind]) count += 1 variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=qubits[0], target=qubits[-1]) count += 1 return circuit elif circuit_id == 14: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubit, control=qubits[ind]) count += 1 variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubits[0], control=qubits[-1]) count += 1 for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=qubit, target=qubits[ind]) count += 1 variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=qubits[0], target=qubits[-1]) count += 1 return circuit elif circuit_id == 15: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.X(target=qubit, control=qubits[ind]) circuit += tq_g.X(control=qubits[-1], target=qubits[0]) for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.X(control=qubit, target=qubits[ind]) circuit += tq_g.X(target=qubits[-1], control=qubits[0]) return circuit elif circuit_id == 16: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=control, target=qubits[ind+1]) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=control, target=qubits[ind+1]) count += 1 return circuit elif circuit_id == 17: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=control, target=qubits[ind+1]) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=control, target=qubits[ind+1]) count += 1 return circuit elif circuit_id == 18: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[:-1]): variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubit, control=qubits[ind+1]) count += 1 variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubits[-1], control=qubits[0]) count += 1 return circuit elif circuit_id == 19: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[:-1]): variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubit, control=qubits[ind+1]) count += 1 variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubits[-1], control=qubits[0]) count += 1 return circuit
18,425
45.530303
172
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.1/grad_hacked.py
from tequila.circuit.compiler import CircuitCompiler from tequila.objective.objective import Objective, ExpectationValueImpl, Variable, \ assign_variable, identity, FixedVariable from tequila import TequilaException from tequila.objective import QTensor from tequila.simulators.simulator_api import compile import typing from numpy import vectorize from tequila.autograd_imports import jax, __AUTOGRAD__BACKEND__ def grad(objective: typing.Union[Objective, QTensor], variable: Variable = None, no_compile=False, *args, **kwargs): ''' wrapper function for getting the gradients of Objectives,ExpectationValues, Unitaries (including single gates), and Transforms. :param obj (QCircuit,ParametrizedGateImpl,Objective,ExpectationValue,Transform,Variable): structure to be differentiated :param variables (list of Variable): parameter with respect to which obj should be differentiated. default None: total gradient. return: dictionary of Objectives, if called on gate, circuit, exp.value, or objective; if Variable or Transform, returns number. ''' if variable is None: # None means that all components are created variables = objective.extract_variables() result = {} if len(variables) == 0: raise TequilaException("Error in gradient: Objective has no variables") for k in variables: assert (k is not None) result[k] = grad(objective, k, no_compile=no_compile) return result else: variable = assign_variable(variable) if isinstance(objective, QTensor): f = lambda x: grad(objective=x, variable=variable, *args, **kwargs) ff = vectorize(f) return ff(objective) if variable not in objective.extract_variables(): return Objective() if no_compile: compiled = objective else: compiler = CircuitCompiler(multitarget=True, trotterized=True, hadamard_power=True, power=True, controlled_phase=True, controlled_rotation=True, gradient_mode=True) compiled = compiler(objective, variables=[variable]) if variable not in compiled.extract_variables(): raise TequilaException("Error in taking gradient. Objective does not depend on variable {} ".format(variable)) if isinstance(objective, ExpectationValueImpl): return __grad_expectationvalue(E=objective, variable=variable) elif objective.is_expectationvalue(): return __grad_expectationvalue(E=compiled.args[-1], variable=variable) elif isinstance(compiled, Objective) or (hasattr(compiled, "args") and hasattr(compiled, "transformation")): return __grad_objective(objective=compiled, variable=variable) else: raise TequilaException("Gradient not implemented for other types than ExpectationValue and Objective.") def __grad_objective(objective: Objective, variable: Variable): args = objective.args transformation = objective.transformation dO = None processed_expectationvalues = {} for i, arg in enumerate(args): if __AUTOGRAD__BACKEND__ == "jax": df = jax.grad(transformation, argnums=i, holomorphic=True) elif __AUTOGRAD__BACKEND__ == "autograd": df = jax.grad(transformation, argnum=i) else: raise TequilaException("Can't differentiate without autograd or jax") # We can detect one simple case where the outer derivative is const=1 if transformation is None or transformation == identity: outer = 1.0 else: outer = Objective(args=args, transformation=df) if hasattr(arg, "U"): # save redundancies if arg in processed_expectationvalues: inner = processed_expectationvalues[arg] else: inner = __grad_inner(arg=arg, variable=variable) processed_expectationvalues[arg] = inner else: # this means this inner derivative is purely variable dependent inner = __grad_inner(arg=arg, variable=variable) if inner == 0.0: # don't pile up zero expectationvalues continue if dO is None: dO = outer * inner else: dO = dO + outer * inner if dO is None: raise TequilaException("caught None in __grad_objective") return dO # def __grad_vector_objective(objective: Objective, variable: Variable): # argsets = objective.argsets # transformations = objective._transformations # outputs = [] # for pos in range(len(objective)): # args = argsets[pos] # transformation = transformations[pos] # dO = None # # processed_expectationvalues = {} # for i, arg in enumerate(args): # if __AUTOGRAD__BACKEND__ == "jax": # df = jax.grad(transformation, argnums=i) # elif __AUTOGRAD__BACKEND__ == "autograd": # df = jax.grad(transformation, argnum=i) # else: # raise TequilaException("Can't differentiate without autograd or jax") # # # We can detect one simple case where the outer derivative is const=1 # if transformation is None or transformation == identity: # outer = 1.0 # else: # outer = Objective(args=args, transformation=df) # # if hasattr(arg, "U"): # # save redundancies # if arg in processed_expectationvalues: # inner = processed_expectationvalues[arg] # else: # inner = __grad_inner(arg=arg, variable=variable) # processed_expectationvalues[arg] = inner # else: # # this means this inner derivative is purely variable dependent # inner = __grad_inner(arg=arg, variable=variable) # # if inner == 0.0: # # don't pile up zero expectationvalues # continue # # if dO is None: # dO = outer * inner # else: # dO = dO + outer * inner # # if dO is None: # dO = Objective() # outputs.append(dO) # if len(outputs) == 1: # return outputs[0] # return outputs def __grad_inner(arg, variable): ''' a modified loop over __grad_objective, which gets derivatives all the way down to variables, return 1 or 0 when a variable is (isnt) identical to var. :param arg: a transform or variable object, to be differentiated :param variable: the Variable with respect to which par should be differentiated. :ivar var: the string representation of variable ''' assert (isinstance(variable, Variable)) if isinstance(arg, Variable): if arg == variable: return 1.0 else: return 0.0 elif isinstance(arg, FixedVariable): return 0.0 elif isinstance(arg, ExpectationValueImpl): return __grad_expectationvalue(arg, variable=variable) elif hasattr(arg, "abstract_expectationvalue"): E = arg.abstract_expectationvalue dE = __grad_expectationvalue(E, variable=variable) return compile(dE, **arg._input_args) else: return __grad_objective(objective=arg, variable=variable) def __grad_expectationvalue(E: ExpectationValueImpl, variable: Variable): ''' implements the analytic partial derivative of a unitary as it would appear in an expectation value. See the paper. :param unitary: the unitary whose gradient should be obtained :param variables (list, dict, str): the variables with respect to which differentiation should be performed. :return: vector (as dict) of dU/dpi as Objective (without hamiltonian) ''' hamiltonian = E.H unitary = E.U if not (unitary.verify()): raise TequilaException("error in grad_expectationvalue unitary is {}".format(unitary)) # fast return if possible if variable not in unitary.extract_variables(): return 0.0 param_gates = unitary._parameter_map[variable] dO = Objective() for idx_g in param_gates: idx, g = idx_g dOinc = __grad_shift_rule(unitary, g, idx, variable, hamiltonian) dO += dOinc assert dO is not None return dO def __grad_shift_rule(unitary, g, i, variable, hamiltonian): ''' function for getting the gradients of directly differentiable gates. Expects precompiled circuits. :param unitary: QCircuit: the QCircuit object containing the gate to be differentiated :param g: a parametrized: the gate being differentiated :param i: Int: the position in unitary at which g appears :param variable: Variable or String: the variable with respect to which gate g is being differentiated :param hamiltonian: the hamiltonian with respect to which unitary is to be measured, in the case that unitary is contained within an ExpectationValue :return: an Objective, whose calculation yields the gradient of g w.r.t variable ''' # possibility for overwride in custom gate construction if hasattr(g, "shifted_gates"): inner_grad = __grad_inner(g.parameter, variable) shifted = g.shifted_gates() dOinc = Objective() for x in shifted: w, g = x Ux = unitary.replace_gates(positions=[i], circuits=[g]) wx = w * inner_grad Ex = Objective.ExpectationValue(U=Ux, H=hamiltonian) dOinc += wx * Ex return dOinc else: raise TequilaException('No shift found for gate {}\nWas the compiler called?'.format(g))
9,886
38.548
132
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.1/vqe_utils.py
import tequila as tq import numpy as np from hacked_openfermion_qubit_operator import ParamQubitHamiltonian from openfermion import QubitOperator from HEA import * def get_ansatz_circuit(ansatz_type, geometry, basis_set=None, trotter_steps = 1, name=None, circuit_id=None,num_layers=1): """ This function generates the ansatz for the molecule and the Hamiltonian param: ansatz_type (str) -> the type of the ansatz ('UCCSD, UpCCGSD, SPA, HEA') param: geometry (str) -> the geometry of the molecule param: basis_set (str) -> the basis set for wchich the ansatz has to generated param: trotter_steps (int) -> the number of trotter step to be used in the trotter decomposition param: name (str) -> the name for the madness molecule param: circuit_id (int) -> the type of hardware efficient ansatz param: num_layers (int) -> the number of layers of the HEA e.g.: input: ansatz_type -> "UCCSD" geometry -> "H 0.0 0.0 0.0\nH 0.0 0.0 0.714" basis_set -> 'sto-3g' trotter_steps -> 1 name -> None circuit_id -> None num_layers -> 1 returns: ucc_ansatz (tq.QCircuit()) -> a circuit printed below: circuit: FermionicExcitation(target=(0, 1, 2, 3), control=(), parameter=Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = []) FermionicExcitation(target=(0, 1, 2, 3), control=(), parameter=Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = []) Hamiltonian (tq.QubitHamiltonian()) -> -0.0621+0.1755Z(0)+0.1755Z(1)-0.2358Z(2)-0.2358Z(3)+0.1699Z(0)Z(1) +0.0449Y(0)X(1)X(2)Y(3)-0.0449Y(0)Y(1)X(2)X(3)-0.0449X(0)X(1)Y(2)Y(3) +0.0449X(0)Y(1)Y(2)X(3)+0.1221Z(0)Z(2)+0.1671Z(0)Z(3)+0.1671Z(1)Z(2) +0.1221Z(1)Z(3)+0.1756Z(2)Z(3) fci_ener (float) -> """ ham = tq.QubitHamiltonian() fci_ener = 0.0 ansatz = tq.QCircuit() if ansatz_type == "UCCSD": molecule = tq.Molecule(geometry=geometry, basis_set=basis_set) ansatz = molecule.make_uccsd_ansatz(trotter_steps) ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy(method="fci") elif ansatz_type == "UCCS": molecule = tq.Molecule(geometry=geometry, basis_set=basis_set, backend='psi4') ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy("fci") indices = molecule.make_upccgsd_indices(key='UCCS') print("indices are:", indices) ansatz = molecule.make_upccgsd_layer(indices=indices, include_singles=True, include_doubles=False) elif ansatz_type == "UpCCGSD": molecule = tq.Molecule(name=name, geometry=geometry, n_pno=None) ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy("fci") ansatz = molecule.make_upccgsd_ansatz() elif ansatz_type == "SPA": molecule = tq.Molecule(name=name, geometry=geometry, n_pno=None) ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy("fci") ansatz = molecule.make_upccgsd_ansatz(name="SPA") elif ansatz_type == "HEA": molecule = tq.Molecule(geometry=geometry, basis_set=basis_set) ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy(method="fci") ansatz = generate_HEA(molecule.n_orbitals * 2, circuit_id) else: raise Exception("not implemented any other ansatz, please choose from 'UCCSD, UpCCGSD, SPA, HEA'") return ansatz, ham, fci_ener def get_generator_for_gates(unitary): """ This function takes a unitary gate and returns the generator of the the gate so that it can be padded to the Hamiltonian param: unitary (tq.QGateImpl()) -> the unitary circuit element that has to be converted to a paulistring e.g.: input: unitary -> a FermionicGateImpl object as the one printed below FermionicExcitation(target=(0, 1, 2, 3), control=(), parameter=Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = []) returns: parameter (tq.Variable()) -> (1, 0, 1, 0) generator (tq.QubitHamiltonian()) -> -0.1250Y(0)Y(1)Y(2)X(3)+0.1250Y(0)X(1)Y(2)Y(3) +0.1250X(0)X(1)Y(2)X(3)+0.1250X(0)Y(1)Y(2)Y(3) -0.1250Y(0)X(1)X(2)X(3)-0.1250Y(0)Y(1)X(2)Y(3) -0.1250X(0)Y(1)X(2)X(3)+0.1250X(0)X(1)X(2)Y(3) null_proj (tq.QubitHamiltonian()) -> -0.1250Z(0)Z(1)+0.1250Z(1)Z(3)+0.1250Z(0)Z(3) +0.1250Z(1)Z(2)+0.1250Z(0)Z(2)-0.1250Z(2)Z(3) -0.1250Z(0)Z(1)Z(2)Z(3) """ try: parameter = None generator = None null_proj = None if isinstance(unitary, tq.quantumchemistry.qc_base.FermionicGateImpl): parameter = unitary.extract_variables() generator = unitary.generator null_proj = unitary.p0 else: #getting parameter if unitary.is_parametrized(): parameter = unitary.extract_variables() else: parameter = [None] try: generator = unitary.make_generator(include_controls=True) except: generator = unitary.generator() """if len(parameter) == 0: parameter = [tq.objective.objective.assign_variable(unitary.parameter)]""" return parameter[0], generator, null_proj except Exception as e: print("An Exception happened, details :",e) pass def fold_unitary_into_hamiltonian(unitary, Hamiltonian): """ This function return a list of the resulting Hamiltonian terms after folding the paulistring correspondig to the unitary into the Hamiltonian param: unitary (tq.QGateImpl()) -> the unitary to be folded into the Hamiltonian param: Hamiltonian (ParamQubitHamiltonian()) -> the Hamiltonian of the system e.g.: input: unitary -> a FermionicGateImpl object as the one printed below FermionicExcitation(target=(0, 1, 2, 3), control=(), parameter=Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = []) Hamiltonian -> -0.06214952615456104 [] + -0.044941923860490916 [X0 X1 Y2 Y3] + 0.044941923860490916 [X0 Y1 Y2 X3] + 0.044941923860490916 [Y0 X1 X2 Y3] + -0.044941923860490916 [Y0 Y1 X2 X3] + 0.17547360045040505 [Z0] + 0.16992958569230643 [Z0 Z1] + 0.12212314332112947 [Z0 Z2] + 0.1670650671816204 [Z0 Z3] + 0.17547360045040508 [Z1] + 0.1670650671816204 [Z1 Z2] + 0.12212314332112947 [Z1 Z3] + -0.23578915712819945 [Z2] + 0.17561918557144712 [Z2 Z3] + -0.23578915712819945 [Z3] returns: folded_hamiltonian (ParamQubitHamiltonian()) -> Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [X0 X1 X2 X3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [X0 X1 Y2 Y3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [X0 Y1 X2 Y3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [X0 Y1 Y2 X3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Y0 X1 X2 Y3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Y0 X1 Y2 X3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Y0 Y1 X2 X3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Y0 Y1 Y2 Y3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z1] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z1 Z2] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z1 Z2 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z1 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z2] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z2 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z1] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z1 Z2] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z1 Z2 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z1 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z2] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z2 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z3] """ folded_hamiltonian = ParamQubitHamiltonian() if isinstance(unitary, tq.circuit._gates_impl.DifferentiableGateImpl) and not isinstance(unitary, tq.circuit._gates_impl.PhaseGateImpl): variable, generator, null_proj = get_generator_for_gates(unitary) # print(generator) # print(null_proj) #converting into ParamQubitHamiltonian() c_generator = convert_tq_QH_to_PQH(generator) """c_null_proj = convert_tq_QH_to_PQH(null_proj) print(variable) prod1 = (null_proj*ham*generator - generator*ham*null_proj) print(prod1) #print((Hamiltonian*c_generator)) prod2 = convert_PQH_to_tq_QH(c_null_proj*Hamiltonian*c_generator - c_generator*Hamiltonian*c_null_proj)({var:0.1 for var in variable.extract_variables()}) print(prod2) assert prod1 ==prod2 raise Exception("testing")""" #print("starting", flush=True) #handling the parameterize gates if variable is not None: #print("folding generator") # adding the term: cos^2(\theta)*H temp_ham = ParamQubitHamiltonian().identity() temp_ham *= Hamiltonian temp_ham *= (variable.apply(tq.numpy.cos)**2) #print(convert_PQH_to_tq_QH(temp_ham)({var:1. for var in variable.extract_variables()})) folded_hamiltonian += temp_ham #print("step1 done", flush=True) # adding the term: sin^2(\theta)*G*H*G temp_ham = ParamQubitHamiltonian().identity() temp_ham *= c_generator temp_ham *= Hamiltonian temp_ham *= c_generator temp_ham *= (variable.apply(tq.numpy.sin)**2) #print(convert_PQH_to_tq_QH(temp_ham)({var:1. for var in variable.extract_variables()})) folded_hamiltonian += temp_ham #print("step2 done", flush=True) # adding the term: i*cos^2(\theta)8sin^2(\theta)*(G*H -H*G) temp_ham1 = ParamQubitHamiltonian().identity() temp_ham1 *= c_generator temp_ham1 *= Hamiltonian temp_ham2 = ParamQubitHamiltonian().identity() temp_ham2 *= Hamiltonian temp_ham2 *= c_generator temp_ham = temp_ham1 - temp_ham2 temp_ham *= 1.0j temp_ham *= variable.apply(tq.numpy.sin) * variable.apply(tq.numpy.cos) #print(convert_PQH_to_tq_QH(temp_ham)({var:1. for var in variable.extract_variables()})) folded_hamiltonian += temp_ham #print("step3 done", flush=True) #handling the non-paramterized gates else: raise Exception("This function is not implemented yet") # adding the term: G*H*G folded_hamiltonian += c_generator*Hamiltonian*c_generator #print("Halfway there", flush=True) #handle the FermionicGateImpl gates if null_proj is not None: print("folding null projector") c_null_proj = convert_tq_QH_to_PQH(null_proj) #print("step4 done", flush=True) # adding the term: (1-cos(\theta))^2*P0*H*P0 temp_ham = ParamQubitHamiltonian().identity() temp_ham *= c_null_proj temp_ham *= Hamiltonian temp_ham *= c_null_proj temp_ham *= ((1-variable.apply(tq.numpy.cos))**2) folded_hamiltonian += temp_ham #print("step5 done", flush=True) # adding the term: 2*cos(\theta)*(1-cos(\theta))*(P0*H +H*P0) temp_ham1 = ParamQubitHamiltonian().identity() temp_ham1 *= c_null_proj temp_ham1 *= Hamiltonian temp_ham2 = ParamQubitHamiltonian().identity() temp_ham2 *= Hamiltonian temp_ham2 *= c_null_proj temp_ham = temp_ham1 + temp_ham2 temp_ham *= (variable.apply(tq.numpy.cos)*(1-variable.apply(tq.numpy.cos))) folded_hamiltonian += temp_ham #print("step6 done", flush=True) # adding the term: i*sin(\theta)*(1-cos(\theta))*(G*H*P0 - P0*H*G) temp_ham1 = ParamQubitHamiltonian().identity() temp_ham1 *= c_generator temp_ham1 *= Hamiltonian temp_ham1 *= c_null_proj temp_ham2 = ParamQubitHamiltonian().identity() temp_ham2 *= c_null_proj temp_ham2 *= Hamiltonian temp_ham2 *= c_generator temp_ham = temp_ham1 - temp_ham2 temp_ham *= 1.0j temp_ham *= (variable.apply(tq.numpy.sin)*(1-variable.apply(tq.numpy.cos))) folded_hamiltonian += temp_ham #print("step7 done", flush=True) elif isinstance(unitary, tq.circuit._gates_impl.PhaseGateImpl): if np.isclose(unitary.parameter, np.pi/2.0): return Hamiltonian._clifford_simplify_s(unitary.qubits[0]) elif np.isclose(unitary.parameter, -1.*np.pi/2.0): return Hamiltonian._clifford_simplify_s_dag(unitary.qubits[0]) else: raise Exception("Only DifferentiableGateImpl, PhaseGateImpl(S), Pauligate(X,Y,Z), Controlled(X,Y,Z) and Hadamrd(H) implemented yet") elif isinstance(unitary, tq.circuit._gates_impl.QGateImpl): if unitary.is_controlled(): if unitary.name == "X": return Hamiltonian._clifford_simplify_control_g("X", unitary.control[0], unitary.target[0]) elif unitary.name == "Y": return Hamiltonian._clifford_simplify_control_g("Y", unitary.control[0], unitary.target[0]) elif unitary.name == "Z": return Hamiltonian._clifford_simplify_control_g("Z", unitary.control[0], unitary.target[0]) else: raise Exception("Only DifferentiableGateImpl, PhaseGateImpl(S), Pauligate(X,Y,Z), Controlled(X,Y,Z) and Hadamrd(H) implemented yet") else: if unitary.name == "X": gate = convert_tq_QH_to_PQH(tq.paulis.X(unitary.qubits[0])) return gate*Hamiltonian*gate elif unitary.name == "Y": gate = convert_tq_QH_to_PQH(tq.paulis.Y(unitary.qubits[0])) return gate*Hamiltonian*gate elif unitary.name == "Z": gate = convert_tq_QH_to_PQH(tq.paulis.Z(unitary.qubits[0])) return gate*Hamiltonian*gate elif unitary.name == "H": return Hamiltonian._clifford_simplify_h(unitary.qubits[0]) else: raise Exception("Only DifferentiableGateImpl, PhaseGateImpl(S), Pauligate(X,Y,Z), Controlled(X,Y,Z) and Hadamrd(H) implemented yet") else: raise Exception("Only DifferentiableGateImpl, PhaseGateImpl(S), Pauligate(X,Y,Z), Controlled(X,Y,Z) and Hadamrd(H) implemented yet") return folded_hamiltonian def convert_tq_QH_to_PQH(Hamiltonian): """ This function takes the tequila QubitHamiltonian object and converts into a ParamQubitHamiltonian object. param: Hamiltonian (tq.QubitHamiltonian()) -> the Hamiltonian to be converted e.g: input: Hamiltonian -> -0.0621+0.1755Z(0)+0.1755Z(1)-0.2358Z(2)-0.2358Z(3)+0.1699Z(0)Z(1) +0.0449Y(0)X(1)X(2)Y(3)-0.0449Y(0)Y(1)X(2)X(3)-0.0449X(0)X(1)Y(2)Y(3) +0.0449X(0)Y(1)Y(2)X(3)+0.1221Z(0)Z(2)+0.1671Z(0)Z(3)+0.1671Z(1)Z(2) +0.1221Z(1)Z(3)+0.1756Z(2)Z(3) returns: param_hamiltonian (ParamQubitHamiltonian()) -> -0.06214952615456104 [] + -0.044941923860490916 [X0 X1 Y2 Y3] + 0.044941923860490916 [X0 Y1 Y2 X3] + 0.044941923860490916 [Y0 X1 X2 Y3] + -0.044941923860490916 [Y0 Y1 X2 X3] + 0.17547360045040505 [Z0] + 0.16992958569230643 [Z0 Z1] + 0.12212314332112947 [Z0 Z2] + 0.1670650671816204 [Z0 Z3] + 0.17547360045040508 [Z1] + 0.1670650671816204 [Z1 Z2] + 0.12212314332112947 [Z1 Z3] + -0.23578915712819945 [Z2] + 0.17561918557144712 [Z2 Z3] + -0.23578915712819945 [Z3] """ param_hamiltonian = ParamQubitHamiltonian() Hamiltonian = Hamiltonian.to_openfermion() for term in Hamiltonian.terms: param_hamiltonian += ParamQubitHamiltonian(term = term, coefficient = Hamiltonian.terms[term]) return param_hamiltonian class convert_PQH_to_tq_QH: def __init__(self, Hamiltonian): self.param_hamiltonian = Hamiltonian def __call__(self,variables=None): """ This function takes the ParamQubitHamiltonian object and converts into a tequila QubitHamiltonian object. param: param_hamiltonian (ParamQubitHamiltonian()) -> the Hamiltonian to be converted param: variables (dict) -> a dictionary with the values of the variables in the Hamiltonian coefficient e.g: input: param_hamiltonian -> a [Y0 X2 Z3] + b [Z0 X2 Z3] variables -> {"a":1,"b":2} returns: Hamiltonian (tq.QubitHamiltonian()) -> +1.0000Y(0)X(2)Z(3)+2.0000Z(0)X(2)Z(3) """ Hamiltonian = tq.QubitHamiltonian() for term in self.param_hamiltonian.terms: val = self.param_hamiltonian.terms[term]# + self.param_hamiltonian.imag_terms[term]*1.0j if isinstance(val, tq.Variable) or isinstance(val, tq.objective.objective.Objective): try: for key in variables.keys(): variables[key] = variables[key] #print(variables) val = val(variables) #print(val) except Exception as e: print(e) raise Exception("You forgot to pass the dictionary with the values of the variables") Hamiltonian += tq.QubitHamiltonian(QubitOperator(term=term, coefficient=val)) return Hamiltonian def _construct_derivatives(self, variables=None): """ """ derivatives = {} variable_names = [] for term in self.param_hamiltonian.terms: val = self.param_hamiltonian.terms[term]# + self.param_hamiltonian.imag_terms[term]*1.0j #print(val) if isinstance(val, tq.Variable) or isinstance(val, tq.objective.objective.Objective): variable = val.extract_variables() for var in list(variable): from grad_hacked import grad derivative = ParamQubitHamiltonian(term = term, coefficient = grad(val, var)) if var not in variable_names: variable_names.append(var) if var not in list(derivatives.keys()): derivatives[var] = derivative else: derivatives[var] += derivative return variable_names, derivatives def get_geometry(name, b_l): """ This is utility fucntion that generates tehe geometry string of a Molecule param: name (str) -> name of the molecule param: b_l (float) -> the bond length of the molecule e.g.: input: name -> "H2" b_l -> 0.714 returns: geo_str (str) -> "H 0.0 0.0 0.0\nH 0.0 0.0 0.714" """ geo_str = None if name == "LiH": geo_str = "H 0.0 0.0 0.0\nLi 0.0 0.0 {0}".format(b_l) elif name == "H2": geo_str = "H 0.0 0.0 0.0\nH 0.0 0.0 {0}".format(b_l) elif name == "BeH2": geo_str = "H 0.0 0.0 {0}\nH 0.0 0.0 {1}\nBe 0.0 0.0 0.0".format(b_l,-1*b_l) elif name == "N2": geo_str = "N 0.0 0.0 0.0\nN 0.0 0.0 {0}".format(b_l) elif name == "H4": geo_str = "H 0.0 0.0 0.0\nH 0.0 0.0 {0}\nH 0.0 0.0 {1}\nH 0.0 0.0 {2}".format(b_l,-1*b_l,2*b_l) return geo_str
27,934
51.807183
162
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.1/hacked_openfermion_symbolic_operator.py
import abc import copy import itertools import re import warnings import sympy import tequila as tq from tequila.objective.objective import Objective, Variable from openfermion.config import EQ_TOLERANCE COEFFICIENT_TYPES = (int, float, complex, sympy.Expr, Variable, Objective) class SymbolicOperator(metaclass=abc.ABCMeta): """Base class for FermionOperator and QubitOperator. A SymbolicOperator stores an object which represents a weighted sum of terms; each term is a product of individual factors of the form (`index`, `action`), where `index` is a nonnegative integer and the possible values for `action` are determined by the subclass. For instance, for the subclass FermionOperator, `action` can be 1 or 0, indicating raising or lowering, and for QubitOperator, `action` is from the set {'X', 'Y', 'Z'}. The coefficients of the terms are stored in a dictionary whose keys are the terms. SymbolicOperators of the same type can be added or multiplied together. Note: Adding SymbolicOperators is faster using += (as this is done by in-place addition). Specifying the coefficient during initialization is faster than multiplying a SymbolicOperator with a scalar. Attributes: actions (tuple): A tuple of objects representing the possible actions. e.g. for FermionOperator, this is (1, 0). action_strings (tuple): A tuple of string representations of actions. These should be in one-to-one correspondence with actions and listed in the same order. e.g. for FermionOperator, this is ('^', ''). action_before_index (bool): A boolean indicating whether in string representations, the action should come before the index. different_indices_commute (bool): A boolean indicating whether factors acting on different indices commute. terms (dict): **key** (tuple of tuples): A dictionary storing the coefficients of the terms in the operator. The keys are the terms. A term is a product of individual factors; each factor is represented by a tuple of the form (`index`, `action`), and these tuples are collected into a larger tuple which represents the term as the product of its factors. """ @staticmethod def _issmall(val, tol=EQ_TOLERANCE): '''Checks whether a value is near-zero Parses the allowed coefficients above for near-zero tests. Args: val (COEFFICIENT_TYPES) -- the value to be tested tol (float) -- tolerance for inequality ''' if isinstance(val, sympy.Expr): if sympy.simplify(abs(val) < tol) == True: return True return False if isinstance(val, tq.Variable) or isinstance(val, tq.objective.objective.Objective): return False if abs(val) < tol: return True return False @abc.abstractproperty def actions(self): """The allowed actions. Returns a tuple of objects representing the possible actions. """ pass @abc.abstractproperty def action_strings(self): """The string representations of the allowed actions. Returns a tuple containing string representations of the possible actions, in the same order as the `actions` property. """ pass @abc.abstractproperty def action_before_index(self): """Whether action comes before index in string representations. Example: For QubitOperator, the actions are ('X', 'Y', 'Z') and the string representations look something like 'X0 Z2 Y3'. So the action comes before the index, and this function should return True. For FermionOperator, the string representations look like '0^ 1 2^ 3'. The action comes after the index, so this function should return False. """ pass @abc.abstractproperty def different_indices_commute(self): """Whether factors acting on different indices commute.""" pass __hash__ = None def __init__(self, term=None, coefficient=1.): if not isinstance(coefficient, COEFFICIENT_TYPES): raise ValueError('Coefficient must be a numeric type.') # Initialize the terms dictionary self.terms = {} # Detect if the input is the string representation of a sum of terms; # if so, initialization needs to be handled differently if isinstance(term, str) and '[' in term: self._long_string_init(term, coefficient) return # Zero operator: leave the terms dictionary empty if term is None: return # Parse the term # Sequence input if isinstance(term, (list, tuple)): term = self._parse_sequence(term) # String input elif isinstance(term, str): term = self._parse_string(term) # Invalid input type else: raise ValueError('term specified incorrectly.') # Simplify the term coefficient, term = self._simplify(term, coefficient=coefficient) # Add the term to the dictionary self.terms[term] = coefficient def _long_string_init(self, long_string, coefficient): r""" Initialization from a long string representation. e.g. For FermionOperator: '1.5 [2^ 3] + 1.4 [3^ 0]' """ pattern = r'(.*?)\[(.*?)\]' # regex for a term for match in re.findall(pattern, long_string, flags=re.DOTALL): # Determine the coefficient for this term coef_string = re.sub(r"\s+", "", match[0]) if coef_string and coef_string[0] == '+': coef_string = coef_string[1:].strip() if coef_string == '': coef = 1.0 elif coef_string == '-': coef = -1.0 else: try: if 'j' in coef_string: if coef_string[0] == '-': coef = -complex(coef_string[1:]) else: coef = complex(coef_string) else: coef = float(coef_string) except ValueError: raise ValueError( 'Invalid coefficient {}.'.format(coef_string)) coef *= coefficient # Parse the term, simpify it and add to the dict term = self._parse_string(match[1]) coef, term = self._simplify(term, coefficient=coef) if term not in self.terms: self.terms[term] = coef else: self.terms[term] += coef def _validate_factor(self, factor): """Check that a factor of a term is valid.""" if len(factor) != 2: raise ValueError('Invalid factor {}.'.format(factor)) index, action = factor if action not in self.actions: raise ValueError('Invalid action in factor {}. ' 'Valid actions are: {}'.format( factor, self.actions)) if not isinstance(index, int) or index < 0: raise ValueError('Invalid index in factor {}. ' 'The index should be a non-negative ' 'integer.'.format(factor)) def _simplify(self, term, coefficient=1.0): """Simplifies a term.""" if self.different_indices_commute: term = sorted(term, key=lambda factor: factor[0]) return coefficient, tuple(term) def _parse_sequence(self, term): """Parse a term given as a sequence type (i.e., list, tuple, etc.). e.g. For QubitOperator: [('X', 2), ('Y', 0), ('Z', 3)] -> (('Y', 0), ('X', 2), ('Z', 3)) """ if not term: # Empty sequence return () elif isinstance(term[0], int): # Single factor self._validate_factor(term) return (tuple(term),) else: # Check that all factors in the term are valid for factor in term: self._validate_factor(factor) # Return a tuple return tuple(term) def _parse_string(self, term): """Parse a term given as a string. e.g. For FermionOperator: "2^ 3" -> ((2, 1), (3, 0)) """ factors = term.split() # Convert the string representations of the factors to tuples processed_term = [] for factor in factors: # Get the index and action string if self.action_before_index: # The index is at the end of the string; find where it starts. if not factor[-1].isdigit(): raise ValueError('Invalid factor {}.'.format(factor)) index_start = len(factor) - 1 while index_start > 0 and factor[index_start - 1].isdigit(): index_start -= 1 if factor[index_start - 1] == '-': raise ValueError('Invalid index in factor {}. ' 'The index should be a non-negative ' 'integer.'.format(factor)) index = int(factor[index_start:]) action_string = factor[:index_start] else: # The index is at the beginning of the string; find where # it ends if factor[0] == '-': raise ValueError('Invalid index in factor {}. ' 'The index should be a non-negative ' 'integer.'.format(factor)) if not factor[0].isdigit(): raise ValueError('Invalid factor {}.'.format(factor)) index_end = 1 while (index_end <= len(factor) - 1 and factor[index_end].isdigit()): index_end += 1 index = int(factor[:index_end]) action_string = factor[index_end:] # Convert the action string to an action if action_string in self.action_strings: action = self.actions[self.action_strings.index(action_string)] else: raise ValueError('Invalid action in factor {}. ' 'Valid actions are: {}'.format( factor, self.action_strings)) # Add the factor to the list as a tuple processed_term.append((index, action)) # Return a tuple return tuple(processed_term) @property def constant(self): """The value of the constant term.""" return self.terms.get((), 0.0) @constant.setter def constant(self, value): self.terms[()] = value @classmethod def zero(cls): """ Returns: additive_identity (SymbolicOperator): A symbolic operator o with the property that o+x = x+o = x for all operators x of the same class. """ return cls(term=None) @classmethod def identity(cls): """ Returns: multiplicative_identity (SymbolicOperator): A symbolic operator u with the property that u*x = x*u = x for all operators x of the same class. """ return cls(term=()) def __str__(self): """Return an easy-to-read string representation.""" if not self.terms: return '0' string_rep = '' for term, coeff in sorted(self.terms.items()): if self._issmall(coeff): continue tmp_string = '{} ['.format(coeff) for factor in term: index, action = factor action_string = self.action_strings[self.actions.index(action)] if self.action_before_index: tmp_string += '{}{} '.format(action_string, index) else: tmp_string += '{}{} '.format(index, action_string) string_rep += '{}] +\n'.format(tmp_string.strip()) return string_rep[:-3] def __repr__(self): return str(self) def __imul__(self, multiplier): """In-place multiply (*=) with scalar or operator of the same type. Default implementation is to multiply coefficients and concatenate terms. Args: multiplier(complex float, or SymbolicOperator): multiplier Returns: product (SymbolicOperator): Mutated self. """ # Handle scalars. if isinstance(multiplier, COEFFICIENT_TYPES): for term in self.terms: self.terms[term] *= multiplier return self # Handle operator of the same type elif isinstance(multiplier, self.__class__): result_terms = dict() for left_term in self.terms: for right_term in multiplier.terms: left_coefficient = self.terms[left_term] right_coefficient = multiplier.terms[right_term] new_coefficient = left_coefficient * right_coefficient new_term = left_term + right_term new_coefficient, new_term = self._simplify( new_term, coefficient=new_coefficient) # Update result dict. if new_term in result_terms: result_terms[new_term] += new_coefficient else: result_terms[new_term] = new_coefficient self.terms = result_terms return self # Invalid multiplier type else: raise TypeError('Cannot multiply {} with {}'.format( self.__class__.__name__, multiplier.__class__.__name__)) def __mul__(self, multiplier): """Return self * multiplier for a scalar, or a SymbolicOperator. Args: multiplier: A scalar, or a SymbolicOperator. Returns: product (SymbolicOperator) Raises: TypeError: Invalid type cannot be multiply with SymbolicOperator. """ if isinstance(multiplier, COEFFICIENT_TYPES + (type(self),)): product = copy.deepcopy(self) product *= multiplier return product else: raise TypeError('Object of invalid type cannot multiply with ' + type(self) + '.') def __iadd__(self, addend): """In-place method for += addition of SymbolicOperator. Args: addend (SymbolicOperator, or scalar): The operator to add. If scalar, adds to the constant term Returns: sum (SymbolicOperator): Mutated self. Raises: TypeError: Cannot add invalid type. """ if isinstance(addend, type(self)): for term in addend.terms: self.terms[term] = (self.terms.get(term, 0.0) + addend.terms[term]) if self._issmall(self.terms[term]): del self.terms[term] elif isinstance(addend, COEFFICIENT_TYPES): self.constant += addend else: raise TypeError('Cannot add invalid type to {}.'.format(type(self))) return self def __add__(self, addend): """ Args: addend (SymbolicOperator): The operator to add. Returns: sum (SymbolicOperator) """ summand = copy.deepcopy(self) summand += addend return summand def __radd__(self, addend): """ Args: addend (SymbolicOperator): The operator to add. Returns: sum (SymbolicOperator) """ return self + addend def __isub__(self, subtrahend): """In-place method for -= subtraction of SymbolicOperator. Args: subtrahend (A SymbolicOperator, or scalar): The operator to subtract if scalar, subtracts from the constant term. Returns: difference (SymbolicOperator): Mutated self. Raises: TypeError: Cannot subtract invalid type. """ if isinstance(subtrahend, type(self)): for term in subtrahend.terms: self.terms[term] = (self.terms.get(term, 0.0) - subtrahend.terms[term]) if self._issmall(self.terms[term]): del self.terms[term] elif isinstance(subtrahend, COEFFICIENT_TYPES): self.constant -= subtrahend else: raise TypeError('Cannot subtract invalid type from {}.'.format( type(self))) return self def __sub__(self, subtrahend): """ Args: subtrahend (SymbolicOperator): The operator to subtract. Returns: difference (SymbolicOperator) """ minuend = copy.deepcopy(self) minuend -= subtrahend return minuend def __rsub__(self, subtrahend): """ Args: subtrahend (SymbolicOperator): The operator to subtract. Returns: difference (SymbolicOperator) """ return -1 * self + subtrahend def __rmul__(self, multiplier): """ Return multiplier * self for a scalar. We only define __rmul__ for scalars because the left multiply exist for SymbolicOperator and left multiply is also queried as the default behavior. Args: multiplier: A scalar to multiply by. Returns: product: A new instance of SymbolicOperator. Raises: TypeError: Object of invalid type cannot multiply SymbolicOperator. """ if not isinstance(multiplier, COEFFICIENT_TYPES): raise TypeError('Object of invalid type cannot multiply with ' + type(self) + '.') return self * multiplier def __truediv__(self, divisor): """ Return self / divisor for a scalar. Note: This is always floating point division. Args: divisor: A scalar to divide by. Returns: A new instance of SymbolicOperator. Raises: TypeError: Cannot divide local operator by non-scalar type. """ if not isinstance(divisor, COEFFICIENT_TYPES): raise TypeError('Cannot divide ' + type(self) + ' by non-scalar type.') return self * (1.0 / divisor) def __div__(self, divisor): """ For compatibility with Python 2. """ return self.__truediv__(divisor) def __itruediv__(self, divisor): if not isinstance(divisor, COEFFICIENT_TYPES): raise TypeError('Cannot divide ' + type(self) + ' by non-scalar type.') self *= (1.0 / divisor) return self def __idiv__(self, divisor): """ For compatibility with Python 2. """ return self.__itruediv__(divisor) def __neg__(self): """ Returns: negation (SymbolicOperator) """ return -1 * self def __pow__(self, exponent): """Exponentiate the SymbolicOperator. Args: exponent (int): The exponent with which to raise the operator. Returns: exponentiated (SymbolicOperator) Raises: ValueError: Can only raise SymbolicOperator to non-negative integer powers. """ # Handle invalid exponents. if not isinstance(exponent, int) or exponent < 0: raise ValueError( 'exponent must be a non-negative int, but was {} {}'.format( type(exponent), repr(exponent))) # Initialized identity. exponentiated = self.__class__(()) # Handle non-zero exponents. for _ in range(exponent): exponentiated *= self return exponentiated def __eq__(self, other): """Approximate numerical equality (not true equality).""" return self.isclose(other) def __ne__(self, other): return not (self == other) def __iter__(self): self._iter = iter(self.terms.items()) return self def __next__(self): term, coefficient = next(self._iter) return self.__class__(term=term, coefficient=coefficient) def isclose(self, other, tol=EQ_TOLERANCE): """Check if other (SymbolicOperator) is close to self. Comparison is done for each term individually. Return True if the difference between each term in self and other is less than EQ_TOLERANCE Args: other(SymbolicOperator): SymbolicOperator to compare against. """ if not isinstance(self, type(other)): return NotImplemented # terms which are in both: for term in set(self.terms).intersection(set(other.terms)): a = self.terms[term] b = other.terms[term] if not (isinstance(a, sympy.Expr) or isinstance(b, sympy.Expr)): tol *= max(1, abs(a), abs(b)) if self._issmall(a - b, tol) is False: return False # terms only in one (compare to 0.0 so only abs_tol) for term in set(self.terms).symmetric_difference(set(other.terms)): if term in self.terms: if self._issmall(self.terms[term], tol) is False: return False else: if self._issmall(other.terms[term], tol) is False: return False return True def compress(self, abs_tol=EQ_TOLERANCE): """ Eliminates all terms with coefficients close to zero and removes small imaginary and real parts. Args: abs_tol(float): Absolute tolerance, must be at least 0.0 """ new_terms = {} for term in self.terms: coeff = self.terms[term] if isinstance(coeff, sympy.Expr): if sympy.simplify(sympy.im(coeff) <= abs_tol) == True: coeff = sympy.re(coeff) if sympy.simplify(sympy.re(coeff) <= abs_tol) == True: coeff = 1j * sympy.im(coeff) if (sympy.simplify(abs(coeff) <= abs_tol) != True): new_terms[term] = coeff continue if isinstance(val, tq.Variable) or isinstance(val, tq.objective.objective.Objective): continue # Remove small imaginary and real parts if abs(coeff.imag) <= abs_tol: coeff = coeff.real if abs(coeff.real) <= abs_tol: coeff = 1.j * coeff.imag # Add the term if the coefficient is large enough if abs(coeff) > abs_tol: new_terms[term] = coeff self.terms = new_terms def induced_norm(self, order=1): r""" Compute the induced p-norm of the operator. If we represent an operator as :math: `\sum_{j} w_j H_j` where :math: `w_j` are scalar coefficients then this norm is :math: `\left(\sum_{j} \| w_j \|^p \right)^{\frac{1}{p}} where :math: `p` is the order of the induced norm Args: order(int): the order of the induced norm. """ norm = 0. for coefficient in self.terms.values(): norm += abs(coefficient)**order return norm**(1. / order) def many_body_order(self): """Compute the many-body order of a SymbolicOperator. The many-body order of a SymbolicOperator is the maximum length of a term with nonzero coefficient. Returns: int """ if not self.terms: # Zero operator return 0 else: return max( len(term) for term, coeff in self.terms.items() if (self._issmall(coeff) is False)) @classmethod def accumulate(cls, operators, start=None): """Sums over SymbolicOperators.""" total = copy.deepcopy(start or cls.zero()) for operator in operators: total += operator return total def get_operators(self): """Gets a list of operators with a single term. Returns: operators([self.__class__]): A generator of the operators in self. """ for term, coefficient in self.terms.items(): yield self.__class__(term, coefficient) def get_operator_groups(self, num_groups): """Gets a list of operators with a few terms. Args: num_groups(int): How many operators to get in the end. Returns: operators([self.__class__]): A list of operators summing up to self. """ if num_groups < 1: warnings.warn('Invalid num_groups {} < 1.'.format(num_groups), RuntimeWarning) num_groups = 1 operators = self.get_operators() num_groups = min(num_groups, len(self.terms)) for i in range(num_groups): yield self.accumulate( itertools.islice(operators, len(range(i, len(self.terms), num_groups))))
25,797
35.697013
97
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_0.6/main.py
import tequila as tq import numpy as np from tequila.objective.objective import Variable import openfermion from typing import Union from vqe_utils import convert_PQH_to_tq_QH, convert_tq_QH_to_PQH,\ fold_unitary_into_hamiltonian from energy_optimization import * from do_annealing import * import random # guess we could substitute that with numpy.random #TODO import argparse import pickle as pk import matplotlib.pyplot as plt # Main hyperparameters mu = 2.0 # lognormal dist mean sigma = 0.4 # lognormal dist std T_0 = 1.0 # T_0, initial starting temperature # max_epochs = 25 # num_epochs, max number of iterations max_epochs = 20 # num_epochs, max number of iterations min_epochs = 2 # num_epochs, max number of iterations5 # min_epochs = 20 # num_epochs, max number of iterations tol = 1e-6 # minimum change in energy required, otherwise terminate optimization actions_ratio = [.15, .6, .25] patience = 100 beta = 0.5 max_non_cliffords = 0 type_energy_eval='wfn' num_population = 24 num_offsprings = 20 num_processors = 8 #tuning, input as lists. # parser.add_argument('--alphas', type = float, nargs = '+', help='alpha, temperature decay', required=True) alphas = [0.9] # alpha, temperature decay' #Required be = False h2 = True n2 = False name_prefix = '../../data/' # Construct qubit-Hamiltonian #num_active = 3 #active_orbitals = list(range(num_active)) if be: R1 = rrrr R2 = 0.6 geometry = "be 0.0 0.0 0.0\nh 0.0 0.0 {R1}\nh 0.0 0.0 -{R2}" name = "/h/292/philipps/software/moldata/beh2/beh2_{R1:2.2f}_{R2:2.2f}_180" # adapt of you move data mol = tq.Molecule(name=name.format(R1=R1, R2=R2), geometry=geometry.format(R1=R1,R2=R2), n_pno=None) lqm = mol.local_qubit_map(hcb=False) H = mol.make_hamiltonian().map_qubits(lqm).simplify() #print("FCI ENERGY: ", mol.compute_energy(method="fci")) U_spa = mol.make_upccgsd_ansatz(name="SPA").map_qubits(lqm) U = U_spa elif n2: R1 = rrrr geometry = "N 0.0 0.0 0.0\nN 0.0 0.0 {R1}" # name = "/home/abhinav/matter_lab/moldata/n2/n2_{R1:2.2f}" # adapt of you move data name = "/h/292/philipps/software/moldata/n2/n2_{R1:2.2f}" # adapt of you move data mol = tq.Molecule(name=name.format(R1=R1), geometry=geometry.format(R1=R1), n_pno=None) lqm = mol.local_qubit_map(hcb=False) H = mol.make_hamiltonian().map_qubits(lqm).simplify() # print("FCI ENERGY: ", mol.compute_energy(method="fci")) print("Skip FCI calculation, take old data...") U_spa = mol.make_upccgsd_ansatz(name="SPA").map_qubits(lqm) U = U_spa elif h2: active_orbitals = list(range(3)) mol = tq.Molecule(geometry='H 0.0 0.0 0.0\n H 0.0 0.0 0.6', basis_set='6-31g', active_orbitals=active_orbitals, backend='psi4') H = mol.make_hamiltonian().simplify() print("FCI ENERGY: ", mol.compute_energy(method="fci")) U = mol.make_uccsd_ansatz(trotter_steps=1) # Alternatively, get qubit-Hamiltonian from openfermion/externally # with open("ham_6qubits.txt") as hamstring_file: """if be: with open("ham_beh2_3_3.txt") as hamstring_file: hamstring = hamstring_file.read() #print(hamstring) H = tq.QubitHamiltonian().from_string(string=hamstring, openfermion_format=True) elif h2: with open("ham_6qubits.txt") as hamstring_file: hamstring = hamstring_file.read() #print(hamstring) H = tq.QubitHamiltonian().from_string(string=hamstring, openfermion_format=True)""" n_qubits = len(H.qubits) ''' Option 'wfn': "Shortcut" via wavefunction-optimization using MPO-rep of Hamiltonian Option 'qc': Need to input a proper quantum circuit ''' # Clifford optimization in the context of reduced-size quantum circuits starting_E = 123.456 reference = True if reference: if type_energy_eval.lower() == 'wfn': starting_E, _ = minimize_energy(hamiltonian=H, n_qubits=n_qubits, type_energy_eval='wfn') print('starting energy wfn: {:.5f}'.format(starting_E), flush=True) elif type_energy_eval.lower() == 'qc': starting_E, _ = minimize_energy(hamiltonian=H, n_qubits=n_qubits, type_energy_eval='qc', cluster_circuit=U) print('starting energy spa: {:.5f}'.format(starting_E)) else: raise Exception("type_energy_eval must be either 'wfn' or 'qc', but is", type_energy_eval) starting_E, _ = minimize_energy(hamiltonian=H, n_qubits=n_qubits, type_energy_eval='wfn') """for alpha in alphas: print('Starting optimization, alpha = {:3f}'.format(alpha)) # print('Energy to beat', minimize_energy(H, n_qubits, 'wfn')[0]) simulated_annealing(hamiltonian=H, num_population=num_population, num_offsprings=num_offsprings, num_processors=num_processors, tol=tol, max_epochs=max_epochs, min_epochs=min_epochs, T_0=T_0, alpha=alpha, actions_ratio=actions_ratio, max_non_cliffords=max_non_cliffords, verbose=True, patience=patience, beta=beta, type_energy_eval=type_energy_eval.lower(), cluster_circuit=U, starting_energy=starting_E)""" alter_cliffords = True if alter_cliffords: print("starting to replace cliffords with non-clifford gates to see if that improves the current fitness") replace_cliff_with_non_cliff(hamiltonian=H, num_population=num_population, num_offsprings=num_offsprings, num_processors=num_processors, tol=tol, max_epochs=max_epochs, min_epochs=min_epochs, T_0=T_0, alpha=alphas[0], actions_ratio=actions_ratio, max_non_cliffords=max_non_cliffords, verbose=True, patience=patience, beta=beta, type_energy_eval=type_energy_eval.lower(), cluster_circuit=U, starting_energy=starting_E) # accepted_E, tested_E, decisions, instructions_list, best_instructions, temp, best_E = simulated_annealing(hamiltonian=H, # population=4, # num_mutations=2, # num_processors=1, # tol=opt.tol, max_epochs=opt.max_epochs, # min_epochs=opt.min_epochs, T_0=opt.T_0, alpha=alpha, # mu=opt.mu, sigma=opt.sigma, verbose=True, prev_E = starting_E, patience = 10, beta = 0.5, # energy_eval='qc', # eval_circuit=U # print(best_E) # print(best_instructions) # print(len(accepted_E)) # plt.plot(accepted_E) # plt.show() # #pickling data # data = {'accepted_energies': accepted_E, 'tested_energies': tested_E, # 'decisions': decisions, 'instructions': instructions_list, # 'best_instructions': best_instructions, 'temperature': temp, # 'best_energy': best_E} # f_name = '{}{}_alpha_{:.2f}.pk'.format(opt.name_prefix, r, alpha) # pk.dump(data, open(f_name, 'wb')) # print('Finished optimization, data saved in {}'.format(f_name))
7,368
40.869318
129
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_0.6/my_mpo.py
import numpy as np import tensornetwork as tn from tensornetwork.backends.abstract_backend import AbstractBackend tn.set_default_backend("pytorch") #tn.set_default_backend("numpy") from typing import List, Union, Text, Optional, Any, Type Tensor = Any import tequila as tq import torch EPS = 1e-12 class SubOperator: """ This is just a helper class to store coefficient, operators and positions in an intermediate format """ def __init__(self, coefficient: float, operators: List, positions: List ): self._coefficient = coefficient self._operators = operators self._positions = positions @property def coefficient(self): return self._coefficient @property def operators(self): return self._operators @property def positions(self): return self._positions class MPOContainer: """ Class that handles the MPO. Is able to set values at certain positions, update containers (wannabe-equivalent to dynamic arrays) and compress the MPO """ def __init__(self, n_qubits: int, ): self.n_qubits = n_qubits self.container = [ np.zeros((1,1,2,2), dtype=np.complex) for q in range(self.n_qubits) ] def get_dim(self): """ Returns max dimension of container """ d = 1 for q in range(len(self.container)): d = max(d, self.container[q].shape[0]) return d def set_tensor(self, qubit: int, set_at: list, add_operator: Union[np.ndarray, float]): """ set_at: where to put data """ # Set a matrix if len(set_at) == 2: self.container[qubit][set_at[0],set_at[1],:,:] = add_operator[:,:] # Set specific values elif len(set_at) == 4: self.container[qubit][set_at[0],set_at[1],set_at[2],set_at[3]] =\ add_operator else: raise Exception("set_at needs to be either of length 2 or 4") def update_container(self, qubit: int, update_dir: list, add_operator: np.ndarray): """ This should mimick a dynamic array update_dir: e.g. [1,1,0,0] -> extend dimension along where there's a 1 the last two dimensions are always 2x2 only """ old_shape = self.container[qubit].shape # print(old_shape) if not len(update_dir) == 4: if len(update_dir) == 2: update_dir += [0, 0] else: raise Exception("update_dir needs to be either of length 2 or 4") if update_dir[2] or update_dir[3]: raise Exception("Last two dims must be zero.") new_shape = tuple(update_dir[i]+old_shape[i] for i in range(len(update_dir))) new_tensor = np.zeros(new_shape, dtype=np.complex) # Copy old values new_tensor[:old_shape[0],:old_shape[1],:,:] = self.container[qubit][:,:,:,:] # Add new values new_tensor[new_shape[0]-1,new_shape[1]-1,:,:] = add_operator[:,:] # Overwrite container self.container[qubit] = new_tensor def compress_mpo(self): """ Compression of MPO via SVD """ n_qubits = len(self.container) for q in range(n_qubits): my_shape = self.container[q].shape self.container[q] =\ self.container[q].reshape((my_shape[0], my_shape[1], -1)) # Go forwards for q in range(n_qubits-1): # Apply permutation [0 1 2] -> [0 2 1] my_tensor = np.swapaxes(self.container[q], 1, 2) my_tensor = my_tensor.reshape((-1, my_tensor.shape[2])) # full_matrices flag corresponds to 'econ' -> no zero-singular values u, s, vh = np.linalg.svd(my_tensor, full_matrices=False) # Count the non-zero singular values num_nonzeros = len(np.argwhere(s>EPS)) # Construct matrix from square root of singular values s = np.diag(np.sqrt(s[:num_nonzeros])) u = u[:,:num_nonzeros] vh = vh[:num_nonzeros,:] # Distribute weights to left- and right singular vectors (@ = np.matmul) u = u @ s vh = s @ vh # Apply permutation [0 1 2] -> [0 2 1] u = u.reshape((self.container[q].shape[0],\ self.container[q].shape[2], -1)) self.container[q] = np.swapaxes(u, 1, 2) self.container[q+1] = tn.ncon([vh, self.container[q+1]], [(-1, 1),(1, -2, -3)]) # Go backwards for q in range(n_qubits-1, 0, -1): my_tensor = self.container[q] my_tensor = my_tensor.reshape((self.container[q].shape[0], -1)) # full_matrices flag corresponds to 'econ' -> no zero-singular values u, s, vh = np.linalg.svd(my_tensor, full_matrices=False) # Count the non-zero singular values num_nonzeros = len(np.argwhere(s>EPS)) # Construct matrix from square root of singular values s = np.diag(np.sqrt(s[:num_nonzeros])) u = u[:,:num_nonzeros] vh = vh[:num_nonzeros,:] # Distribute weights to left- and right singular vectors u = u @ s vh = s @ vh self.container[q] = np.reshape(vh, (num_nonzeros, self.container[q].shape[1], self.container[q].shape[2])) self.container[q-1] = tn.ncon([self.container[q-1], u], [(-1, 1, -3),(1, -2)]) for q in range(n_qubits): my_shape = self.container[q].shape self.container[q] = self.container[q].reshape((my_shape[0],\ my_shape[1],2,2)) # TODO maybe make subclass of tn.FiniteMPO if it makes sense #class my_MPO(tn.FiniteMPO): class MyMPO: """ Class building up on tensornetwork FiniteMPO to handle MPO-Hamiltonians """ def __init__(self, hamiltonian: Union[tq.QubitHamiltonian, Text], # tensors: List[Tensor], backend: Optional[Union[AbstractBackend, Text]] = None, n_qubits: Optional[int] = None, name: Optional[Text] = None, maxdim: Optional[int] = 10000) -> None: # TODO: modifiy docstring """ Initialize a finite MPO object Args: tensors: The mpo tensors. backend: An optional backend. Defaults to the defaulf backend of TensorNetwork. name: An optional name for the MPO. """ self.hamiltonian = hamiltonian self.maxdim = maxdim if n_qubits: self._n_qubits = n_qubits else: self._n_qubits = self.get_n_qubits() @property def n_qubits(self): return self._n_qubits def make_mpo_from_hamiltonian(self): intermediate = self.openfermion_to_intermediate() # for i in range(len(intermediate)): # print(intermediate[i].coefficient) # print(intermediate[i].operators) # print(intermediate[i].positions) self.mpo = self.intermediate_to_mpo(intermediate) def openfermion_to_intermediate(self): # Here, have either a QubitHamiltonian or a file with a of-operator # Start with Qubithamiltonian def get_pauli_matrix(string): pauli_matrices = { 'I': np.array([[1, 0], [0, 1]], dtype=np.complex), 'Z': np.array([[1, 0], [0, -1]], dtype=np.complex), 'X': np.array([[0, 1], [1, 0]], dtype=np.complex), 'Y': np.array([[0, -1j], [1j, 0]], dtype=np.complex) } return pauli_matrices[string.upper()] intermediate = [] first = True # Store all paulistrings in intermediate format for paulistring in self.hamiltonian.paulistrings: coefficient = paulistring.coeff # print(coefficient) operators = [] positions = [] # Only first one should be identity -> distribute over all if first and not paulistring.items(): positions += [] operators += [] first = False elif not first and not paulistring.items(): raise Exception("Only first Pauli should be identity.") # Get operators and where they act for k,v in paulistring.items(): positions += [k] operators += [get_pauli_matrix(v)] tmp_op = SubOperator(coefficient=coefficient, operators=operators, positions=positions) intermediate += [tmp_op] # print("len intermediate = num Pauli strings", len(intermediate)) return intermediate def build_single_mpo(self, intermediate, j): # Set MPO Container n_qubits = self._n_qubits mpo = MPOContainer(n_qubits=n_qubits) # *********************************************************************** # Set first entries (of which we know that they are 2x2-matrices) # Typically, this is an identity my_coefficient = intermediate[j].coefficient my_positions = intermediate[j].positions my_operators = intermediate[j].operators for q in range(n_qubits): if not q in my_positions: mpo.set_tensor(qubit=q, set_at=[0,0], add_operator=np.complex(my_coefficient)**(1/n_qubits)* np.eye(2)) elif q in my_positions: my_pos_index = my_positions.index(q) mpo.set_tensor(qubit=q, set_at=[0,0], add_operator=np.complex(my_coefficient)**(1/n_qubits)* my_operators[my_pos_index]) # *********************************************************************** # All other entries # while (j smaller than number of intermediates left) and mpo.dim() <= self.maxdim # Re-write this based on positions keyword! j += 1 while j < len(intermediate) and mpo.get_dim() < self.maxdim: # """ my_coefficient = intermediate[j].coefficient my_positions = intermediate[j].positions my_operators = intermediate[j].operators for q in range(n_qubits): # It is guaranteed that every index appears only once in positions if q == 0: update_dir = [0,1] elif q == n_qubits-1: update_dir = [1,0] else: update_dir = [1,1] # If there's an operator on my position, add that if q in my_positions: my_pos_index = my_positions.index(q) mpo.update_container(qubit=q, update_dir=update_dir, add_operator= np.complex(my_coefficient)**(1/n_qubits)* my_operators[my_pos_index]) # Else add an identity else: mpo.update_container(qubit=q, update_dir=update_dir, add_operator= np.complex(my_coefficient)**(1/n_qubits)* np.eye(2)) if not j % 100: mpo.compress_mpo() #print("\t\tAt iteration ", j, " MPO has dimension ", mpo.get_dim()) j += 1 mpo.compress_mpo() #print("\tAt final iteration ", j-1, " MPO has dimension ", mpo.get_dim()) return mpo, j def intermediate_to_mpo(self, intermediate): n_qubits = self._n_qubits # TODO Change to multiple MPOs mpo_list = [] j_global = 0 num_mpos = 0 # Start with 0, then final one is correct while j_global < len(intermediate): current_mpo, j_global = self.build_single_mpo(intermediate, j_global) mpo_list += [current_mpo] num_mpos += 1 return mpo_list def construct_matrix(self): # TODO extend to lists of MPOs ''' Recover matrix, e.g. to compare with Hamiltonian that we get from tq ''' mpo = self.mpo # Contract over all bond indices # mpo.container has indices [bond, bond, physical, physical] n_qubits = self._n_qubits d = int(2**(n_qubits/2)) first = True H = None #H = np.zeros((d,d,d,d), dtype='complex') # Define network nodes # | | | | # -O--O--...--O--O- # | | | | for m in mpo: assert(n_qubits == len(m.container)) nodes = [tn.Node(m.container[q], name=str(q)) for q in range(n_qubits)] # Connect network (along double -- above) for q in range(n_qubits-1): nodes[q][1] ^ nodes[q+1][0] # Collect dangling edges (free indices) edges = [] # Left dangling edge edges += [nodes[0].get_edge(0)] # Right dangling edge edges += [nodes[-1].get_edge(1)] # Upper dangling edges for q in range(n_qubits): edges += [nodes[q].get_edge(2)] # Lower dangling edges for q in range(n_qubits): edges += [nodes[q].get_edge(3)] # Contract between all nodes along non-dangling edges res = tn.contractors.auto(nodes, output_edge_order=edges) # Reshape to get tensor of order 4 (get rid of left- and right open indices # and combine top&bottom into one) if isinstance(res.tensor, torch.Tensor): H_m = res.tensor.numpy() if not first: H += H_m else: H = H_m first = False return H.reshape((d,d,d,d))
14,354
36.480418
99
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_0.6/do_annealing.py
import tequila as tq import numpy as np import pickle from pathos.multiprocessing import ProcessingPool as Pool from parallel_annealing import * #from dummy_par import * from mutation_options import * from single_thread_annealing import * def find_best_instructions(instructions_dict): """ This function finds the instruction with the best fitness args: instructions_dict: A dictionary with the "Instructions" objects the corresponding fitness values as values """ best_instructions = None best_fitness = 10000000 for key in instructions_dict: if instructions_dict[key][1] <= best_fitness: best_instructions = instructions_dict[key][0] best_fitness = instructions_dict[key][1] return best_instructions, best_fitness def simulated_annealing(num_population, num_offsprings, actions_ratio, hamiltonian, max_epochs=100, min_epochs=1, tol=1e-6, type_energy_eval="wfn", cluster_circuit=None, patience = 20, num_processors=4, T_0=1.0, alpha=0.9, max_non_cliffords=0, verbose=False, beta=0.5, starting_energy=None): """ this function tries to find the clifford circuit that best lowers the energy of the hamiltonian using simulated annealing. params: - num_population = number of members in a generation - num_offsprings = number of mutations carried on every member - num_processors = number of processors to use for parallelization - T_0 = initial temperature - alpha = temperature decay - beta = parameter to adjust temperature on resetting after running out of patience - max_epochs = max iterations for optimizing - min_epochs = min iterations for optimizing - tol = minimum change in energy required, otherwise terminate optimization - verbose = display energies/decisions at iterations of not - hamiltonian = original hamiltonian - actions_ratio = The ratio of the different actions for mutations - type_energy_eval = keyword specifying the type of optimization method to use for energy minimization - cluster_circuit = the reference circuit to which clifford gates are added - patience = the number of epochs before resetting the optimization """ if verbose: print("Starting to Optimize Cluster circuit", flush=True) num_qubits = len(hamiltonian.qubits) if verbose: print("Initializing Generation", flush=True) # restart = False if previous_instructions is None\ # else True restart = False instructions_dict = {} instructions_list = [] current_fitness_list = [] fitness, wfn = None, None # pre-initialize with None for instruction_id in range(num_population): instructions = None if restart: try: instructions = Instructions(n_qubits=num_qubits, alpha=alpha, T_0=T_0, beta=beta, patience=patience, max_non_cliffords=max_non_cliffords, reference_energy=starting_energy) instructions.gates = pickle.load(open("instruct_gates.pickle", "rb")) instructions.positions = pickle.load(open("instruct_positions.pickle", "rb")) instructions.best_reference_wfn = pickle.load(open("best_reference_wfn.pickle", "rb")) print("Added a guess from previous runs", flush=True) fitness, wfn = evaluate_fitness(instructions=instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) except Exception as e: print(e) raise Exception("Did not find a guess from previous runs") # pass restart = False #print(instructions._str()) else: failed = True while failed: instructions = Instructions(n_qubits=num_qubits, alpha=alpha, T_0=T_0, beta=beta, patience=patience, max_non_cliffords=max_non_cliffords, reference_energy=starting_energy) instructions.prune() fitness, wfn = evaluate_fitness(instructions=instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) # if fitness <= starting_energy: failed = False instructions.set_reference_wfn(wfn) current_fitness_list.append(fitness) instructions_list.append(instructions) instructions_dict[instruction_id] = (instructions, fitness) if verbose: print("First Generation details: \n", flush=True) for key in instructions_dict: print("Initial Instructions number: ", key, flush=True) instructions_dict[key][0]._str() print("Initial fitness values: ", instructions_dict[key][1], flush=True) best_instructions, best_energy = find_best_instructions(instructions_dict) if verbose: print("Best member of the Generation: \n", flush=True) print("Instructions: ", flush=True) best_instructions._str() print("fitness value: ", best_energy, flush=True) pickle.dump(best_instructions.gates, open("instruct_gates.pickle", "wb")) pickle.dump(best_instructions.positions, open("instruct_positions.pickle", "wb")) pickle.dump(best_instructions.best_reference_wfn, open("best_reference_wfn.pickle", "wb")) epoch = 0 previous_best_energy = best_energy converged = False has_improved_before = False dts = [] #pool = multiprocessing.Pool(processes=num_processors) while (epoch < max_epochs): print("Epoch: ", epoch, flush=True) import time t0 = time.time() if num_processors == 1: st_evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, type_energy_eval, cluster_circuit) else: evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, num_processors, type_energy_eval, cluster_circuit) t1 = time.time() dts += [t1-t0] best_instructions, best_energy = find_best_instructions(instructions_dict) if verbose: print("Best member of the Generation: \n", flush=True) print("Instructions: ", flush=True) best_instructions._str() print("fitness value: ", best_energy, flush=True) # A bit confusing, but: # Want that current best energy has improved something previous, is better than # some starting energy and achieves some convergence criterion has_improved_before = True if np.abs(best_energy - previous_best_energy) < 0\ else False if np.abs(best_energy - previous_best_energy) < tol and has_improved_before: if starting_energy is not None: converged = True if best_energy < starting_energy else False else: converged = True else: converged = False if best_energy < previous_best_energy: previous_best_energy = best_energy epoch += 1 pickle.dump(best_instructions.gates, open("instruct_gates.pickle", "wb")) pickle.dump(best_instructions.positions, open("instruct_positions.pickle", "wb")) pickle.dump(best_instructions.best_reference_wfn, open("best_reference_wfn.pickle", "wb")) #pool.close() if converged: print("Converged after ", epoch, " iterations.", flush=True) print("Best energy:", best_energy, flush=True) print("\t with instructions", best_instructions.gates, best_instructions.positions, flush=True) print("\t optimal parameters", best_instructions.best_reference_wfn, flush=True) print("average time: ", np.average(dts), flush=True) print("overall time: ", np.sum(dts), flush=True) # best_instructions.replace_UCCXc_with_UCC(number=max_non_cliffords) pickle.dump(best_instructions.gates, open("instruct_gates.pickle", "wb")) pickle.dump(best_instructions.positions, open("instruct_positions.pickle", "wb")) pickle.dump(best_instructions.best_reference_wfn, open("best_reference_wfn.pickle", "wb")) def replace_cliff_with_non_cliff(num_population, num_offsprings, actions_ratio, hamiltonian, max_epochs=100, min_epochs=1, tol=1e-6, type_energy_eval="wfn", cluster_circuit=None, patience = 20, num_processors=4, T_0=1.0, alpha=0.9, max_non_cliffords=0, verbose=False, beta=0.5, starting_energy=None): """ this function tries to find the clifford circuit that best lowers the energy of the hamiltonian using simulated annealing. params: - num_population = number of members in a generation - num_offsprings = number of mutations carried on every member - num_processors = number of processors to use for parallelization - T_0 = initial temperature - alpha = temperature decay - beta = parameter to adjust temperature on resetting after running out of patience - max_epochs = max iterations for optimizing - min_epochs = min iterations for optimizing - tol = minimum change in energy required, otherwise terminate optimization - verbose = display energies/decisions at iterations of not - hamiltonian = original hamiltonian - actions_ratio = The ratio of the different actions for mutations - type_energy_eval = keyword specifying the type of optimization method to use for energy minimization - cluster_circuit = the reference circuit to which clifford gates are added - patience = the number of epochs before resetting the optimization """ if verbose: print("Starting to replace clifford gates Cluster circuit with non-clifford gates one at a time", flush=True) num_qubits = len(hamiltonian.qubits) #get the best clifford object instructions = Instructions(n_qubits=num_qubits, alpha=alpha, T_0=T_0, beta=beta, patience=patience, max_non_cliffords=max_non_cliffords, reference_energy=starting_energy) instructions.gates = pickle.load(open("instruct_gates.pickle", "rb")) instructions.positions = pickle.load(open("instruct_positions.pickle", "rb")) instructions.best_reference_wfn = pickle.load(open("best_reference_wfn.pickle", "rb")) fitness, wfn = evaluate_fitness(instructions=instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) if verbose: print("Initial energy after previous Clifford optimization is",\ fitness, flush=True) print("Starting with instructions", instructions.gates, instructions.positions, flush=True) instructions_dict = {} instructions_dict[0] = (instructions, fitness) for gate_id, (gate, position) in enumerate(zip(instructions.gates, instructions.positions)): print(gate) altered_instructions = copy.deepcopy(instructions) # skip if controlled rotation if gate[0]=='C': continue altered_instructions.replace_cg_w_ncg(gate_id) # altered_instructions.max_non_cliffords = 1 # TODO why is this set to 1?? altered_instructions.max_non_cliffords = max_non_cliffords #clifford_circuit, init_angles = build_circuit(instructions) #print(clifford_circuit, init_angles) #folded_hamiltonian = perform_folding(hamiltonian, clifford_circuit) #folded_hamiltonian2 = (convert_PQH_to_tq_QH(folded_hamiltonian))() #print(folded_hamiltonian) #clifford_circuit, init_angles = build_circuit(altered_instructions) #print(clifford_circuit, init_angles) #folded_hamiltonian = perform_folding(hamiltonian, clifford_circuit) #folded_hamiltonian1 = (convert_PQH_to_tq_QH(folded_hamiltonian))(init_angles) #print(folded_hamiltonian1 - folded_hamiltonian2) #print(folded_hamiltonian) #raise Exception("teste") counter = 0 success = False while not success: counter += 1 try: fitness, wfn = evaluate_fitness(instructions=altered_instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) success = True except Exception as e: print(e) if counter > 5: print("This replacement failed more than 5 times") success = True instructions_dict[gate_id+1] = (altered_instructions, fitness) #circuit = build_circuit(altered_instructions) #tq.draw(circuit,backend="cirq") best_instructions, best_energy = find_best_instructions(instructions_dict) print("best instrucitons after the non-clifford opimizaton") print("Best energy:", best_energy, flush=True) print("\t with instructions", best_instructions.gates, best_instructions.positions, flush=True)
13,155
46.154122
187
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_0.6/scipy_optimizer.py
import numpy, copy, scipy, typing, numbers from tequila import BitString, BitNumbering, BitStringLSB from tequila.utils.keymap import KeyMapRegisterToSubregister from tequila.circuit.compiler import change_basis from tequila.utils import to_float import tequila as tq from tequila.objective import Objective from tequila.optimizers.optimizer_scipy import OptimizerSciPy, SciPyResults from tequila.objective.objective import assign_variable, Variable, format_variable_dictionary, format_variable_list from tequila.circuit.noise import NoiseModel #from tequila.optimizers._containers import _EvalContainer, _GradContainer, _HessContainer, _QngContainer from vqe_utils import * class _EvalContainer: """ Overwrite the call function Container Class to access scipy and keep the optimization history. This class is used by the SciPy optimizer and should not be used elsewhere. Attributes --------- objective: the objective to evaluate. param_keys: the dictionary mapping parameter keys to positions in a numpy array. samples: the number of samples to evaluate objective with. save_history: whether or not to save, in a history, information about each time __call__ occurs. print_level dictates the verbosity of printing during call. N: the length of param_keys. history: if save_history, a list of energies received from every __call__ history_angles: if save_history, a list of angles sent to __call__. """ def __init__(self, Hamiltonian, unitary, param_keys, Ham_derivatives= None, Eval=None, passive_angles=None, samples=1024, save_history=True, print_level: int = 3): self.Hamiltonian = Hamiltonian self.unitary = unitary self.samples = samples self.param_keys = param_keys self.N = len(param_keys) self.save_history = save_history self.print_level = print_level self.passive_angles = passive_angles self.Eval = Eval self.infostring = None self.Ham_derivatives = Ham_derivatives if save_history: self.history = [] self.history_angles = [] def __call__(self, p, *args, **kwargs): """ call a wrapped objective. Parameters ---------- p: numpy array: Parameters with which to call the objective. args kwargs Returns ------- numpy.array: value of self.objective with p translated into variables, as a numpy array. """ angles = {}#dict((self.param_keys[i], p[i]) for i in range(self.N)) for i in range(self.N): if self.param_keys[i] in self.unitary.extract_variables(): angles[self.param_keys[i]] = p[i] else: angles[self.param_keys[i]] = complex(p[i]) if self.passive_angles is not None: angles = {**angles, **self.passive_angles} vars = format_variable_dictionary(angles) Hamiltonian = self.Hamiltonian(vars) #print(Hamiltonian) #print(self.unitary) #print(vars) Expval = tq.ExpectationValue(H=Hamiltonian, U=self.unitary) #print(Expval) E = tq.simulate(Expval, vars, backend='qulacs', samples=self.samples) self.infostring = "{:15} : {} expectationvalues\n".format("Objective", Expval.count_expectationvalues()) if self.print_level > 2: print("E={:+2.8f}".format(E), " angles=", angles, " samples=", self.samples) elif self.print_level > 1: print("E={:+2.8f}".format(E)) if self.save_history: self.history.append(E) self.history_angles.append(angles) return complex(E) # jax types confuses optimizers class _GradContainer(_EvalContainer): """ Overwrite the call function Container Class to access scipy and keep the optimization history. This class is used by the SciPy optimizer and should not be used elsewhere. see _EvalContainer for details. """ def __call__(self, p, *args, **kwargs): """ call the wrapped qng. Parameters ---------- p: numpy array: Parameters with which to call gradient args kwargs Returns ------- numpy.array: value of self.objective with p translated into variables, as a numpy array. """ Ham_derivatives = self.Ham_derivatives Hamiltonian = self.Hamiltonian unitary = self.unitary dE_vec = numpy.zeros(self.N) memory = dict() #variables = dict((self.param_keys[i], p[i]) for i in range(len(self.param_keys))) variables = {}#dict((self.param_keys[i], p[i]) for i in range(self.N)) for i in range(len(self.param_keys)): if self.param_keys[i] in self.unitary.extract_variables(): variables[self.param_keys[i]] = p[i] else: variables[self.param_keys[i]] = complex(p[i]) if self.passive_angles is not None: variables = {**variables, **self.passive_angles} vars = format_variable_dictionary(variables) expvals = 0 for i in range(self.N): derivative = 0.0 if self.param_keys[i] in list(unitary.extract_variables()): Ham = Hamiltonian(vars) Expval = tq.ExpectationValue(H=Ham, U=unitary) temp_derivative = tq.compile(objective = tq.grad(objective = Expval, variable = self.param_keys[i]),backend='qulacs') expvals += temp_derivative.count_expectationvalues() derivative += temp_derivative if self.param_keys[i] in list(Ham_derivatives.keys()): #print(self.param_keys[i]) Ham = Ham_derivatives[self.param_keys[i]] Ham = convert_PQH_to_tq_QH(Ham) H = Ham(vars) #print(H) #raise Exception("testing") Expval = tq.ExpectationValue(H=H, U=unitary) expvals += Expval.count_expectationvalues() derivative += tq.simulate(Expval, vars, backend='qulacs', samples=self.samples) #print(derivative) #print(type(H)) if isinstance(derivative, float) or isinstance(derivative, numpy.complex64) : dE_vec[i] = derivative else: dE_vec[i] = derivative(variables=variables, samples=self.samples) memory[self.param_keys[i]] = dE_vec[i] self.infostring = "{:15} : {} expectationvalues\n".format("gradient", expvals) self.history.append(memory) return numpy.asarray(dE_vec, dtype=numpy.complex64) class optimize_scipy(OptimizerSciPy): """ overwrite the expectation and gradient container objects """ def initialize_variables(self, all_variables, initial_values, variables): """ Convenience function to format the variables of some objective recieved in calls to optimzers. Parameters ---------- objective: Objective: the objective being optimized. initial_values: dict or string: initial values for the variables of objective, as a dictionary. if string: can be `zero` or `random` if callable: custom function that initializes when keys are passed if None: random initialization between 0 and 2pi (not recommended) variables: list: the variables being optimized over. Returns ------- tuple: active_angles, a dict of those variables being optimized. passive_angles, a dict of those variables NOT being optimized. variables: formatted list of the variables being optimized. """ # bring into right format variables = format_variable_list(variables) initial_values = format_variable_dictionary(initial_values) all_variables = all_variables if variables is None: variables = all_variables if initial_values is None: initial_values = {k: numpy.random.uniform(0, 2 * numpy.pi) for k in all_variables} elif hasattr(initial_values, "lower"): if initial_values.lower() == "zero": initial_values = {k:0.0 for k in all_variables} elif initial_values.lower() == "random": initial_values = {k: numpy.random.uniform(0, 2 * numpy.pi) for k in all_variables} else: raise TequilaOptimizerException("unknown initialization instruction: {}".format(initial_values)) elif callable(initial_values): initial_values = {k: initial_values(k) for k in all_variables} elif isinstance(initial_values, numbers.Number): initial_values = {k: initial_values for k in all_variables} else: # autocomplete initial values, warn if you did detected = False for k in all_variables: if k not in initial_values: initial_values[k] = 0.0 detected = True if detected and not self.silent: warnings.warn("initial_variables given but not complete: Autocompleted with zeroes", TequilaWarning) active_angles = {} for v in variables: active_angles[v] = initial_values[v] passive_angles = {} for k, v in initial_values.items(): if k not in active_angles.keys(): passive_angles[k] = v return active_angles, passive_angles, variables def __call__(self, Hamiltonian, unitary, variables: typing.List[Variable] = None, initial_values: typing.Dict[Variable, numbers.Real] = None, gradient: typing.Dict[Variable, Objective] = None, hessian: typing.Dict[typing.Tuple[Variable, Variable], Objective] = None, reset_history: bool = True, *args, **kwargs) -> SciPyResults: """ Perform optimization using scipy optimizers. Parameters ---------- objective: Objective: the objective to optimize. variables: list, optional: the variables of objective to optimize. If None: optimize all. initial_values: dict, optional: a starting point from which to begin optimization. Will be generated if None. gradient: optional: Information or object used to calculate the gradient of objective. Defaults to None: get analytically. hessian: optional: Information or object used to calculate the hessian of objective. Defaults to None: get analytically. reset_history: bool: Default = True: whether or not to reset all history before optimizing. args kwargs Returns ------- ScipyReturnType: the results of optimization. """ H = convert_PQH_to_tq_QH(Hamiltonian) Ham_variables, Ham_derivatives = H._construct_derivatives() #print("hamvars",Ham_variables) all_variables = copy.deepcopy(Ham_variables) #print(all_variables) for var in unitary.extract_variables(): all_variables.append(var) #print(all_variables) infostring = "{:15} : {}\n".format("Method", self.method) #infostring += "{:15} : {} expectationvalues\n".format("Objective", objective.count_expectationvalues()) if self.save_history and reset_history: self.reset_history() active_angles, passive_angles, variables = self.initialize_variables(all_variables, initial_values, variables) #print(active_angles, passive_angles, variables) # Transform the initial value directory into (ordered) arrays param_keys, param_values = zip(*active_angles.items()) param_values = numpy.array(param_values) # process and initialize scipy bounds bounds = None if self.method_bounds is not None: bounds = {k: None for k in active_angles} for k, v in self.method_bounds.items(): if k in bounds: bounds[k] = v infostring += "{:15} : {}\n".format("bounds", self.method_bounds) names, bounds = zip(*bounds.items()) assert (names == param_keys) # make sure the bounds are not shuffled #print(param_keys, param_values) # do the compilation here to avoid costly recompilation during the optimization #compiled_objective = self.compile_objective(objective=objective, *args, **kwargs) E = _EvalContainer(Hamiltonian = H, unitary = unitary, Eval=None, param_keys=param_keys, samples=self.samples, passive_angles=passive_angles, save_history=self.save_history, print_level=self.print_level) E.print_level = 0 (E(param_values)) E.print_level = self.print_level infostring += E.infostring if gradient is not None: infostring += "{:15} : {}\n".format("grad instr", gradient) if hessian is not None: infostring += "{:15} : {}\n".format("hess_instr", hessian) compile_gradient = self.method in (self.gradient_based_methods + self.hessian_based_methods) compile_hessian = self.method in self.hessian_based_methods dE = None ddE = None # detect if numerical gradients shall be used # switch off compiling if so if isinstance(gradient, str): if gradient.lower() == 'qng': compile_gradient = False if compile_hessian: raise TequilaException('Sorry, QNG and hessian not yet tested together.') combos = get_qng_combos(objective, initial_values=initial_values, backend=self.backend, samples=self.samples, noise=self.noise) dE = _QngContainer(combos=combos, param_keys=param_keys, passive_angles=passive_angles) infostring += "{:15} : QNG {}\n".format("gradient", dE) else: dE = gradient compile_gradient = False if compile_hessian: compile_hessian = False if hessian is None: hessian = gradient infostring += "{:15} : scipy numerical {}\n".format("gradient", dE) infostring += "{:15} : scipy numerical {}\n".format("hessian", ddE) if isinstance(gradient,dict): if gradient['method'] == 'qng': func = gradient['function'] compile_gradient = False if compile_hessian: raise TequilaException('Sorry, QNG and hessian not yet tested together.') combos = get_qng_combos(objective,func=func, initial_values=initial_values, backend=self.backend, samples=self.samples, noise=self.noise) dE = _QngContainer(combos=combos, param_keys=param_keys, passive_angles=passive_angles) infostring += "{:15} : QNG {}\n".format("gradient", dE) if isinstance(hessian, str): ddE = hessian compile_hessian = False if compile_gradient: dE =_GradContainer(Ham_derivatives = Ham_derivatives, unitary = unitary, Hamiltonian = H, Eval= E, param_keys=param_keys, samples=self.samples, passive_angles=passive_angles, save_history=self.save_history, print_level=self.print_level) dE.print_level = 0 (dE(param_values)) dE.print_level = self.print_level infostring += dE.infostring if self.print_level > 0: print(self) print(infostring) print("{:15} : {}\n".format("active variables", len(active_angles))) Es = [] optimizer_instance = self class SciPyCallback: energies = [] gradients = [] hessians = [] angles = [] real_iterations = 0 def __call__(self, *args, **kwargs): self.energies.append(E.history[-1]) self.angles.append(E.history_angles[-1]) if dE is not None and not isinstance(dE, str): self.gradients.append(dE.history[-1]) if ddE is not None and not isinstance(ddE, str): self.hessians.append(ddE.history[-1]) self.real_iterations += 1 if 'callback' in optimizer_instance.kwargs: optimizer_instance.kwargs['callback'](E.history_angles[-1]) callback = SciPyCallback() res = scipy.optimize.minimize(E, x0=param_values, jac=dE, hess=ddE, args=(Es,), method=self.method, tol=self.tol, bounds=bounds, constraints=self.method_constraints, options=self.method_options, callback=callback) # failsafe since callback is not implemented everywhere if callback.real_iterations == 0: real_iterations = range(len(E.history)) if self.save_history: self.history.energies = callback.energies self.history.energy_evaluations = E.history self.history.angles = callback.angles self.history.angles_evaluations = E.history_angles self.history.gradients = callback.gradients self.history.hessians = callback.hessians if dE is not None and not isinstance(dE, str): self.history.gradients_evaluations = dE.history if ddE is not None and not isinstance(ddE, str): self.history.hessians_evaluations = ddE.history # some methods like "cobyla" do not support callback functions if len(self.history.energies) == 0: self.history.energies = E.history self.history.angles = E.history_angles # some scipy methods always give back the last value and not the minimum (e.g. cobyla) ea = sorted(zip(E.history, E.history_angles), key=lambda x: x[0]) E_final = ea[0][0] angles_final = ea[0][1] #dict((param_keys[i], res.x[i]) for i in range(len(param_keys))) angles_final = {**angles_final, **passive_angles} return SciPyResults(energy=E_final, history=self.history, variables=format_variable_dictionary(angles_final), scipy_result=res) def minimize(Hamiltonian, unitary, gradient: typing.Union[str, typing.Dict[Variable, Objective]] = None, hessian: typing.Union[str, typing.Dict[typing.Tuple[Variable, Variable], Objective]] = None, initial_values: typing.Dict[typing.Hashable, numbers.Real] = None, variables: typing.List[typing.Hashable] = None, samples: int = None, maxiter: int = 100, backend: str = None, backend_options: dict = None, noise: NoiseModel = None, device: str = None, method: str = "BFGS", tol: float = 1.e-3, method_options: dict = None, method_bounds: typing.Dict[typing.Hashable, numbers.Real] = None, method_constraints=None, silent: bool = False, save_history: bool = True, *args, **kwargs) -> SciPyResults: """ calls the local optimize_scipy scipy funtion instead and pass down the objective construction down Parameters ---------- objective: Objective : The tequila objective to optimize gradient: typing.Union[str, typing.Dict[Variable, Objective], None] : Default value = None): '2-point', 'cs' or '3-point' for numerical gradient evaluation (does not work in combination with all optimizers), dictionary of variables and tequila objective to define own gradient, None for automatic construction (default) Other options include 'qng' to use the quantum natural gradient. hessian: typing.Union[str, typing.Dict[Variable, Objective], None], optional: '2-point', 'cs' or '3-point' for numerical gradient evaluation (does not work in combination with all optimizers), dictionary (keys:tuple of variables, values:tequila objective) to define own gradient, None for automatic construction (default) initial_values: typing.Dict[typing.Hashable, numbers.Real], optional: Initial values as dictionary of Hashable types (variable keys) and floating point numbers. If given None they will all be set to zero variables: typing.List[typing.Hashable], optional: List of Variables to optimize samples: int, optional: samples/shots to take in every run of the quantum circuits (None activates full wavefunction simulation) maxiter: int : (Default value = 100): max iters to use. backend: str, optional: Simulator backend, will be automatically chosen if set to None backend_options: dict, optional: Additional options for the backend Will be unpacked and passed to the compiled objective in every call noise: NoiseModel, optional: a NoiseModel to apply to all expectation values in the objective. method: str : (Default = "BFGS"): Optimization method (see scipy documentation, or 'available methods') tol: float : (Default = 1.e-3): Convergence tolerance for optimization (see scipy documentation) method_options: dict, optional: Dictionary of options (see scipy documentation) method_bounds: typing.Dict[typing.Hashable, typing.Tuple[float, float]], optional: bounds for the variables (see scipy documentation) method_constraints: optional: (see scipy documentation silent: bool : No printout if True save_history: bool: Save the history throughout the optimization Returns ------- SciPyReturnType: the results of optimization """ if isinstance(gradient, dict) or hasattr(gradient, "items"): if all([isinstance(x, Objective) for x in gradient.values()]): gradient = format_variable_dictionary(gradient) if isinstance(hessian, dict) or hasattr(hessian, "items"): if all([isinstance(x, Objective) for x in hessian.values()]): hessian = {(assign_variable(k[0]), assign_variable([k[1]])): v for k, v in hessian.items()} method_bounds = format_variable_dictionary(method_bounds) # set defaults optimizer = optimize_scipy(save_history=save_history, maxiter=maxiter, method=method, method_options=method_options, method_bounds=method_bounds, method_constraints=method_constraints, silent=silent, backend=backend, backend_options=backend_options, device=device, samples=samples, noise_model=noise, tol=tol, *args, **kwargs) if initial_values is not None: initial_values = {assign_variable(k): v for k, v in initial_values.items()} return optimizer(Hamiltonian, unitary, gradient=gradient, hessian=hessian, initial_values=initial_values, variables=variables, *args, **kwargs)
24,489
42.732143
144
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_0.6/energy_optimization.py
import tequila as tq import numpy as np from tequila.objective.objective import Variable import openfermion from hacked_openfermion_qubit_operator import ParamQubitHamiltonian from typing import Union from vqe_utils import convert_PQH_to_tq_QH, convert_tq_QH_to_PQH,\ fold_unitary_into_hamiltonian from grad_hacked import grad from scipy_optimizer import minimize import scipy import random # guess we could substitute that with numpy.random #TODO import argparse import pickle as pk import sys sys.path.insert(0, '../../../') #sys.path.insert(0, '../') # This needs to be properly integrated somewhere else at some point # from tn_update.qq import contract_energy, optimize_wavefunctions from tn_update.my_mpo import * from tn_update.wfn_optimization import contract_energy_mpo, optimize_wavefunctions_mpo, initialize_wfns_randomly def energy_from_wfn_opti(hamiltonian: tq.QubitHamiltonian, n_qubits: int, guess_wfns=None, TOL=1e-4) -> tuple: ''' Get energy using a tensornetwork based method ~ power method (here as blackbox) ''' d = int(2**(n_qubits/2)) # Build MPO h_mpo = MyMPO(hamiltonian=hamiltonian, n_qubits=n_qubits, maxdim=500) h_mpo.make_mpo_from_hamiltonian() # Optimize wavefunctions based on random guess out = None it = 0 while out is None: # Set up random initial guesses for subsystems it += 1 if guess_wfns is None: psiL_rand = initialize_wfns_randomly(d, n_qubits//2) psiR_rand = initialize_wfns_randomly(d, n_qubits//2) else: psiL_rand = guess_wfns[0] psiR_rand = guess_wfns[1] out = optimize_wavefunctions_mpo(h_mpo, psiL_rand, psiR_rand, TOL=TOL, silent=True) energy_rand = out[0] optimal_wfns = [out[1], out[2]] return energy_rand, optimal_wfns def combine_two_clusters(H: tq.QubitHamiltonian, subsystems: list, circ_list: list) -> float: ''' E = nuc_rep + \sum_j c_j <0_A | U_A+ sigma_j|A U_A | 0_A><0_B | U_B+ sigma_j|B U_B | 0_B> i ) Split up Hamiltonian into vector c = [c_j], all sigmas of system A and system B ii ) Two vectors of ExpectationValues E_A=[E(U_A, sigma_j|A)], E_B=[E(U_B, sigma_j|B)] iii) Minimize vectors from ii) iv ) Perform weighted sum \sum_j c_[j] E_A[j] E_B[j] result = nuc_rep + iv) Finishing touch inspired by private tequila-repo / pair-separated objective This is still rather inefficient/unoptimized Can still prune out near-zero coefficients c_j ''' objective = 0.0 n_subsystems = len(subsystems) # Over all Paulistrings in the Hamiltonian for p_index, pauli in enumerate(H.paulistrings): # Gather coefficient coeff = pauli.coeff.real # Empty dictionary for operations: # to be filled with another dictionary per subsystem, where then # e.g. X(0)Z(1)Y(2)X(4) and subsystems=[[0,1,2],[3,4,5]] # -> ops={ 0: {0: 'X', 1: 'Z', 2: 'Y'}, 1: {4: 'X'} } ops = {} for s_index, sys in enumerate(subsystems): for k, v in pauli.items(): if k in sys: if s_index in ops: ops[s_index][k] = v else: ops[s_index] = {k: v} # If no ops gathered -> identity -> nuclear repulsion if len(ops) == 0: #print ("this should only happen ONCE") objective += coeff # If not just identity: # add objective += c_j * prod_subsys( < Paulistring_j_subsys >_{U_subsys} ) elif len(ops) > 0: obj_tmp = coeff for s_index, sys_pauli in ops.items(): #print (s_index, sys_pauli) H_tmp = QubitHamiltonian.from_paulistrings(PauliString(data=sys_pauli)) E_tmp = ExpectationValue(U=circ_list[s_index], H=H_tmp) obj_tmp *= E_tmp objective += obj_tmp initial_values = {k: 0.0 for k in objective.extract_variables()} random_initial_values = {k: 1e-2*np.random.uniform(-1, 1) for k in objective.extract_variables()} method = 'bfgs' # 'bfgs' # 'l-bfgs-b' # 'cobyla' # 'slsqp' curr_res = tq.minimize(method=method, objective=objective, initial_values=initial_values, gradient='two-point', backend='qulacs', method_options={"finite_diff_rel_step": 1e-3}) return curr_res.energy def energy_from_tq_qcircuit(hamiltonian: Union[tq.QubitHamiltonian, ParamQubitHamiltonian], n_qubits: int, circuit = Union[list, tq.QCircuit], subsystems: list = [[0,1,2,3,4,5]], initial_guess = None)-> tuple: ''' Get minimal energy using tequila ''' result = None # If only one circuit handed over, just run simple VQE if isinstance(circuit, list) and len(circuit) == 1: circuit = circuit[0] if isinstance(circuit, tq.QCircuit): if isinstance(hamiltonian, tq.QubitHamiltonian): E = tq.ExpectationValue(H=hamiltonian, U=circuit) if initial_guess is None: initial_angles = {k: 0.0 for k in E.extract_variables()} else: initial_angles = initial_guess #print ("optimizing non-param...") result = tq.minimize(objective=E, method='l-bfgs-b', silent=True, backend='qulacs', initial_values=initial_angles) #gradient='two-point', backend='qulacs', #method_options={"finite_diff_rel_step": 1e-4}) elif isinstance(hamiltonian, ParamQubitHamiltonian): if initial_guess is None: raise Exception("Need to provide initial guess for this to work.") initial_angles = None else: initial_angles = initial_guess #print ("optimizing param...") result = minimize(hamiltonian, circuit, method='bfgs', initial_values=initial_angles, backend="qulacs", silent=True) # If more circuits handed over, assume subsystems else: # TODO!! implement initial guess for the combine_two_clusters thing #print ("Should not happen for now...") result = combine_two_clusters(hamiltonian, subsystems, circuit) return result.energy, result.angles def mixed_optimization(hamiltonian: ParamQubitHamiltonian, n_qubits: int, initial_guess: Union[dict, list]=None, init_angles: list=None): ''' Minimizes energy using wfn opti and a parametrized Hamiltonian min_{psi, theta fixed} <psi | H(theta) | psi> --> min_{t, p fixed} <p | H(t) | p> ^---------------------------------------------------^ until convergence ''' energy, optimal_state = None, None H_qh = convert_PQH_to_tq_QH(hamiltonian) var_keys, H_derivs = H_qh._construct_derivatives() print("var keys", var_keys, flush=True) print('var dict', init_angles, flush=True) # if not init_angles: # var_vals = [0. for i in range(len(var_keys))] # initialize with 0 # else: # var_vals = init_angles def build_variable_dict(keys, values): assert(len(keys)==len(values)) out = dict() for idx, key in enumerate(keys): out[key] = complex(values[idx]) return out var_dict = init_angles var_vals = [*init_angles.values()] assert(build_variable_dict(var_keys, var_vals) == var_dict) def wrap_energy_eval(psi): ''' like energy_from_wfn_opti but instead of optimize get inner product ''' def energy_eval_fn(x): var_dict = build_variable_dict(var_keys, x) H_qh_fix = H_qh(var_dict) H_mpo = MyMPO(hamiltonian=H_qh_fix, n_qubits=n_qubits, maxdim=500) H_mpo.make_mpo_from_hamiltonian() return contract_energy_mpo(H_mpo, psi[0], psi[1]) return energy_eval_fn def wrap_gradient_eval(psi): ''' call derivatives with updated variable list ''' def gradient_eval_fn(x): variables = build_variable_dict(var_keys, x) deriv_expectations = H_derivs.values() # list of ParamQubitHamiltonian's deriv_qhs = [convert_PQH_to_tq_QH(d) for d in deriv_expectations] deriv_qhs = [d(variables) for d in deriv_qhs] # list of tq.QubitHamiltonian's # print(deriv_qhs) deriv_mpos = [MyMPO(hamiltonian=d, n_qubits=n_qubits, maxdim=500)\ for d in deriv_qhs] # print(deriv_mpos[0].n_qubits) for d in deriv_mpos: d.make_mpo_from_hamiltonian() # deriv_mpos = [d.make_mpo_from_hamiltonian() for d in deriv_mpos] return np.asarray([contract_energy_mpo(d, psi[0], psi[1]) for d in deriv_mpos]) return gradient_eval_fn def do_wfn_opti(values, guess_wfns, TOL): # H_qh = H_qh(H_vars) var_dict = build_variable_dict(var_keys, values) en, psi = energy_from_wfn_opti(H_qh(var_dict), n_qubits=n_qubits, guess_wfns=guess_wfns, TOL=TOL) return en, psi def do_param_opti(psi, x0): result = scipy.optimize.minimize(fun=wrap_energy_eval(psi), jac=wrap_gradient_eval(psi), method='bfgs', x0=x0, options={'maxiter': 4}) # print(result) return result e_prev, psi_prev = 123., None # print("iguess", initial_guess) e_curr, psi_curr = do_wfn_opti(var_vals, initial_guess, 1e-5) print('first eval', e_curr, flush=True) def converged(e_prev, e_curr, TOL=1e-4): return True if np.abs(e_prev-e_curr) < TOL else False it = 0 var_prev = var_vals print("vars before comp", var_prev, flush=True) while not converged(e_prev, e_curr) and it < 50: e_prev, psi_prev = e_curr, psi_curr # print('before param opti') res = do_param_opti(psi_curr, var_prev) var_curr = res['x'] print('curr vars', var_curr, flush=True) e_curr = res['fun'] print('en before wfn opti', e_curr, flush=True) # print("iiiiiguess", psi_prev) e_curr, psi_curr = do_wfn_opti(var_curr, psi_prev, 1e-3) print('en after wfn opti', e_curr, flush=True) it += 1 print('at iteration', it, flush=True) return e_curr, psi_curr # optimize parameters with fixed wavefunction # define/wrap energy function - given |p>, evaluate <p|H(t)|p> ''' def wrap_gradient(objective: typing.Union[Objective, QTensor], no_compile=False, *args, **kwargs): def gradient_fn(variable: Variable = None): return grad(objective: typing.Union[Objective, QTensor], variable: Variable = None, no_compile=False, *args, **kwargs) return grad_fn ''' def minimize_energy(hamiltonian: Union[ParamQubitHamiltonian, tq.QubitHamiltonian], n_qubits: int, type_energy_eval: str='wfn', cluster_circuit: tq.QCircuit=None, initial_guess=None, initial_mixed_angles: dict=None) -> float: ''' Minimizes energy functional either according a power-method inspired shortcut ('wfn') or using a unitary circuit ('qc') ''' if type_energy_eval == 'wfn': if isinstance(hamiltonian, tq.QubitHamiltonian): energy, optimal_state = energy_from_wfn_opti(hamiltonian, n_qubits, initial_guess) elif isinstance(hamiltonian, ParamQubitHamiltonian): init_angles = initial_mixed_angles energy, optimal_state = mixed_optimization(hamiltonian=hamiltonian, n_qubits=n_qubits, initial_guess=initial_guess, init_angles=init_angles) elif type_energy_eval == 'qc': if cluster_circuit is None: raise Exception("Need to hand over circuit!") energy, optimal_state = energy_from_tq_qcircuit(hamiltonian, n_qubits, cluster_circuit, [[0,1,2,3],[4,5,6,7]], initial_guess) else: raise Exception("Option not implemented!") return energy, optimal_state
12,457
43.021201
225
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_0.6/parallel_annealing.py
import tequila as tq import multiprocessing import copy from time import sleep from mutation_options import * from pathos.multiprocessing import ProcessingPool as Pool def evolve_population(hamiltonian, type_energy_eval, cluster_circuit, process_id, num_offsprings, actions_ratio, tasks, results): """ This function carries a single step of the simulated annealing on a single member of the generation args: process_id: A unique identifier for each process num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for mutations tasks: multiprocessing queue to pass family_id, instructions and current_fitness family_id: A unique identifier for each family instructions: An object consisting of the instructions in the quantum circuit current_fitness: Current fitness value of the circuit results: multiprocessing queue to pass results back """ #print('[%s] evaluation routine starts' % process_id) while True: try: #getting parameters for mutation and carrying it family_id, instructions, current_fitness = tasks.get() #check if patience has been exhausted if instructions.patience == 0: instructions.reset_to_best() best_child = 0 best_energy = current_fitness new_generations = {} for off_id in range(1, num_offsprings+1): scheduled_ratio = schedule_actions_ratio(epoch=0, steady_ratio=actions_ratio) action = get_action(scheduled_ratio) updated_instructions = copy.deepcopy(instructions) updated_instructions.update_by_action(action) new_fitness, wfn = evaluate_fitness(updated_instructions, hamiltonian, type_energy_eval, cluster_circuit) updated_instructions.set_reference_wfn(wfn) prob_acceptance = get_prob_acceptance(current_fitness, new_fitness, updated_instructions.T, updated_instructions.reference_energy) # need to figure out in case we have two equals new_generations[str(off_id)] = updated_instructions if best_energy > new_fitness: # now two equals -> "first one" is picked best_child = off_id best_energy = new_fitness # decision = np.random.binomial(1, prob_acceptance) # if decision == 0: if best_child == 0: # Add result to the queue instructions.patience -= 1 #print('Reduced patience -- now ' + str(updated_instructions.patience)) if instructions.patience == 0: if instructions.best_previous_instructions: instructions.reset_to_best() else: instructions.update_T() results.put((family_id, instructions, current_fitness)) else: # Add result to the queue if (best_energy < current_fitness): new_generations[str(best_child)].update_best_previous_instructions() new_generations[str(best_child)].update_T() results.put((family_id, new_generations[str(best_child)], best_energy)) except Exception as eeee: #print('[%s] evaluation routine quits' % process_id) #print(eeee) # Indicate finished results.put(-1) break return def evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, num_processors=4, type_energy_eval='wfn', cluster_circuit=None): """ This function does parallel mutation on all the members of the generation and updates the generation args: num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for sampling instructions_dict: A dictionary with the "Instructions" objects the corresponding fitness values as values num_processors: Number of processors to use for parallel run """ # Define IPC manager manager = multiprocessing.Manager() # Define a list (queue) for tasks and computation results tasks = manager.Queue() results = manager.Queue() processes = [] pool = Pool(processes=num_processors) for i in range(num_processors): process_id = 'P%i' % i # Create the process, and connect it to the worker function new_process = multiprocessing.Process(target=evolve_population, args=(hamiltonian, type_energy_eval, cluster_circuit, process_id, num_offsprings, actions_ratio, tasks, results)) # Add new process to the list of processes processes.append(new_process) # Start the process new_process.start() #print("putting tasks") for family_id in instructions_dict: single_task = (family_id, instructions_dict[family_id][0], instructions_dict[family_id][1]) tasks.put(single_task) # Wait while the workers process - change it to something for our case later # sleep(5) multiprocessing.Barrier(num_processors) #print("after barrier") # Quit the worker processes by sending them -1 for i in range(num_processors): tasks.put(-1) # Read calculation results num_finished_processes = 0 while True: # Read result #print("num fin", num_finished_processes) try: family_id, updated_instructions, new_fitness = results.get() instructions_dict[family_id] = (updated_instructions, new_fitness) except: # Process has finished num_finished_processes += 1 if num_finished_processes == num_processors: break for process in processes: process.join() pool.close()
6,456
38.371951
146
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_0.6/single_thread_annealing.py
import tequila as tq import copy from mutation_options import * def st_evolve_population(hamiltonian, type_energy_eval, cluster_circuit, num_offsprings, actions_ratio, tasks): """ This function carries a single step of the simulated annealing on a single member of the generation args: num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for mutations tasks: a tuple of (family_id, instructions and current_fitness) family_id: A unique identifier for each family instructions: An object consisting of the instructions in the quantum circuit current_fitness: Current fitness value of the circuit """ family_id, instructions, current_fitness = tasks #check if patience has been exhausted if instructions.patience == 0: if instructions.best_previous_instructions: instructions.reset_to_best() best_child = 0 best_energy = current_fitness new_generations = {} for off_id in range(1, num_offsprings+1): scheduled_ratio = schedule_actions_ratio(epoch=0, steady_ratio=actions_ratio) action = get_action(scheduled_ratio) updated_instructions = copy.deepcopy(instructions) updated_instructions.update_by_action(action) new_fitness, wfn = evaluate_fitness(updated_instructions, hamiltonian, type_energy_eval, cluster_circuit) updated_instructions.set_reference_wfn(wfn) prob_acceptance = get_prob_acceptance(current_fitness, new_fitness, updated_instructions.T, updated_instructions.reference_energy) # need to figure out in case we have two equals new_generations[str(off_id)] = updated_instructions if best_energy > new_fitness: # now two equals -> "first one" is picked best_child = off_id best_energy = new_fitness # decision = np.random.binomial(1, prob_acceptance) # if decision == 0: if best_child == 0: # Add result to the queue instructions.patience -= 1 #print('Reduced patience -- now ' + str(updated_instructions.patience)) if instructions.patience == 0: if instructions.best_previous_instructions: instructions.reset_to_best() else: instructions.update_T() results = ((family_id, instructions, current_fitness)) else: # Add result to the queue if (best_energy < current_fitness): new_generations[str(best_child)].update_best_previous_instructions() new_generations[str(best_child)].update_T() results = ((family_id, new_generations[str(best_child)], best_energy)) return results def st_evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, type_energy_eval='wfn', cluster_circuit=None): """ This function does a single threas mutation on all the members of the generation and updates the generation args: num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for sampling instructions_dict: A dictionary with the "Instructions" objects the corresponding fitness values as values """ for family_id in instructions_dict: task = (family_id, instructions_dict[family_id][0], instructions_dict[family_id][1]) results = st_evolve_population(hamiltonian, type_energy_eval, cluster_circuit, num_offsprings, actions_ratio, task) family_id, updated_instructions, new_fitness = results instructions_dict[family_id] = (updated_instructions, new_fitness)
4,005
40.298969
138
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_0.6/mutation_options.py
import argparse import numpy as np import random import copy import tequila as tq from typing import Union from collections import Counter from time import time from vqe_utils import convert_PQH_to_tq_QH, convert_tq_QH_to_PQH,\ fold_unitary_into_hamiltonian from energy_optimization import minimize_energy global_seed = 1 class Instructions: ''' TODO need to put some documentation here ''' def __init__(self, n_qubits, mu=2.0, sigma=0.4, alpha=0.9, T_0=1.0, beta=0.5, patience=10, max_non_cliffords=0, reference_energy=0., number=None): # hardcoded values for now self.num_non_cliffords = 0 self.max_non_cliffords = max_non_cliffords # ------------------------ self.starting_patience = patience self.patience = patience self.mu = mu self.sigma = sigma self.alpha = alpha self.beta = beta self.T_0 = T_0 self.T = T_0 self.gates = self.get_random_gates(number=number) self.n_qubits = n_qubits self.positions = self.get_random_positions() self.best_previous_instructions = {} self.reference_energy = reference_energy self.best_reference_wfn = None self.noncliff_replacements = {} def _str(self): print(self.gates) print(self.positions) def set_reference_wfn(self, reference_wfn): self.best_reference_wfn = reference_wfn def update_T(self, update_type: str = 'regular', best_temp=None): # Regular update if update_type.lower() == 'regular': self.T = self.alpha * self.T # Temperature update if patience ran out elif update_type.lower() == 'patience': self.T = self.beta*best_temp + (1-self.beta)*self.T_0 def get_random_gates(self, number=None): ''' Randomly generates a list of gates. number indicates the number of gates to generate otherwise, number will be drawn from a log normal distribution ''' mu, sigma = self.mu, self.sigma full_options = ['X','Y','Z','S','H','CX', 'CY', 'CZ','SWAP', 'UCC2c', 'UCC4c', 'UCC2', 'UCC4'] clifford_options = ['X','Y','Z','S','H','CX', 'CY', 'CZ','SWAP', 'UCC2c', 'UCC4c'] #non_clifford_options = ['UCC2', 'UCC4'] # Gate distribution, selecting number of gates to add k = np.random.lognormal(mu, sigma) k = np.int(k) if number is not None: k = number # Selecting gate types gates = None if self.num_non_cliffords < self.max_non_cliffords: gates = random.choices(full_options, k=k) # with replacement else: gates = random.choices(clifford_options, k=k) new_num_non_cliffords = 0 if "UCC2" in gates: new_num_non_cliffords += Counter(gates)["UCC2"] if "UCC4" in gates: new_num_non_cliffords += Counter(gates)["UCC4"] if (new_num_non_cliffords+self.num_non_cliffords) <= self.max_non_cliffords: self.num_non_cliffords += new_num_non_cliffords else: extra_cliffords = (new_num_non_cliffords+self.num_non_cliffords) - self.max_non_cliffords assert(extra_cliffords >= 0) new_gates = random.choices(clifford_options, k=extra_cliffords) for g in new_gates: try: gates[gates.index("UCC4")] = g except: gates[gates.index("UCC2")] = g self.num_non_cliffords = self.max_non_cliffords if k == 1: if gates == "UCC2c" or gates == "UCC4c": gates = get_string_Cliff_ucc(gates) if gates == "UCC2" or gates == "UCC4": gates = get_string_ucc(gates) else: for ind, gate in enumerate(gates): if gate == "UCC2c" or gate == "UCC4c": gates[ind] = get_string_Cliff_ucc(gate) if gate == "UCC2" or gate == "UCC4": gates[ind] = get_string_ucc(gate) return gates def get_random_positions(self, gates=None): ''' Randomly assign gates to qubits. ''' if gates is None: gates = self.gates n_qubits = self.n_qubits single_qubit = ['X','Y','Z','S','H'] # two_qubit = ['CX','CY','CZ', 'SWAP'] two_qubit = ['CX', 'CY', 'CZ', 'SWAP', 'UCC2c', 'UCC2'] four_qubit = ['UCC4c', 'UCC4'] qubits = list(range(0, n_qubits)) q_positions = [] for gate in gates: if gate in four_qubit: p = random.sample(qubits, k=4) if gate in two_qubit: p = random.sample(qubits, k=2) if gate in single_qubit: p = random.sample(qubits, k=1) if "UCC2" in gate: p = random.sample(qubits, k=2) if "UCC4" in gate: p = random.sample(qubits, k=4) q_positions.append(p) return q_positions def delete(self, number=None): ''' Randomly drops some gates from a clifford instruction set if not specified, the number of gates to drop is sampled from a uniform distribution over all the gates ''' gates = copy.deepcopy(self.gates) positions = copy.deepcopy(self.positions) n_qubits = self.n_qubits if number is not None: num_to_drop = number else: num_to_drop = random.sample(range(1,len(gates)-1), k=1)[0] action_indices = random.sample(range(0,len(gates)-1), k=num_to_drop) for index in sorted(action_indices, reverse=True): if "UCC2_" in str(gates[index]) or "UCC4_" in str(gates[index]): self.num_non_cliffords -= 1 del gates[index] del positions[index] self.gates = gates self.positions = positions #print ('deleted {} gates'.format(num_to_drop)) def add(self, number=None): ''' adds a random selection of clifford gates to the end of a clifford instruction set if number is not specified, the number of gates to add will be drawn from a log normal distribution ''' gates = copy.deepcopy(self.gates) positions = copy.deepcopy(self.positions) n_qubits = self.n_qubits added_instructions = self.get_new_instructions(number=number) gates.extend(added_instructions['gates']) positions.extend(added_instructions['positions']) self.gates = gates self.positions = positions #print ('added {} gates'.format(len(added_instructions['gates']))) def change(self, number=None): ''' change a random number of gates and qubit positions in a clifford instruction set if not specified, the number of gates to change is sampled from a uniform distribution over all the gates ''' gates = copy.deepcopy(self.gates) positions = copy.deepcopy(self.positions) n_qubits = self.n_qubits if number is not None: num_to_change = number else: num_to_change = random.sample(range(1,len(gates)), k=1)[0] action_indices = random.sample(range(0,len(gates)-1), k=num_to_change) added_instructions = self.get_new_instructions(number=num_to_change) for i in range(num_to_change): gates[action_indices[i]] = added_instructions['gates'][i] positions[action_indices[i]] = added_instructions['positions'][i] self.gates = gates self.positions = positions #print ('changed {} gates'.format(len(added_instructions['gates']))) # TODO to be debugged! def prune(self): ''' Prune instructions to remove redundant operations: --> first gate should go beyond subsystems (this assumes expressible enough subsystem-ciruits #TODO later -> this needs subsystem information in here! --> 2 subsequent gates that are their respective inverse can be removed #TODO this might change the number of qubits acted on in theory? ''' pass #print ("DEBUG PRUNE FUNCTION!") # gates = copy.deepcopy(self.gates) # positions = copy.deepcopy(self.positions) # for g_index in range(len(gates)-1): # if (gates[g_index] == gates[g_index+1] and not 'S' in gates[g_index])\ # or (gates[g_index] == 'S' and gates[g_index+1] == 'S-dag')\ # or (gates[g_index] == 'S-dag' and gates[g_index+1] == 'S'): # print(len(gates)) # if positions[g_index] == positions[g_index+1]: # self.gates.pop(g_index) # self.positions.pop(g_index) def update_by_action(self, action: str): ''' Updates instruction dictionary -> Either adds, deletes or changes gates ''' if action == 'delete': try: self.delete() # In case there are too few gates to delete except: pass elif action == 'add': self.add() elif action == 'change': self.change() else: raise Exception("Unknown action type " + action + ".") self.prune() def update_best_previous_instructions(self): ''' Overwrites the best previous instructions with the current ones. ''' self.best_previous_instructions['gates'] = copy.deepcopy(self.gates) self.best_previous_instructions['positions'] = copy.deepcopy(self.positions) self.best_previous_instructions['T'] = copy.deepcopy(self.T) def reset_to_best(self): ''' Overwrites the current instructions with best previous ones. ''' #print ('Patience ran out... resetting to best previous instructions.') self.gates = copy.deepcopy(self.best_previous_instructions['gates']) self.positions = copy.deepcopy(self.best_previous_instructions['positions']) self.patience = copy.deepcopy(self.starting_patience) self.update_T(update_type='patience', best_temp=copy.deepcopy(self.best_previous_instructions['T'])) def get_new_instructions(self, number=None): ''' Returns a a clifford instruction set, a dictionary of gates and qubit positions for building a clifford circuit ''' mu = self.mu sigma = self.sigma n_qubits = self.n_qubits instruction = {} gates = self.get_random_gates(number=number) q_positions = self.get_random_positions(gates) assert(len(q_positions) == len(gates)) instruction['gates'] = gates instruction['positions'] = q_positions # instruction['n_qubits'] = n_qubits # instruction['patience'] = patience # instruction['best_previous_options'] = {} return instruction def replace_cg_w_ncg(self, gate_id): ''' replaces a set of Clifford gates with corresponding non-Cliffords ''' print("gates before", self.gates, flush=True) gate = self.gates[gate_id] if gate == 'X': gate = "Rx" elif gate == 'Y': gate = "Ry" elif gate == 'Z': gate = "Rz" elif gate == 'S': gate = "S_nc" #gate = "Rz" elif gate == 'H': gate = "H_nc" # this does not work??????? # gate = "Ry" elif gate == 'CX': gate = "CRx" elif gate == 'CY': gate = "CRy" elif gate == 'CZ': gate = "CRz" elif gate == 'SWAP':#find a way to change this as well pass # gate = "SWAP" elif "UCC2c" in str(gate): pre_gate = gate.split("_")[0] mid_gate = gate.split("_")[-1] gate = pre_gate + "_" + "UCC2" + "_" +mid_gate elif "UCC4c" in str(gate): pre_gate = gate.split("_")[0] mid_gate = gate.split("_")[-1] gate = pre_gate + "_" + "UCC4" + "_" + mid_gate self.gates[gate_id] = gate print("gates after", self.gates, flush=True) def build_circuit(instructions): ''' constructs a tequila circuit from a clifford instruction set ''' gates = instructions.gates q_positions = instructions.positions init_angles = {} clifford_circuit = tq.QCircuit() # for i in range(1, len(gates)): # TODO len(q_positions) not == len(gates) for i in range(len(gates)): if len(q_positions[i]) == 2: q1, q2 = q_positions[i] elif len(q_positions[i]) == 1: q1 = q_positions[i] q2 = None elif not len(q_positions[i]) == 4: raise Exception("q_positions[i] must have length 1, 2 or 4...") if gates[i] == 'X': clifford_circuit += tq.gates.X(q1) if gates[i] == 'Y': clifford_circuit += tq.gates.Y(q1) if gates[i] == 'Z': clifford_circuit += tq.gates.Z(q1) if gates[i] == 'S': clifford_circuit += tq.gates.S(q1) if gates[i] == 'H': clifford_circuit += tq.gates.H(q1) if gates[i] == 'CX': clifford_circuit += tq.gates.CX(q1, q2) if gates[i] == 'CY': #using generators clifford_circuit += tq.gates.S(q2) clifford_circuit += tq.gates.CX(q1, q2) clifford_circuit += tq.gates.S(q2).dagger() if gates[i] == 'CZ': #using generators clifford_circuit += tq.gates.H(q2) clifford_circuit += tq.gates.CX(q1, q2) clifford_circuit += tq.gates.H(q2) if gates[i] == 'SWAP': clifford_circuit += tq.gates.CX(q1, q2) clifford_circuit += tq.gates.CX(q2, q1) clifford_circuit += tq.gates.CX(q1, q2) if "UCC2c" in str(gates[i]) or "UCC4c" in str(gates[i]): clifford_circuit += get_clifford_UCC_circuit(gates[i], q_positions[i]) # NON-CLIFFORD STUFF FROM HERE ON global global_seed if gates[i] == "S_nc": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.S(q1) clifford_circuit += tq.gates.Rz(angle=var_name, target=q1) if gates[i] == "H_nc": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.H(q1) clifford_circuit += tq.gates.Ry(angle=var_name, target=q1) if gates[i] == "Rx": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.X(q1) clifford_circuit += tq.gates.Rx(angle=var_name, target=q1) if gates[i] == "Ry": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.Y(q1) clifford_circuit += tq.gates.Ry(angle=var_name, target=q1) if gates[i] == "Rz": global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0 clifford_circuit += tq.gates.Z(q1) clifford_circuit += tq.gates.Rz(angle=var_name, target=q1) if gates[i] == "CRx": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = np.pi clifford_circuit += tq.gates.Rx(angle=var_name, target=q2, control=q1) if gates[i] == "CRy": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = np.pi clifford_circuit += tq.gates.Ry(angle=var_name, target=q2, control=q1) if gates[i] == "CRz": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = np.pi clifford_circuit += tq.gates.Rz(angle=var_name, target=q2, control=q1) def get_ucc_init_angles(gate): angle = None pre_gate = gate.split("_")[0] mid_gate = gate.split("_")[-1] if mid_gate == 'Z': angle = 0. elif mid_gate == 'S': angle = 0. elif mid_gate == 'S-dag': angle = 0. else: raise Exception("This should not happen -- center/mid gate should be Z,S,S_dag.") return angle if "UCC2_" in str(gates[i]) or "UCC4_" in str(gates[i]): uccc_circuit = get_non_clifford_UCC_circuit(gates[i], q_positions[i]) clifford_circuit += uccc_circuit try: var_name = uccc_circuit.extract_variables()[0] init_angles[var_name]= get_ucc_init_angles(gates[i]) except: init_angles = {} return clifford_circuit, init_angles def get_non_clifford_UCC_circuit(gate, positions): """ """ pre_cir_dic = {"X":tq.gates.X, "Y":tq.gates.Y, "H":tq.gates.H, "I":None} pre_gate = gate.split("_")[0] pre_gates = pre_gate.split(*"#") pre_circuit = tq.QCircuit() for i, pos in enumerate(positions): try: pre_circuit += pre_cir_dic[pre_gates[i]](pos) except: pass for i, pos in enumerate(positions[:-1]): pre_circuit += tq.gates.CX(pos, positions[i+1]) global global_seed mid_gate = gate.split("_")[-1] mid_circuit = tq.QCircuit() if mid_gate == "S": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit += tq.gates.S(positions[-1]) mid_circuit += tq.gates.Rz(angle=tq.Variable(var_name), target=positions[-1]) elif mid_gate == "S-dag": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit += tq.gates.S(positions[-1]).dagger() mid_circuit += tq.gates.Rz(angle=tq.Variable(var_name), target=positions[-1]) elif mid_gate == "Z": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit += tq.gates.Z(positions[-1]) mid_circuit += tq.gates.Rz(angle=tq.Variable(var_name), target=positions[-1]) return pre_circuit + mid_circuit + pre_circuit.dagger() def get_string_Cliff_ucc(gate): """ this function randomly sample basis change and mid circuit elements for a ucc-type clifford circuit and adds it to the gate """ pre_circ_comp = ["X", "Y", "H", "I"] mid_circ_comp = ["S", "S-dag", "Z"] p = None if "UCC2c" in gate: p = random.sample(pre_circ_comp, k=2) elif "UCC4c" in gate: p = random.sample(pre_circ_comp, k=4) pre_gate = "#".join([str(item) for item in p]) mid_gate = random.sample(mid_circ_comp, k=1)[0] return str(pre_gate + "_" + gate + "_" + mid_gate) def get_string_ucc(gate): """ this function randomly sample basis change and mid circuit elements for a ucc-type clifford circuit and adds it to the gate """ pre_circ_comp = ["X", "Y", "H", "I"] p = None if "UCC2" in gate: p = random.sample(pre_circ_comp, k=2) elif "UCC4" in gate: p = random.sample(pre_circ_comp, k=4) pre_gate = "#".join([str(item) for item in p]) mid_gate = str(random.random() * 2 * np.pi) return str(pre_gate + "_" + gate + "_" + mid_gate) def get_clifford_UCC_circuit(gate, positions): """ This function creates an approximate UCC excitation circuit using only clifford Gates """ #pre_circ_comp = ["X", "Y", "H", "I"] pre_cir_dic = {"X":tq.gates.X, "Y":tq.gates.Y, "H":tq.gates.H, "I":None} pre_gate = gate.split("_")[0] pre_gates = pre_gate.split(*"#") #pre_gates = [] #if gate == "UCC2": # pre_gates = random.choices(pre_circ_comp, k=2) #if gate == "UCC4": # pre_gates = random.choices(pre_circ_comp, k=4) pre_circuit = tq.QCircuit() for i, pos in enumerate(positions): try: pre_circuit += pre_cir_dic[pre_gates[i]](pos) except: pass for i, pos in enumerate(positions[:-1]): pre_circuit += tq.gates.CX(pos, positions[i+1]) #mid_circ_comp = ["S", "S-dag", "Z"] #mid_gate = random.sample(mid_circ_comp, k=1)[0] mid_gate = gate.split("_")[-1] mid_circuit = tq.QCircuit() if mid_gate == "S": mid_circuit += tq.gates.S(positions[-1]) elif mid_gate == "S-dag": mid_circuit += tq.gates.S(positions[-1]).dagger() elif mid_gate == "Z": mid_circuit += tq.gates.Z(positions[-1]) return pre_circuit + mid_circuit + pre_circuit.dagger() def get_UCC_circuit(gate, positions): """ This function creates an UCC excitation circuit """ #pre_circ_comp = ["X", "Y", "H", "I"] pre_cir_dic = {"X":tq.gates.X, "Y":tq.gates.Y, "H":tq.gates.H, "I":None} pre_gate = gate.split("_")[0] pre_gates = pre_gate.split(*"#") pre_circuit = tq.QCircuit() for i, pos in enumerate(positions): try: pre_circuit += pre_cir_dic[pre_gates[i]](pos) except: pass for i, pos in enumerate(positions[:-1]): pre_circuit += tq.gates.CX(pos, positions[i+1]) mid_gate_val = gate.split("_")[-1] global global_seed np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit = tq.gates.Rz(target=positions[-1], angle=tq.Variable(var_name)) # mid_circ_comp = ["S", "S-dag", "Z"] # mid_gate = random.sample(mid_circ_comp, k=1)[0] # mid_circuit = tq.QCircuit() # if mid_gate == "S": # mid_circuit += tq.gates.S(positions[-1]) # elif mid_gate == "S-dag": # mid_circuit += tq.gates.S(positions[-1]).dagger() # elif mid_gate == "Z": # mid_circuit += tq.gates.Z(positions[-1]) return pre_circuit + mid_circuit + pre_circuit.dagger() def schedule_actions_ratio(epoch: int, action_options: list = ['delete', 'change', 'add'], decay: int = 30, steady_ratio: Union[tuple, list] = [0.2, 0.6, 0.2]) -> list: delete, change, add = tuple(steady_ratio) actions_ratio = [] for action in action_options: if action == 'delete': actions_ratio += [ delete*(1-np.exp(-1*epoch / decay)) ] elif action == 'change': actions_ratio += [ change*(1-np.exp(-1*epoch / decay)) ] elif action == 'add': actions_ratio += [ (1-add)*np.exp(-1*epoch / decay) + add ] else: print('Action type ', action, ' not defined!') # unnecessary for current schedule # if not np.isclose(np.sum(actions_ratio), 1.0): # actions_ratio /= np.sum(actions_ratio) return actions_ratio def get_action(ratio: list = [0.20,0.60,0.20]): ''' randomly chooses an action from delete, change, add ratio denotes the multinomial probabilities ''' choice = np.random.multinomial(n=1, pvals = ratio, size = 1) index = np.where(choice[0] == 1) action_options = ['delete', 'change', 'add'] action = action_options[index[0].item()] return action def get_prob_acceptance(E_curr, E_prev, T, reference_energy): ''' Computes acceptance probability of a certain action based on change in energy ''' delta_E = E_curr - E_prev prob = 0 if delta_E < 0 and E_curr < reference_energy: prob = 1 else: if E_curr < reference_energy: prob = np.exp(-delta_E/T) else: prob = 0 return prob def perform_folding(hamiltonian, circuit): # QubitHamiltonian -> ParamQubitHamiltonian param_hamiltonian = convert_tq_QH_to_PQH(hamiltonian) gates = circuit.gates # Go backwards gates.reverse() for gate in gates: # print("\t folding", gate) param_hamiltonian = (fold_unitary_into_hamiltonian(gate, param_hamiltonian)) # hamiltonian = convert_PQH_to_tq_QH(param_hamiltonian)() hamiltonian = param_hamiltonian return hamiltonian def evaluate_fitness(instructions, hamiltonian: tq.QubitHamiltonian, type_energy_eval: str, cluster_circuit: tq.QCircuit=None) -> tuple: ''' Evaluates fitness=objective=energy given a system for a set of instructions ''' #print ("evaluating fitness") n_qubits = instructions.n_qubits clifford_circuit, init_angles = build_circuit(instructions) # tq.draw(clifford_circuit, backend="cirq") ## TODO check if cluster_circuit is parametrized t0 = time() t1 = None folded_hamiltonian = perform_folding(hamiltonian, clifford_circuit) t1 = time() #print ("\tfolding took ", t1-t0) parametrized = len(clifford_circuit.extract_variables()) > 0 initial_guess = None if not parametrized: folded_hamiltonian = (convert_PQH_to_tq_QH(folded_hamiltonian))() elif parametrized: # TODO clifford_circuit is both ref + rest; so nomenclature is shit here variables = [gate.extract_variables() for gate in clifford_circuit.gates\ if gate.extract_variables()] variables = np.array(variables).flatten().tolist() # TODO this initial_guess is absolutely useless rn and is just causing problems if called initial_guess = { k: 0.1 for k in variables } if instructions.best_reference_wfn is not None: initial_guess = instructions.best_reference_wfn E_new, optimal_state = minimize_energy(hamiltonian=folded_hamiltonian, n_qubits=n_qubits, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit, initial_guess=initial_guess,\ initial_mixed_angles=init_angles) t2 = time() #print ("evaluated fitness; comp was ", t2-t1) #print ("current fitness: ", E_new) return E_new, optimal_state
26,497
34.096689
191
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_0.6/hacked_openfermion_qubit_operator.py
import tequila as tq import sympy import copy #from param_hamiltonian import get_geometry, generate_ucc_ansatz from hacked_openfermion_symbolic_operator import SymbolicOperator # Define products of all Pauli operators for symbolic multiplication. _PAULI_OPERATOR_PRODUCTS = { ('I', 'I'): (1., 'I'), ('I', 'X'): (1., 'X'), ('X', 'I'): (1., 'X'), ('I', 'Y'): (1., 'Y'), ('Y', 'I'): (1., 'Y'), ('I', 'Z'): (1., 'Z'), ('Z', 'I'): (1., 'Z'), ('X', 'X'): (1., 'I'), ('Y', 'Y'): (1., 'I'), ('Z', 'Z'): (1., 'I'), ('X', 'Y'): (1.j, 'Z'), ('X', 'Z'): (-1.j, 'Y'), ('Y', 'X'): (-1.j, 'Z'), ('Y', 'Z'): (1.j, 'X'), ('Z', 'X'): (1.j, 'Y'), ('Z', 'Y'): (-1.j, 'X') } _clifford_h_products = { ('I') : (1., 'I'), ('X') : (1., 'Z'), ('Y') : (-1., 'Y'), ('Z') : (1., 'X') } _clifford_s_products = { ('I') : (1., 'I'), ('X') : (-1., 'Y'), ('Y') : (1., 'X'), ('Z') : (1., 'Z') } _clifford_s_dag_products = { ('I') : (1., 'I'), ('X') : (1., 'Y'), ('Y') : (-1., 'X'), ('Z') : (1., 'Z') } _clifford_cx_products = { ('I', 'I'): (1., 'I', 'I'), ('I', 'X'): (1., 'I', 'X'), ('I', 'Y'): (1., 'Z', 'Y'), ('I', 'Z'): (1., 'Z', 'Z'), ('X', 'I'): (1., 'X', 'X'), ('X', 'X'): (1., 'X', 'I'), ('X', 'Y'): (1., 'Y', 'Z'), ('X', 'Z'): (-1., 'Y', 'Y'), ('Y', 'I'): (1., 'Y', 'X'), ('Y', 'X'): (1., 'Y', 'I'), ('Y', 'Y'): (-1., 'X', 'Z'), ('Y', 'Z'): (1., 'X', 'Y'), ('Z', 'I'): (1., 'Z', 'I'), ('Z', 'X'): (1., 'Z', 'X'), ('Z', 'Y'): (1., 'I', 'Y'), ('Z', 'Z'): (1., 'I', 'Z'), } _clifford_cy_products = { ('I', 'I'): (1., 'I', 'I'), ('I', 'X'): (1., 'Z', 'X'), ('I', 'Y'): (1., 'I', 'Y'), ('I', 'Z'): (1., 'Z', 'Z'), ('X', 'I'): (1., 'X', 'Y'), ('X', 'X'): (-1., 'Y', 'Z'), ('X', 'Y'): (1., 'X', 'I'), ('X', 'Z'): (-1., 'Y', 'X'), ('Y', 'I'): (1., 'Y', 'Y'), ('Y', 'X'): (1., 'X', 'Z'), ('Y', 'Y'): (1., 'Y', 'I'), ('Y', 'Z'): (-1., 'X', 'X'), ('Z', 'I'): (1., 'Z', 'I'), ('Z', 'X'): (1., 'I', 'X'), ('Z', 'Y'): (1., 'Z', 'Y'), ('Z', 'Z'): (1., 'I', 'Z'), } _clifford_cz_products = { ('I', 'I'): (1., 'I', 'I'), ('I', 'X'): (1., 'Z', 'X'), ('I', 'Y'): (1., 'Z', 'Y'), ('I', 'Z'): (1., 'I', 'Z'), ('X', 'I'): (1., 'X', 'Z'), ('X', 'X'): (-1., 'Y', 'Y'), ('X', 'Y'): (-1., 'Y', 'X'), ('X', 'Z'): (1., 'X', 'I'), ('Y', 'I'): (1., 'Y', 'Z'), ('Y', 'X'): (-1., 'X', 'Y'), ('Y', 'Y'): (1., 'X', 'X'), ('Y', 'Z'): (1., 'Y', 'I'), ('Z', 'I'): (1., 'Z', 'I'), ('Z', 'X'): (1., 'I', 'X'), ('Z', 'Y'): (1., 'I', 'Y'), ('Z', 'Z'): (1., 'Z', 'Z'), } COEFFICIENT_TYPES = (int, float, complex, sympy.Expr, tq.Variable) class ParamQubitHamiltonian(SymbolicOperator): @property def actions(self): """The allowed actions.""" return ('X', 'Y', 'Z') @property def action_strings(self): """The string representations of the allowed actions.""" return ('X', 'Y', 'Z') @property def action_before_index(self): """Whether action comes before index in string representations.""" return True @property def different_indices_commute(self): """Whether factors acting on different indices commute.""" return True def renormalize(self): """Fix the trace norm of an operator to 1""" norm = self.induced_norm(2) if numpy.isclose(norm, 0.0): raise ZeroDivisionError('Cannot renormalize empty or zero operator') else: self /= norm def _simplify(self, term, coefficient=1.0): """Simplify a term using commutator and anti-commutator relations.""" if not term: return coefficient, term term = sorted(term, key=lambda factor: factor[0]) new_term = [] left_factor = term[0] for right_factor in term[1:]: left_index, left_action = left_factor right_index, right_action = right_factor # Still on the same qubit, keep simplifying. if left_index == right_index: new_coefficient, new_action = _PAULI_OPERATOR_PRODUCTS[ left_action, right_action] left_factor = (left_index, new_action) coefficient *= new_coefficient # Reached different qubit, save result and re-initialize. else: if left_action != 'I': new_term.append(left_factor) left_factor = right_factor # Save result of final iteration. if left_factor[1] != 'I': new_term.append(left_factor) return coefficient, tuple(new_term) def _clifford_simplify_h(self, qubit): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 for left, right in term: if left == qubit: coeff, new_pauli = _clifford_h_products[right] new_term.append(tuple((left, new_pauli))) else: new_term.append(tuple((left,right))) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self def _clifford_simplify_s(self, qubit): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 for left, right in term: if left == qubit: coeff, new_pauli = _clifford_s_products[right] new_term.append(tuple((left, new_pauli))) else: new_term.append(tuple((left,right))) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self def _clifford_simplify_s_dag(self, qubit): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 for left, right in term: if left == qubit: coeff, new_pauli = _clifford_s_dag_products[right] new_term.append(tuple((left, new_pauli))) else: new_term.append(tuple((left,right))) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self def _clifford_simplify_control_g(self, axis, control_q, target_q): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 target = "I" control = "I" for left, right in term: if left == control_q: control = right elif left == target_q: target = right else: new_term.append(tuple((left,right))) new_c = "I" new_t = "I" if not (target == "I" and control == "I"): if axis == "X": coeff, new_c, new_t = _clifford_cx_products[control, target] if axis == "Y": coeff, new_c, new_t = _clifford_cy_products[control, target] if axis == "Z": coeff, new_c, new_t = _clifford_cz_products[control, target] if new_c != "I": new_term.append(tuple((control_q, new_c))) if new_t != "I": new_term.append(tuple((target_q, new_t))) new_term = sorted(new_term, key=lambda factor: factor[0]) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self if __name__ == "__main__": """geometry = get_geometry("H2", 0.714) print(geometry) basis_set = 'sto-3g' ref_anz, uccsd_anz, ham = generate_ucc_ansatz(geometry, basis_set) print(ham) b_ham = tq.grouping.binary_rep.BinaryHamiltonian.init_from_qubit_hamiltonian(ham) c_ham = tq.grouping.binary_rep.BinaryHamiltonian.init_from_qubit_hamiltonian(ham) print(b_ham) print(b_ham.get_binary()) print(b_ham.get_coeff()) param = uccsd_anz.extract_variables() print(param) for term in b_ham.binary_terms: print(term.coeff) term.set_coeff(param[0]) print(term.coeff) print(b_ham.get_coeff()) d_ham = c_ham.to_qubit_hamiltonian() + b_ham.to_qubit_hamiltonian() """ term = [(2,'X'), (0,'Y'), (3, 'Z')] coeff = tq.Variable("a") coeff = coeff *2.j print(coeff) print(type(coeff)) print(coeff({"a":1})) ham = ParamQubitHamiltonian(term= term, coefficient=coeff) print(ham.terms) print(str(ham)) for term in ham.terms: print(ham.terms[term]({"a":1,"b":2})) term = [(2,'X'), (0,'Z'), (3, 'Z')] coeff = tq.Variable("b") print(coeff({"b":1})) b_ham = ParamQubitHamiltonian(term= term, coefficient=coeff) print(b_ham.terms) print(str(b_ham)) for term in b_ham.terms: print(b_ham.terms[term]({"a":1,"b":2})) coeff = tq.Variable("a")*tq.Variable("b") print(coeff) print(coeff({"a":1,"b":2})) ham *= b_ham print(ham.terms) print(str(ham)) for term in ham.terms: coeff = (ham.terms[term]) print(coeff) print(coeff({"a":1,"b":2})) ham = ham*2. print(ham.terms) print(str(ham))
9,918
29.614198
85
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_0.6/HEA.py
import tequila as tq import numpy as np from tequila import gates as tq_g from tequila.objective.objective import Variable def generate_HEA(num_qubits, circuit_id=11, num_layers=1): """ This function generates different types of hardware efficient circuits as in this paper https://onlinelibrary.wiley.com/doi/full/10.1002/qute.201900070 param: num_qubits (int) -> the number of qubits in the circuit param: circuit_id (int) -> the type of hardware efficient circuit param: num_layers (int) -> the number of layers of the HEA input: num_qubits -> 4 circuit_id -> 11 num_layers -> 1 returns: ansatz (tq.QCircuit()) -> a circuit as shown below 0: ───Ry(0.318309886183791*pi*f((y0,))_0)───Rz(0.318309886183791*pi*f((z0,))_1)───@───────────────────────────────────────────────────────────────────────────────────── │ 1: ───Ry(0.318309886183791*pi*f((y1,))_2)───Rz(0.318309886183791*pi*f((z1,))_3)───X───Ry(0.318309886183791*pi*f((y4,))_8)────Rz(0.318309886183791*pi*f((z4,))_9)────@─── │ 2: ───Ry(0.318309886183791*pi*f((y2,))_4)───Rz(0.318309886183791*pi*f((z2,))_5)───@───Ry(0.318309886183791*pi*f((y5,))_10)───Rz(0.318309886183791*pi*f((z5,))_11)───X─── │ 3: ───Ry(0.318309886183791*pi*f((y3,))_6)───Rz(0.318309886183791*pi*f((z3,))_7)───X───────────────────────────────────────────────────────────────────────────────────── """ circuit = tq.QCircuit() qubits = [i for i in range(num_qubits)] if circuit_id == 1: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 2: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.CNOT(target=qubit, control=qubits[ind]) return circuit elif circuit_id == 3: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=qubit, control=qubits[ind]) count += 1 return circuit elif circuit_id == 4: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=qubit, control=qubits[ind]) count += 1 return circuit elif circuit_id == 5: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): for target in qubits: if control != target: variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=target, control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 6: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=qubits[ind+1], control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=qubits[ind+1], control=control) count += 1 return circuit elif circuit_id == 7: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): for target in qubits: if control != target: variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=target, control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 8: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=qubits[ind+1], control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=qubits[ind+1], control=control) count += 1 return circuit elif circuit_id == 9: count = 0 for _ in range(num_layers): for qubit in qubits: circuit += tq_g.H(qubit) for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.Z(target=qubit, control=qubits[ind]) for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 10: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.Z(target=qubit, control=qubits[ind]) circuit += tq_g.Z(target=qubits[0], control=qubits[-1]) for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 11: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: circuit += tq_g.X(target=qubits[ind+1], control=control) for ind, qubit in enumerate(qubits[1:-1]): variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: circuit += tq_g.X(target=qubits[ind+1], control=control) return circuit elif circuit_id == 12: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: circuit += tq_g.Z(target=qubits[ind+1], control=control) for ind, control in enumerate(qubits[1:-1]): variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = control) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = control) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: circuit += tq_g.Z(target=qubits[ind+1], control=control) return circuit elif circuit_id == 13: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubit, control=qubits[ind]) count += 1 variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubits[0], control=qubits[-1]) count += 1 for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=qubit, target=qubits[ind]) count += 1 variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=qubits[0], target=qubits[-1]) count += 1 return circuit elif circuit_id == 14: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubit, control=qubits[ind]) count += 1 variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubits[0], control=qubits[-1]) count += 1 for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=qubit, target=qubits[ind]) count += 1 variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=qubits[0], target=qubits[-1]) count += 1 return circuit elif circuit_id == 15: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.X(target=qubit, control=qubits[ind]) circuit += tq_g.X(control=qubits[-1], target=qubits[0]) for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.X(control=qubit, target=qubits[ind]) circuit += tq_g.X(target=qubits[-1], control=qubits[0]) return circuit elif circuit_id == 16: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=control, target=qubits[ind+1]) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=control, target=qubits[ind+1]) count += 1 return circuit elif circuit_id == 17: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=control, target=qubits[ind+1]) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=control, target=qubits[ind+1]) count += 1 return circuit elif circuit_id == 18: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[:-1]): variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubit, control=qubits[ind+1]) count += 1 variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubits[-1], control=qubits[0]) count += 1 return circuit elif circuit_id == 19: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[:-1]): variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubit, control=qubits[ind+1]) count += 1 variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubits[-1], control=qubits[0]) count += 1 return circuit
18,425
45.530303
172
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_0.6/grad_hacked.py
from tequila.circuit.compiler import CircuitCompiler from tequila.objective.objective import Objective, ExpectationValueImpl, Variable, \ assign_variable, identity, FixedVariable from tequila import TequilaException from tequila.objective import QTensor from tequila.simulators.simulator_api import compile import typing from numpy import vectorize from tequila.autograd_imports import jax, __AUTOGRAD__BACKEND__ def grad(objective: typing.Union[Objective, QTensor], variable: Variable = None, no_compile=False, *args, **kwargs): ''' wrapper function for getting the gradients of Objectives,ExpectationValues, Unitaries (including single gates), and Transforms. :param obj (QCircuit,ParametrizedGateImpl,Objective,ExpectationValue,Transform,Variable): structure to be differentiated :param variables (list of Variable): parameter with respect to which obj should be differentiated. default None: total gradient. return: dictionary of Objectives, if called on gate, circuit, exp.value, or objective; if Variable or Transform, returns number. ''' if variable is None: # None means that all components are created variables = objective.extract_variables() result = {} if len(variables) == 0: raise TequilaException("Error in gradient: Objective has no variables") for k in variables: assert (k is not None) result[k] = grad(objective, k, no_compile=no_compile) return result else: variable = assign_variable(variable) if isinstance(objective, QTensor): f = lambda x: grad(objective=x, variable=variable, *args, **kwargs) ff = vectorize(f) return ff(objective) if variable not in objective.extract_variables(): return Objective() if no_compile: compiled = objective else: compiler = CircuitCompiler(multitarget=True, trotterized=True, hadamard_power=True, power=True, controlled_phase=True, controlled_rotation=True, gradient_mode=True) compiled = compiler(objective, variables=[variable]) if variable not in compiled.extract_variables(): raise TequilaException("Error in taking gradient. Objective does not depend on variable {} ".format(variable)) if isinstance(objective, ExpectationValueImpl): return __grad_expectationvalue(E=objective, variable=variable) elif objective.is_expectationvalue(): return __grad_expectationvalue(E=compiled.args[-1], variable=variable) elif isinstance(compiled, Objective) or (hasattr(compiled, "args") and hasattr(compiled, "transformation")): return __grad_objective(objective=compiled, variable=variable) else: raise TequilaException("Gradient not implemented for other types than ExpectationValue and Objective.") def __grad_objective(objective: Objective, variable: Variable): args = objective.args transformation = objective.transformation dO = None processed_expectationvalues = {} for i, arg in enumerate(args): if __AUTOGRAD__BACKEND__ == "jax": df = jax.grad(transformation, argnums=i, holomorphic=True) elif __AUTOGRAD__BACKEND__ == "autograd": df = jax.grad(transformation, argnum=i) else: raise TequilaException("Can't differentiate without autograd or jax") # We can detect one simple case where the outer derivative is const=1 if transformation is None or transformation == identity: outer = 1.0 else: outer = Objective(args=args, transformation=df) if hasattr(arg, "U"): # save redundancies if arg in processed_expectationvalues: inner = processed_expectationvalues[arg] else: inner = __grad_inner(arg=arg, variable=variable) processed_expectationvalues[arg] = inner else: # this means this inner derivative is purely variable dependent inner = __grad_inner(arg=arg, variable=variable) if inner == 0.0: # don't pile up zero expectationvalues continue if dO is None: dO = outer * inner else: dO = dO + outer * inner if dO is None: raise TequilaException("caught None in __grad_objective") return dO # def __grad_vector_objective(objective: Objective, variable: Variable): # argsets = objective.argsets # transformations = objective._transformations # outputs = [] # for pos in range(len(objective)): # args = argsets[pos] # transformation = transformations[pos] # dO = None # # processed_expectationvalues = {} # for i, arg in enumerate(args): # if __AUTOGRAD__BACKEND__ == "jax": # df = jax.grad(transformation, argnums=i) # elif __AUTOGRAD__BACKEND__ == "autograd": # df = jax.grad(transformation, argnum=i) # else: # raise TequilaException("Can't differentiate without autograd or jax") # # # We can detect one simple case where the outer derivative is const=1 # if transformation is None or transformation == identity: # outer = 1.0 # else: # outer = Objective(args=args, transformation=df) # # if hasattr(arg, "U"): # # save redundancies # if arg in processed_expectationvalues: # inner = processed_expectationvalues[arg] # else: # inner = __grad_inner(arg=arg, variable=variable) # processed_expectationvalues[arg] = inner # else: # # this means this inner derivative is purely variable dependent # inner = __grad_inner(arg=arg, variable=variable) # # if inner == 0.0: # # don't pile up zero expectationvalues # continue # # if dO is None: # dO = outer * inner # else: # dO = dO + outer * inner # # if dO is None: # dO = Objective() # outputs.append(dO) # if len(outputs) == 1: # return outputs[0] # return outputs def __grad_inner(arg, variable): ''' a modified loop over __grad_objective, which gets derivatives all the way down to variables, return 1 or 0 when a variable is (isnt) identical to var. :param arg: a transform or variable object, to be differentiated :param variable: the Variable with respect to which par should be differentiated. :ivar var: the string representation of variable ''' assert (isinstance(variable, Variable)) if isinstance(arg, Variable): if arg == variable: return 1.0 else: return 0.0 elif isinstance(arg, FixedVariable): return 0.0 elif isinstance(arg, ExpectationValueImpl): return __grad_expectationvalue(arg, variable=variable) elif hasattr(arg, "abstract_expectationvalue"): E = arg.abstract_expectationvalue dE = __grad_expectationvalue(E, variable=variable) return compile(dE, **arg._input_args) else: return __grad_objective(objective=arg, variable=variable) def __grad_expectationvalue(E: ExpectationValueImpl, variable: Variable): ''' implements the analytic partial derivative of a unitary as it would appear in an expectation value. See the paper. :param unitary: the unitary whose gradient should be obtained :param variables (list, dict, str): the variables with respect to which differentiation should be performed. :return: vector (as dict) of dU/dpi as Objective (without hamiltonian) ''' hamiltonian = E.H unitary = E.U if not (unitary.verify()): raise TequilaException("error in grad_expectationvalue unitary is {}".format(unitary)) # fast return if possible if variable not in unitary.extract_variables(): return 0.0 param_gates = unitary._parameter_map[variable] dO = Objective() for idx_g in param_gates: idx, g = idx_g dOinc = __grad_shift_rule(unitary, g, idx, variable, hamiltonian) dO += dOinc assert dO is not None return dO def __grad_shift_rule(unitary, g, i, variable, hamiltonian): ''' function for getting the gradients of directly differentiable gates. Expects precompiled circuits. :param unitary: QCircuit: the QCircuit object containing the gate to be differentiated :param g: a parametrized: the gate being differentiated :param i: Int: the position in unitary at which g appears :param variable: Variable or String: the variable with respect to which gate g is being differentiated :param hamiltonian: the hamiltonian with respect to which unitary is to be measured, in the case that unitary is contained within an ExpectationValue :return: an Objective, whose calculation yields the gradient of g w.r.t variable ''' # possibility for overwride in custom gate construction if hasattr(g, "shifted_gates"): inner_grad = __grad_inner(g.parameter, variable) shifted = g.shifted_gates() dOinc = Objective() for x in shifted: w, g = x Ux = unitary.replace_gates(positions=[i], circuits=[g]) wx = w * inner_grad Ex = Objective.ExpectationValue(U=Ux, H=hamiltonian) dOinc += wx * Ex return dOinc else: raise TequilaException('No shift found for gate {}\nWas the compiler called?'.format(g))
9,886
38.548
132
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_0.6/vqe_utils.py
import tequila as tq import numpy as np from hacked_openfermion_qubit_operator import ParamQubitHamiltonian from openfermion import QubitOperator from HEA import * def get_ansatz_circuit(ansatz_type, geometry, basis_set=None, trotter_steps = 1, name=None, circuit_id=None,num_layers=1): """ This function generates the ansatz for the molecule and the Hamiltonian param: ansatz_type (str) -> the type of the ansatz ('UCCSD, UpCCGSD, SPA, HEA') param: geometry (str) -> the geometry of the molecule param: basis_set (str) -> the basis set for wchich the ansatz has to generated param: trotter_steps (int) -> the number of trotter step to be used in the trotter decomposition param: name (str) -> the name for the madness molecule param: circuit_id (int) -> the type of hardware efficient ansatz param: num_layers (int) -> the number of layers of the HEA e.g.: input: ansatz_type -> "UCCSD" geometry -> "H 0.0 0.0 0.0\nH 0.0 0.0 0.714" basis_set -> 'sto-3g' trotter_steps -> 1 name -> None circuit_id -> None num_layers -> 1 returns: ucc_ansatz (tq.QCircuit()) -> a circuit printed below: circuit: FermionicExcitation(target=(0, 1, 2, 3), control=(), parameter=Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = []) FermionicExcitation(target=(0, 1, 2, 3), control=(), parameter=Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = []) Hamiltonian (tq.QubitHamiltonian()) -> -0.0621+0.1755Z(0)+0.1755Z(1)-0.2358Z(2)-0.2358Z(3)+0.1699Z(0)Z(1) +0.0449Y(0)X(1)X(2)Y(3)-0.0449Y(0)Y(1)X(2)X(3)-0.0449X(0)X(1)Y(2)Y(3) +0.0449X(0)Y(1)Y(2)X(3)+0.1221Z(0)Z(2)+0.1671Z(0)Z(3)+0.1671Z(1)Z(2) +0.1221Z(1)Z(3)+0.1756Z(2)Z(3) fci_ener (float) -> """ ham = tq.QubitHamiltonian() fci_ener = 0.0 ansatz = tq.QCircuit() if ansatz_type == "UCCSD": molecule = tq.Molecule(geometry=geometry, basis_set=basis_set) ansatz = molecule.make_uccsd_ansatz(trotter_steps) ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy(method="fci") elif ansatz_type == "UCCS": molecule = tq.Molecule(geometry=geometry, basis_set=basis_set, backend='psi4') ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy("fci") indices = molecule.make_upccgsd_indices(key='UCCS') print("indices are:", indices) ansatz = molecule.make_upccgsd_layer(indices=indices, include_singles=True, include_doubles=False) elif ansatz_type == "UpCCGSD": molecule = tq.Molecule(name=name, geometry=geometry, n_pno=None) ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy("fci") ansatz = molecule.make_upccgsd_ansatz() elif ansatz_type == "SPA": molecule = tq.Molecule(name=name, geometry=geometry, n_pno=None) ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy("fci") ansatz = molecule.make_upccgsd_ansatz(name="SPA") elif ansatz_type == "HEA": molecule = tq.Molecule(geometry=geometry, basis_set=basis_set) ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy(method="fci") ansatz = generate_HEA(molecule.n_orbitals * 2, circuit_id) else: raise Exception("not implemented any other ansatz, please choose from 'UCCSD, UpCCGSD, SPA, HEA'") return ansatz, ham, fci_ener def get_generator_for_gates(unitary): """ This function takes a unitary gate and returns the generator of the the gate so that it can be padded to the Hamiltonian param: unitary (tq.QGateImpl()) -> the unitary circuit element that has to be converted to a paulistring e.g.: input: unitary -> a FermionicGateImpl object as the one printed below FermionicExcitation(target=(0, 1, 2, 3), control=(), parameter=Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = []) returns: parameter (tq.Variable()) -> (1, 0, 1, 0) generator (tq.QubitHamiltonian()) -> -0.1250Y(0)Y(1)Y(2)X(3)+0.1250Y(0)X(1)Y(2)Y(3) +0.1250X(0)X(1)Y(2)X(3)+0.1250X(0)Y(1)Y(2)Y(3) -0.1250Y(0)X(1)X(2)X(3)-0.1250Y(0)Y(1)X(2)Y(3) -0.1250X(0)Y(1)X(2)X(3)+0.1250X(0)X(1)X(2)Y(3) null_proj (tq.QubitHamiltonian()) -> -0.1250Z(0)Z(1)+0.1250Z(1)Z(3)+0.1250Z(0)Z(3) +0.1250Z(1)Z(2)+0.1250Z(0)Z(2)-0.1250Z(2)Z(3) -0.1250Z(0)Z(1)Z(2)Z(3) """ try: parameter = None generator = None null_proj = None if isinstance(unitary, tq.quantumchemistry.qc_base.FermionicGateImpl): parameter = unitary.extract_variables() generator = unitary.generator null_proj = unitary.p0 else: #getting parameter if unitary.is_parametrized(): parameter = unitary.extract_variables() else: parameter = [None] try: generator = unitary.make_generator(include_controls=True) except: generator = unitary.generator() """if len(parameter) == 0: parameter = [tq.objective.objective.assign_variable(unitary.parameter)]""" return parameter[0], generator, null_proj except Exception as e: print("An Exception happened, details :",e) pass def fold_unitary_into_hamiltonian(unitary, Hamiltonian): """ This function return a list of the resulting Hamiltonian terms after folding the paulistring correspondig to the unitary into the Hamiltonian param: unitary (tq.QGateImpl()) -> the unitary to be folded into the Hamiltonian param: Hamiltonian (ParamQubitHamiltonian()) -> the Hamiltonian of the system e.g.: input: unitary -> a FermionicGateImpl object as the one printed below FermionicExcitation(target=(0, 1, 2, 3), control=(), parameter=Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = []) Hamiltonian -> -0.06214952615456104 [] + -0.044941923860490916 [X0 X1 Y2 Y3] + 0.044941923860490916 [X0 Y1 Y2 X3] + 0.044941923860490916 [Y0 X1 X2 Y3] + -0.044941923860490916 [Y0 Y1 X2 X3] + 0.17547360045040505 [Z0] + 0.16992958569230643 [Z0 Z1] + 0.12212314332112947 [Z0 Z2] + 0.1670650671816204 [Z0 Z3] + 0.17547360045040508 [Z1] + 0.1670650671816204 [Z1 Z2] + 0.12212314332112947 [Z1 Z3] + -0.23578915712819945 [Z2] + 0.17561918557144712 [Z2 Z3] + -0.23578915712819945 [Z3] returns: folded_hamiltonian (ParamQubitHamiltonian()) -> Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [X0 X1 X2 X3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [X0 X1 Y2 Y3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [X0 Y1 X2 Y3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [X0 Y1 Y2 X3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Y0 X1 X2 Y3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Y0 X1 Y2 X3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Y0 Y1 X2 X3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Y0 Y1 Y2 Y3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z1] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z1 Z2] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z1 Z2 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z1 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z2] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z2 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z1] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z1 Z2] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z1 Z2 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z1 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z2] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z2 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z3] """ folded_hamiltonian = ParamQubitHamiltonian() if isinstance(unitary, tq.circuit._gates_impl.DifferentiableGateImpl) and not isinstance(unitary, tq.circuit._gates_impl.PhaseGateImpl): variable, generator, null_proj = get_generator_for_gates(unitary) # print(generator) # print(null_proj) #converting into ParamQubitHamiltonian() c_generator = convert_tq_QH_to_PQH(generator) """c_null_proj = convert_tq_QH_to_PQH(null_proj) print(variable) prod1 = (null_proj*ham*generator - generator*ham*null_proj) print(prod1) #print((Hamiltonian*c_generator)) prod2 = convert_PQH_to_tq_QH(c_null_proj*Hamiltonian*c_generator - c_generator*Hamiltonian*c_null_proj)({var:0.1 for var in variable.extract_variables()}) print(prod2) assert prod1 ==prod2 raise Exception("testing")""" #print("starting", flush=True) #handling the parameterize gates if variable is not None: #print("folding generator") # adding the term: cos^2(\theta)*H temp_ham = ParamQubitHamiltonian().identity() temp_ham *= Hamiltonian temp_ham *= (variable.apply(tq.numpy.cos)**2) #print(convert_PQH_to_tq_QH(temp_ham)({var:1. for var in variable.extract_variables()})) folded_hamiltonian += temp_ham #print("step1 done", flush=True) # adding the term: sin^2(\theta)*G*H*G temp_ham = ParamQubitHamiltonian().identity() temp_ham *= c_generator temp_ham *= Hamiltonian temp_ham *= c_generator temp_ham *= (variable.apply(tq.numpy.sin)**2) #print(convert_PQH_to_tq_QH(temp_ham)({var:1. for var in variable.extract_variables()})) folded_hamiltonian += temp_ham #print("step2 done", flush=True) # adding the term: i*cos^2(\theta)8sin^2(\theta)*(G*H -H*G) temp_ham1 = ParamQubitHamiltonian().identity() temp_ham1 *= c_generator temp_ham1 *= Hamiltonian temp_ham2 = ParamQubitHamiltonian().identity() temp_ham2 *= Hamiltonian temp_ham2 *= c_generator temp_ham = temp_ham1 - temp_ham2 temp_ham *= 1.0j temp_ham *= variable.apply(tq.numpy.sin) * variable.apply(tq.numpy.cos) #print(convert_PQH_to_tq_QH(temp_ham)({var:1. for var in variable.extract_variables()})) folded_hamiltonian += temp_ham #print("step3 done", flush=True) #handling the non-paramterized gates else: raise Exception("This function is not implemented yet") # adding the term: G*H*G folded_hamiltonian += c_generator*Hamiltonian*c_generator #print("Halfway there", flush=True) #handle the FermionicGateImpl gates if null_proj is not None: print("folding null projector") c_null_proj = convert_tq_QH_to_PQH(null_proj) #print("step4 done", flush=True) # adding the term: (1-cos(\theta))^2*P0*H*P0 temp_ham = ParamQubitHamiltonian().identity() temp_ham *= c_null_proj temp_ham *= Hamiltonian temp_ham *= c_null_proj temp_ham *= ((1-variable.apply(tq.numpy.cos))**2) folded_hamiltonian += temp_ham #print("step5 done", flush=True) # adding the term: 2*cos(\theta)*(1-cos(\theta))*(P0*H +H*P0) temp_ham1 = ParamQubitHamiltonian().identity() temp_ham1 *= c_null_proj temp_ham1 *= Hamiltonian temp_ham2 = ParamQubitHamiltonian().identity() temp_ham2 *= Hamiltonian temp_ham2 *= c_null_proj temp_ham = temp_ham1 + temp_ham2 temp_ham *= (variable.apply(tq.numpy.cos)*(1-variable.apply(tq.numpy.cos))) folded_hamiltonian += temp_ham #print("step6 done", flush=True) # adding the term: i*sin(\theta)*(1-cos(\theta))*(G*H*P0 - P0*H*G) temp_ham1 = ParamQubitHamiltonian().identity() temp_ham1 *= c_generator temp_ham1 *= Hamiltonian temp_ham1 *= c_null_proj temp_ham2 = ParamQubitHamiltonian().identity() temp_ham2 *= c_null_proj temp_ham2 *= Hamiltonian temp_ham2 *= c_generator temp_ham = temp_ham1 - temp_ham2 temp_ham *= 1.0j temp_ham *= (variable.apply(tq.numpy.sin)*(1-variable.apply(tq.numpy.cos))) folded_hamiltonian += temp_ham #print("step7 done", flush=True) elif isinstance(unitary, tq.circuit._gates_impl.PhaseGateImpl): if np.isclose(unitary.parameter, np.pi/2.0): return Hamiltonian._clifford_simplify_s(unitary.qubits[0]) elif np.isclose(unitary.parameter, -1.*np.pi/2.0): return Hamiltonian._clifford_simplify_s_dag(unitary.qubits[0]) else: raise Exception("Only DifferentiableGateImpl, PhaseGateImpl(S), Pauligate(X,Y,Z), Controlled(X,Y,Z) and Hadamrd(H) implemented yet") elif isinstance(unitary, tq.circuit._gates_impl.QGateImpl): if unitary.is_controlled(): if unitary.name == "X": return Hamiltonian._clifford_simplify_control_g("X", unitary.control[0], unitary.target[0]) elif unitary.name == "Y": return Hamiltonian._clifford_simplify_control_g("Y", unitary.control[0], unitary.target[0]) elif unitary.name == "Z": return Hamiltonian._clifford_simplify_control_g("Z", unitary.control[0], unitary.target[0]) else: raise Exception("Only DifferentiableGateImpl, PhaseGateImpl(S), Pauligate(X,Y,Z), Controlled(X,Y,Z) and Hadamrd(H) implemented yet") else: if unitary.name == "X": gate = convert_tq_QH_to_PQH(tq.paulis.X(unitary.qubits[0])) return gate*Hamiltonian*gate elif unitary.name == "Y": gate = convert_tq_QH_to_PQH(tq.paulis.Y(unitary.qubits[0])) return gate*Hamiltonian*gate elif unitary.name == "Z": gate = convert_tq_QH_to_PQH(tq.paulis.Z(unitary.qubits[0])) return gate*Hamiltonian*gate elif unitary.name == "H": return Hamiltonian._clifford_simplify_h(unitary.qubits[0]) else: raise Exception("Only DifferentiableGateImpl, PhaseGateImpl(S), Pauligate(X,Y,Z), Controlled(X,Y,Z) and Hadamrd(H) implemented yet") else: raise Exception("Only DifferentiableGateImpl, PhaseGateImpl(S), Pauligate(X,Y,Z), Controlled(X,Y,Z) and Hadamrd(H) implemented yet") return folded_hamiltonian def convert_tq_QH_to_PQH(Hamiltonian): """ This function takes the tequila QubitHamiltonian object and converts into a ParamQubitHamiltonian object. param: Hamiltonian (tq.QubitHamiltonian()) -> the Hamiltonian to be converted e.g: input: Hamiltonian -> -0.0621+0.1755Z(0)+0.1755Z(1)-0.2358Z(2)-0.2358Z(3)+0.1699Z(0)Z(1) +0.0449Y(0)X(1)X(2)Y(3)-0.0449Y(0)Y(1)X(2)X(3)-0.0449X(0)X(1)Y(2)Y(3) +0.0449X(0)Y(1)Y(2)X(3)+0.1221Z(0)Z(2)+0.1671Z(0)Z(3)+0.1671Z(1)Z(2) +0.1221Z(1)Z(3)+0.1756Z(2)Z(3) returns: param_hamiltonian (ParamQubitHamiltonian()) -> -0.06214952615456104 [] + -0.044941923860490916 [X0 X1 Y2 Y3] + 0.044941923860490916 [X0 Y1 Y2 X3] + 0.044941923860490916 [Y0 X1 X2 Y3] + -0.044941923860490916 [Y0 Y1 X2 X3] + 0.17547360045040505 [Z0] + 0.16992958569230643 [Z0 Z1] + 0.12212314332112947 [Z0 Z2] + 0.1670650671816204 [Z0 Z3] + 0.17547360045040508 [Z1] + 0.1670650671816204 [Z1 Z2] + 0.12212314332112947 [Z1 Z3] + -0.23578915712819945 [Z2] + 0.17561918557144712 [Z2 Z3] + -0.23578915712819945 [Z3] """ param_hamiltonian = ParamQubitHamiltonian() Hamiltonian = Hamiltonian.to_openfermion() for term in Hamiltonian.terms: param_hamiltonian += ParamQubitHamiltonian(term = term, coefficient = Hamiltonian.terms[term]) return param_hamiltonian class convert_PQH_to_tq_QH: def __init__(self, Hamiltonian): self.param_hamiltonian = Hamiltonian def __call__(self,variables=None): """ This function takes the ParamQubitHamiltonian object and converts into a tequila QubitHamiltonian object. param: param_hamiltonian (ParamQubitHamiltonian()) -> the Hamiltonian to be converted param: variables (dict) -> a dictionary with the values of the variables in the Hamiltonian coefficient e.g: input: param_hamiltonian -> a [Y0 X2 Z3] + b [Z0 X2 Z3] variables -> {"a":1,"b":2} returns: Hamiltonian (tq.QubitHamiltonian()) -> +1.0000Y(0)X(2)Z(3)+2.0000Z(0)X(2)Z(3) """ Hamiltonian = tq.QubitHamiltonian() for term in self.param_hamiltonian.terms: val = self.param_hamiltonian.terms[term]# + self.param_hamiltonian.imag_terms[term]*1.0j if isinstance(val, tq.Variable) or isinstance(val, tq.objective.objective.Objective): try: for key in variables.keys(): variables[key] = variables[key] #print(variables) val = val(variables) #print(val) except Exception as e: print(e) raise Exception("You forgot to pass the dictionary with the values of the variables") Hamiltonian += tq.QubitHamiltonian(QubitOperator(term=term, coefficient=val)) return Hamiltonian def _construct_derivatives(self, variables=None): """ """ derivatives = {} variable_names = [] for term in self.param_hamiltonian.terms: val = self.param_hamiltonian.terms[term]# + self.param_hamiltonian.imag_terms[term]*1.0j #print(val) if isinstance(val, tq.Variable) or isinstance(val, tq.objective.objective.Objective): variable = val.extract_variables() for var in list(variable): from grad_hacked import grad derivative = ParamQubitHamiltonian(term = term, coefficient = grad(val, var)) if var not in variable_names: variable_names.append(var) if var not in list(derivatives.keys()): derivatives[var] = derivative else: derivatives[var] += derivative return variable_names, derivatives def get_geometry(name, b_l): """ This is utility fucntion that generates tehe geometry string of a Molecule param: name (str) -> name of the molecule param: b_l (float) -> the bond length of the molecule e.g.: input: name -> "H2" b_l -> 0.714 returns: geo_str (str) -> "H 0.0 0.0 0.0\nH 0.0 0.0 0.714" """ geo_str = None if name == "LiH": geo_str = "H 0.0 0.0 0.0\nLi 0.0 0.0 {0}".format(b_l) elif name == "H2": geo_str = "H 0.0 0.0 0.0\nH 0.0 0.0 {0}".format(b_l) elif name == "BeH2": geo_str = "H 0.0 0.0 {0}\nH 0.0 0.0 {1}\nBe 0.0 0.0 0.0".format(b_l,-1*b_l) elif name == "N2": geo_str = "N 0.0 0.0 0.0\nN 0.0 0.0 {0}".format(b_l) elif name == "H4": geo_str = "H 0.0 0.0 0.0\nH 0.0 0.0 {0}\nH 0.0 0.0 {1}\nH 0.0 0.0 {2}".format(b_l,-1*b_l,2*b_l) return geo_str
27,934
51.807183
162
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_0.6/hacked_openfermion_symbolic_operator.py
import abc import copy import itertools import re import warnings import sympy import tequila as tq from tequila.objective.objective import Objective, Variable from openfermion.config import EQ_TOLERANCE COEFFICIENT_TYPES = (int, float, complex, sympy.Expr, Variable, Objective) class SymbolicOperator(metaclass=abc.ABCMeta): """Base class for FermionOperator and QubitOperator. A SymbolicOperator stores an object which represents a weighted sum of terms; each term is a product of individual factors of the form (`index`, `action`), where `index` is a nonnegative integer and the possible values for `action` are determined by the subclass. For instance, for the subclass FermionOperator, `action` can be 1 or 0, indicating raising or lowering, and for QubitOperator, `action` is from the set {'X', 'Y', 'Z'}. The coefficients of the terms are stored in a dictionary whose keys are the terms. SymbolicOperators of the same type can be added or multiplied together. Note: Adding SymbolicOperators is faster using += (as this is done by in-place addition). Specifying the coefficient during initialization is faster than multiplying a SymbolicOperator with a scalar. Attributes: actions (tuple): A tuple of objects representing the possible actions. e.g. for FermionOperator, this is (1, 0). action_strings (tuple): A tuple of string representations of actions. These should be in one-to-one correspondence with actions and listed in the same order. e.g. for FermionOperator, this is ('^', ''). action_before_index (bool): A boolean indicating whether in string representations, the action should come before the index. different_indices_commute (bool): A boolean indicating whether factors acting on different indices commute. terms (dict): **key** (tuple of tuples): A dictionary storing the coefficients of the terms in the operator. The keys are the terms. A term is a product of individual factors; each factor is represented by a tuple of the form (`index`, `action`), and these tuples are collected into a larger tuple which represents the term as the product of its factors. """ @staticmethod def _issmall(val, tol=EQ_TOLERANCE): '''Checks whether a value is near-zero Parses the allowed coefficients above for near-zero tests. Args: val (COEFFICIENT_TYPES) -- the value to be tested tol (float) -- tolerance for inequality ''' if isinstance(val, sympy.Expr): if sympy.simplify(abs(val) < tol) == True: return True return False if isinstance(val, tq.Variable) or isinstance(val, tq.objective.objective.Objective): return False if abs(val) < tol: return True return False @abc.abstractproperty def actions(self): """The allowed actions. Returns a tuple of objects representing the possible actions. """ pass @abc.abstractproperty def action_strings(self): """The string representations of the allowed actions. Returns a tuple containing string representations of the possible actions, in the same order as the `actions` property. """ pass @abc.abstractproperty def action_before_index(self): """Whether action comes before index in string representations. Example: For QubitOperator, the actions are ('X', 'Y', 'Z') and the string representations look something like 'X0 Z2 Y3'. So the action comes before the index, and this function should return True. For FermionOperator, the string representations look like '0^ 1 2^ 3'. The action comes after the index, so this function should return False. """ pass @abc.abstractproperty def different_indices_commute(self): """Whether factors acting on different indices commute.""" pass __hash__ = None def __init__(self, term=None, coefficient=1.): if not isinstance(coefficient, COEFFICIENT_TYPES): raise ValueError('Coefficient must be a numeric type.') # Initialize the terms dictionary self.terms = {} # Detect if the input is the string representation of a sum of terms; # if so, initialization needs to be handled differently if isinstance(term, str) and '[' in term: self._long_string_init(term, coefficient) return # Zero operator: leave the terms dictionary empty if term is None: return # Parse the term # Sequence input if isinstance(term, (list, tuple)): term = self._parse_sequence(term) # String input elif isinstance(term, str): term = self._parse_string(term) # Invalid input type else: raise ValueError('term specified incorrectly.') # Simplify the term coefficient, term = self._simplify(term, coefficient=coefficient) # Add the term to the dictionary self.terms[term] = coefficient def _long_string_init(self, long_string, coefficient): r""" Initialization from a long string representation. e.g. For FermionOperator: '1.5 [2^ 3] + 1.4 [3^ 0]' """ pattern = r'(.*?)\[(.*?)\]' # regex for a term for match in re.findall(pattern, long_string, flags=re.DOTALL): # Determine the coefficient for this term coef_string = re.sub(r"\s+", "", match[0]) if coef_string and coef_string[0] == '+': coef_string = coef_string[1:].strip() if coef_string == '': coef = 1.0 elif coef_string == '-': coef = -1.0 else: try: if 'j' in coef_string: if coef_string[0] == '-': coef = -complex(coef_string[1:]) else: coef = complex(coef_string) else: coef = float(coef_string) except ValueError: raise ValueError( 'Invalid coefficient {}.'.format(coef_string)) coef *= coefficient # Parse the term, simpify it and add to the dict term = self._parse_string(match[1]) coef, term = self._simplify(term, coefficient=coef) if term not in self.terms: self.terms[term] = coef else: self.terms[term] += coef def _validate_factor(self, factor): """Check that a factor of a term is valid.""" if len(factor) != 2: raise ValueError('Invalid factor {}.'.format(factor)) index, action = factor if action not in self.actions: raise ValueError('Invalid action in factor {}. ' 'Valid actions are: {}'.format( factor, self.actions)) if not isinstance(index, int) or index < 0: raise ValueError('Invalid index in factor {}. ' 'The index should be a non-negative ' 'integer.'.format(factor)) def _simplify(self, term, coefficient=1.0): """Simplifies a term.""" if self.different_indices_commute: term = sorted(term, key=lambda factor: factor[0]) return coefficient, tuple(term) def _parse_sequence(self, term): """Parse a term given as a sequence type (i.e., list, tuple, etc.). e.g. For QubitOperator: [('X', 2), ('Y', 0), ('Z', 3)] -> (('Y', 0), ('X', 2), ('Z', 3)) """ if not term: # Empty sequence return () elif isinstance(term[0], int): # Single factor self._validate_factor(term) return (tuple(term),) else: # Check that all factors in the term are valid for factor in term: self._validate_factor(factor) # Return a tuple return tuple(term) def _parse_string(self, term): """Parse a term given as a string. e.g. For FermionOperator: "2^ 3" -> ((2, 1), (3, 0)) """ factors = term.split() # Convert the string representations of the factors to tuples processed_term = [] for factor in factors: # Get the index and action string if self.action_before_index: # The index is at the end of the string; find where it starts. if not factor[-1].isdigit(): raise ValueError('Invalid factor {}.'.format(factor)) index_start = len(factor) - 1 while index_start > 0 and factor[index_start - 1].isdigit(): index_start -= 1 if factor[index_start - 1] == '-': raise ValueError('Invalid index in factor {}. ' 'The index should be a non-negative ' 'integer.'.format(factor)) index = int(factor[index_start:]) action_string = factor[:index_start] else: # The index is at the beginning of the string; find where # it ends if factor[0] == '-': raise ValueError('Invalid index in factor {}. ' 'The index should be a non-negative ' 'integer.'.format(factor)) if not factor[0].isdigit(): raise ValueError('Invalid factor {}.'.format(factor)) index_end = 1 while (index_end <= len(factor) - 1 and factor[index_end].isdigit()): index_end += 1 index = int(factor[:index_end]) action_string = factor[index_end:] # Convert the action string to an action if action_string in self.action_strings: action = self.actions[self.action_strings.index(action_string)] else: raise ValueError('Invalid action in factor {}. ' 'Valid actions are: {}'.format( factor, self.action_strings)) # Add the factor to the list as a tuple processed_term.append((index, action)) # Return a tuple return tuple(processed_term) @property def constant(self): """The value of the constant term.""" return self.terms.get((), 0.0) @constant.setter def constant(self, value): self.terms[()] = value @classmethod def zero(cls): """ Returns: additive_identity (SymbolicOperator): A symbolic operator o with the property that o+x = x+o = x for all operators x of the same class. """ return cls(term=None) @classmethod def identity(cls): """ Returns: multiplicative_identity (SymbolicOperator): A symbolic operator u with the property that u*x = x*u = x for all operators x of the same class. """ return cls(term=()) def __str__(self): """Return an easy-to-read string representation.""" if not self.terms: return '0' string_rep = '' for term, coeff in sorted(self.terms.items()): if self._issmall(coeff): continue tmp_string = '{} ['.format(coeff) for factor in term: index, action = factor action_string = self.action_strings[self.actions.index(action)] if self.action_before_index: tmp_string += '{}{} '.format(action_string, index) else: tmp_string += '{}{} '.format(index, action_string) string_rep += '{}] +\n'.format(tmp_string.strip()) return string_rep[:-3] def __repr__(self): return str(self) def __imul__(self, multiplier): """In-place multiply (*=) with scalar or operator of the same type. Default implementation is to multiply coefficients and concatenate terms. Args: multiplier(complex float, or SymbolicOperator): multiplier Returns: product (SymbolicOperator): Mutated self. """ # Handle scalars. if isinstance(multiplier, COEFFICIENT_TYPES): for term in self.terms: self.terms[term] *= multiplier return self # Handle operator of the same type elif isinstance(multiplier, self.__class__): result_terms = dict() for left_term in self.terms: for right_term in multiplier.terms: left_coefficient = self.terms[left_term] right_coefficient = multiplier.terms[right_term] new_coefficient = left_coefficient * right_coefficient new_term = left_term + right_term new_coefficient, new_term = self._simplify( new_term, coefficient=new_coefficient) # Update result dict. if new_term in result_terms: result_terms[new_term] += new_coefficient else: result_terms[new_term] = new_coefficient self.terms = result_terms return self # Invalid multiplier type else: raise TypeError('Cannot multiply {} with {}'.format( self.__class__.__name__, multiplier.__class__.__name__)) def __mul__(self, multiplier): """Return self * multiplier for a scalar, or a SymbolicOperator. Args: multiplier: A scalar, or a SymbolicOperator. Returns: product (SymbolicOperator) Raises: TypeError: Invalid type cannot be multiply with SymbolicOperator. """ if isinstance(multiplier, COEFFICIENT_TYPES + (type(self),)): product = copy.deepcopy(self) product *= multiplier return product else: raise TypeError('Object of invalid type cannot multiply with ' + type(self) + '.') def __iadd__(self, addend): """In-place method for += addition of SymbolicOperator. Args: addend (SymbolicOperator, or scalar): The operator to add. If scalar, adds to the constant term Returns: sum (SymbolicOperator): Mutated self. Raises: TypeError: Cannot add invalid type. """ if isinstance(addend, type(self)): for term in addend.terms: self.terms[term] = (self.terms.get(term, 0.0) + addend.terms[term]) if self._issmall(self.terms[term]): del self.terms[term] elif isinstance(addend, COEFFICIENT_TYPES): self.constant += addend else: raise TypeError('Cannot add invalid type to {}.'.format(type(self))) return self def __add__(self, addend): """ Args: addend (SymbolicOperator): The operator to add. Returns: sum (SymbolicOperator) """ summand = copy.deepcopy(self) summand += addend return summand def __radd__(self, addend): """ Args: addend (SymbolicOperator): The operator to add. Returns: sum (SymbolicOperator) """ return self + addend def __isub__(self, subtrahend): """In-place method for -= subtraction of SymbolicOperator. Args: subtrahend (A SymbolicOperator, or scalar): The operator to subtract if scalar, subtracts from the constant term. Returns: difference (SymbolicOperator): Mutated self. Raises: TypeError: Cannot subtract invalid type. """ if isinstance(subtrahend, type(self)): for term in subtrahend.terms: self.terms[term] = (self.terms.get(term, 0.0) - subtrahend.terms[term]) if self._issmall(self.terms[term]): del self.terms[term] elif isinstance(subtrahend, COEFFICIENT_TYPES): self.constant -= subtrahend else: raise TypeError('Cannot subtract invalid type from {}.'.format( type(self))) return self def __sub__(self, subtrahend): """ Args: subtrahend (SymbolicOperator): The operator to subtract. Returns: difference (SymbolicOperator) """ minuend = copy.deepcopy(self) minuend -= subtrahend return minuend def __rsub__(self, subtrahend): """ Args: subtrahend (SymbolicOperator): The operator to subtract. Returns: difference (SymbolicOperator) """ return -1 * self + subtrahend def __rmul__(self, multiplier): """ Return multiplier * self for a scalar. We only define __rmul__ for scalars because the left multiply exist for SymbolicOperator and left multiply is also queried as the default behavior. Args: multiplier: A scalar to multiply by. Returns: product: A new instance of SymbolicOperator. Raises: TypeError: Object of invalid type cannot multiply SymbolicOperator. """ if not isinstance(multiplier, COEFFICIENT_TYPES): raise TypeError('Object of invalid type cannot multiply with ' + type(self) + '.') return self * multiplier def __truediv__(self, divisor): """ Return self / divisor for a scalar. Note: This is always floating point division. Args: divisor: A scalar to divide by. Returns: A new instance of SymbolicOperator. Raises: TypeError: Cannot divide local operator by non-scalar type. """ if not isinstance(divisor, COEFFICIENT_TYPES): raise TypeError('Cannot divide ' + type(self) + ' by non-scalar type.') return self * (1.0 / divisor) def __div__(self, divisor): """ For compatibility with Python 2. """ return self.__truediv__(divisor) def __itruediv__(self, divisor): if not isinstance(divisor, COEFFICIENT_TYPES): raise TypeError('Cannot divide ' + type(self) + ' by non-scalar type.') self *= (1.0 / divisor) return self def __idiv__(self, divisor): """ For compatibility with Python 2. """ return self.__itruediv__(divisor) def __neg__(self): """ Returns: negation (SymbolicOperator) """ return -1 * self def __pow__(self, exponent): """Exponentiate the SymbolicOperator. Args: exponent (int): The exponent with which to raise the operator. Returns: exponentiated (SymbolicOperator) Raises: ValueError: Can only raise SymbolicOperator to non-negative integer powers. """ # Handle invalid exponents. if not isinstance(exponent, int) or exponent < 0: raise ValueError( 'exponent must be a non-negative int, but was {} {}'.format( type(exponent), repr(exponent))) # Initialized identity. exponentiated = self.__class__(()) # Handle non-zero exponents. for _ in range(exponent): exponentiated *= self return exponentiated def __eq__(self, other): """Approximate numerical equality (not true equality).""" return self.isclose(other) def __ne__(self, other): return not (self == other) def __iter__(self): self._iter = iter(self.terms.items()) return self def __next__(self): term, coefficient = next(self._iter) return self.__class__(term=term, coefficient=coefficient) def isclose(self, other, tol=EQ_TOLERANCE): """Check if other (SymbolicOperator) is close to self. Comparison is done for each term individually. Return True if the difference between each term in self and other is less than EQ_TOLERANCE Args: other(SymbolicOperator): SymbolicOperator to compare against. """ if not isinstance(self, type(other)): return NotImplemented # terms which are in both: for term in set(self.terms).intersection(set(other.terms)): a = self.terms[term] b = other.terms[term] if not (isinstance(a, sympy.Expr) or isinstance(b, sympy.Expr)): tol *= max(1, abs(a), abs(b)) if self._issmall(a - b, tol) is False: return False # terms only in one (compare to 0.0 so only abs_tol) for term in set(self.terms).symmetric_difference(set(other.terms)): if term in self.terms: if self._issmall(self.terms[term], tol) is False: return False else: if self._issmall(other.terms[term], tol) is False: return False return True def compress(self, abs_tol=EQ_TOLERANCE): """ Eliminates all terms with coefficients close to zero and removes small imaginary and real parts. Args: abs_tol(float): Absolute tolerance, must be at least 0.0 """ new_terms = {} for term in self.terms: coeff = self.terms[term] if isinstance(coeff, sympy.Expr): if sympy.simplify(sympy.im(coeff) <= abs_tol) == True: coeff = sympy.re(coeff) if sympy.simplify(sympy.re(coeff) <= abs_tol) == True: coeff = 1j * sympy.im(coeff) if (sympy.simplify(abs(coeff) <= abs_tol) != True): new_terms[term] = coeff continue if isinstance(val, tq.Variable) or isinstance(val, tq.objective.objective.Objective): continue # Remove small imaginary and real parts if abs(coeff.imag) <= abs_tol: coeff = coeff.real if abs(coeff.real) <= abs_tol: coeff = 1.j * coeff.imag # Add the term if the coefficient is large enough if abs(coeff) > abs_tol: new_terms[term] = coeff self.terms = new_terms def induced_norm(self, order=1): r""" Compute the induced p-norm of the operator. If we represent an operator as :math: `\sum_{j} w_j H_j` where :math: `w_j` are scalar coefficients then this norm is :math: `\left(\sum_{j} \| w_j \|^p \right)^{\frac{1}{p}} where :math: `p` is the order of the induced norm Args: order(int): the order of the induced norm. """ norm = 0. for coefficient in self.terms.values(): norm += abs(coefficient)**order return norm**(1. / order) def many_body_order(self): """Compute the many-body order of a SymbolicOperator. The many-body order of a SymbolicOperator is the maximum length of a term with nonzero coefficient. Returns: int """ if not self.terms: # Zero operator return 0 else: return max( len(term) for term, coeff in self.terms.items() if (self._issmall(coeff) is False)) @classmethod def accumulate(cls, operators, start=None): """Sums over SymbolicOperators.""" total = copy.deepcopy(start or cls.zero()) for operator in operators: total += operator return total def get_operators(self): """Gets a list of operators with a single term. Returns: operators([self.__class__]): A generator of the operators in self. """ for term, coefficient in self.terms.items(): yield self.__class__(term, coefficient) def get_operator_groups(self, num_groups): """Gets a list of operators with a few terms. Args: num_groups(int): How many operators to get in the end. Returns: operators([self.__class__]): A list of operators summing up to self. """ if num_groups < 1: warnings.warn('Invalid num_groups {} < 1.'.format(num_groups), RuntimeWarning) num_groups = 1 operators = self.get_operators() num_groups = min(num_groups, len(self.terms)) for i in range(num_groups): yield self.accumulate( itertools.islice(operators, len(range(i, len(self.terms), num_groups))))
25,797
35.697013
97
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_2.7/main.py
import tequila as tq import numpy as np from tequila.objective.objective import Variable import openfermion from typing import Union from vqe_utils import convert_PQH_to_tq_QH, convert_tq_QH_to_PQH,\ fold_unitary_into_hamiltonian from energy_optimization import * from do_annealing import * import random # guess we could substitute that with numpy.random #TODO import argparse import pickle as pk import matplotlib.pyplot as plt # Main hyperparameters mu = 2.0 # lognormal dist mean sigma = 0.4 # lognormal dist std T_0 = 1.0 # T_0, initial starting temperature # max_epochs = 25 # num_epochs, max number of iterations max_epochs = 20 # num_epochs, max number of iterations min_epochs = 2 # num_epochs, max number of iterations5 # min_epochs = 20 # num_epochs, max number of iterations tol = 1e-6 # minimum change in energy required, otherwise terminate optimization actions_ratio = [.15, .6, .25] patience = 100 beta = 0.5 max_non_cliffords = 0 type_energy_eval='wfn' num_population = 24 num_offsprings = 20 num_processors = 8 #tuning, input as lists. # parser.add_argument('--alphas', type = float, nargs = '+', help='alpha, temperature decay', required=True) alphas = [0.9] # alpha, temperature decay' #Required be = False h2 = True n2 = False name_prefix = '../../data/' # Construct qubit-Hamiltonian #num_active = 3 #active_orbitals = list(range(num_active)) if be: R1 = rrrr R2 = 2.7 geometry = "be 0.0 0.0 0.0\nh 0.0 0.0 {R1}\nh 0.0 0.0 -{R2}" name = "/h/292/philipps/software/moldata/beh2/beh2_{R1:2.2f}_{R2:2.2f}_180" # adapt of you move data mol = tq.Molecule(name=name.format(R1=R1, R2=R2), geometry=geometry.format(R1=R1,R2=R2), n_pno=None) lqm = mol.local_qubit_map(hcb=False) H = mol.make_hamiltonian().map_qubits(lqm).simplify() #print("FCI ENERGY: ", mol.compute_energy(method="fci")) U_spa = mol.make_upccgsd_ansatz(name="SPA").map_qubits(lqm) U = U_spa elif n2: R1 = rrrr geometry = "N 0.0 0.0 0.0\nN 0.0 0.0 {R1}" # name = "/home/abhinav/matter_lab/moldata/n2/n2_{R1:2.2f}" # adapt of you move data name = "/h/292/philipps/software/moldata/n2/n2_{R1:2.2f}" # adapt of you move data mol = tq.Molecule(name=name.format(R1=R1), geometry=geometry.format(R1=R1), n_pno=None) lqm = mol.local_qubit_map(hcb=False) H = mol.make_hamiltonian().map_qubits(lqm).simplify() # print("FCI ENERGY: ", mol.compute_energy(method="fci")) print("Skip FCI calculation, take old data...") U_spa = mol.make_upccgsd_ansatz(name="SPA").map_qubits(lqm) U = U_spa elif h2: active_orbitals = list(range(3)) mol = tq.Molecule(geometry='H 0.0 0.0 0.0\n H 0.0 0.0 2.7', basis_set='6-31g', active_orbitals=active_orbitals, backend='psi4') H = mol.make_hamiltonian().simplify() print("FCI ENERGY: ", mol.compute_energy(method="fci")) U = mol.make_uccsd_ansatz(trotter_steps=1) # Alternatively, get qubit-Hamiltonian from openfermion/externally # with open("ham_6qubits.txt") as hamstring_file: """if be: with open("ham_beh2_3_3.txt") as hamstring_file: hamstring = hamstring_file.read() #print(hamstring) H = tq.QubitHamiltonian().from_string(string=hamstring, openfermion_format=True) elif h2: with open("ham_6qubits.txt") as hamstring_file: hamstring = hamstring_file.read() #print(hamstring) H = tq.QubitHamiltonian().from_string(string=hamstring, openfermion_format=True)""" n_qubits = len(H.qubits) ''' Option 'wfn': "Shortcut" via wavefunction-optimization using MPO-rep of Hamiltonian Option 'qc': Need to input a proper quantum circuit ''' # Clifford optimization in the context of reduced-size quantum circuits starting_E = 123.456 reference = True if reference: if type_energy_eval.lower() == 'wfn': starting_E, _ = minimize_energy(hamiltonian=H, n_qubits=n_qubits, type_energy_eval='wfn') print('starting energy wfn: {:.5f}'.format(starting_E), flush=True) elif type_energy_eval.lower() == 'qc': starting_E, _ = minimize_energy(hamiltonian=H, n_qubits=n_qubits, type_energy_eval='qc', cluster_circuit=U) print('starting energy spa: {:.5f}'.format(starting_E)) else: raise Exception("type_energy_eval must be either 'wfn' or 'qc', but is", type_energy_eval) starting_E, _ = minimize_energy(hamiltonian=H, n_qubits=n_qubits, type_energy_eval='wfn') """for alpha in alphas: print('Starting optimization, alpha = {:3f}'.format(alpha)) # print('Energy to beat', minimize_energy(H, n_qubits, 'wfn')[0]) simulated_annealing(hamiltonian=H, num_population=num_population, num_offsprings=num_offsprings, num_processors=num_processors, tol=tol, max_epochs=max_epochs, min_epochs=min_epochs, T_0=T_0, alpha=alpha, actions_ratio=actions_ratio, max_non_cliffords=max_non_cliffords, verbose=True, patience=patience, beta=beta, type_energy_eval=type_energy_eval.lower(), cluster_circuit=U, starting_energy=starting_E)""" alter_cliffords = True if alter_cliffords: print("starting to replace cliffords with non-clifford gates to see if that improves the current fitness") replace_cliff_with_non_cliff(hamiltonian=H, num_population=num_population, num_offsprings=num_offsprings, num_processors=num_processors, tol=tol, max_epochs=max_epochs, min_epochs=min_epochs, T_0=T_0, alpha=alphas[0], actions_ratio=actions_ratio, max_non_cliffords=max_non_cliffords, verbose=True, patience=patience, beta=beta, type_energy_eval=type_energy_eval.lower(), cluster_circuit=U, starting_energy=starting_E) # accepted_E, tested_E, decisions, instructions_list, best_instructions, temp, best_E = simulated_annealing(hamiltonian=H, # population=4, # num_mutations=2, # num_processors=1, # tol=opt.tol, max_epochs=opt.max_epochs, # min_epochs=opt.min_epochs, T_0=opt.T_0, alpha=alpha, # mu=opt.mu, sigma=opt.sigma, verbose=True, prev_E = starting_E, patience = 10, beta = 0.5, # energy_eval='qc', # eval_circuit=U # print(best_E) # print(best_instructions) # print(len(accepted_E)) # plt.plot(accepted_E) # plt.show() # #pickling data # data = {'accepted_energies': accepted_E, 'tested_energies': tested_E, # 'decisions': decisions, 'instructions': instructions_list, # 'best_instructions': best_instructions, 'temperature': temp, # 'best_energy': best_E} # f_name = '{}{}_alpha_{:.2f}.pk'.format(opt.name_prefix, r, alpha) # pk.dump(data, open(f_name, 'wb')) # print('Finished optimization, data saved in {}'.format(f_name))
7,368
40.869318
129
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_2.7/my_mpo.py
import numpy as np import tensornetwork as tn from tensornetwork.backends.abstract_backend import AbstractBackend tn.set_default_backend("pytorch") #tn.set_default_backend("numpy") from typing import List, Union, Text, Optional, Any, Type Tensor = Any import tequila as tq import torch EPS = 1e-12 class SubOperator: """ This is just a helper class to store coefficient, operators and positions in an intermediate format """ def __init__(self, coefficient: float, operators: List, positions: List ): self._coefficient = coefficient self._operators = operators self._positions = positions @property def coefficient(self): return self._coefficient @property def operators(self): return self._operators @property def positions(self): return self._positions class MPOContainer: """ Class that handles the MPO. Is able to set values at certain positions, update containers (wannabe-equivalent to dynamic arrays) and compress the MPO """ def __init__(self, n_qubits: int, ): self.n_qubits = n_qubits self.container = [ np.zeros((1,1,2,2), dtype=np.complex) for q in range(self.n_qubits) ] def get_dim(self): """ Returns max dimension of container """ d = 1 for q in range(len(self.container)): d = max(d, self.container[q].shape[0]) return d def set_tensor(self, qubit: int, set_at: list, add_operator: Union[np.ndarray, float]): """ set_at: where to put data """ # Set a matrix if len(set_at) == 2: self.container[qubit][set_at[0],set_at[1],:,:] = add_operator[:,:] # Set specific values elif len(set_at) == 4: self.container[qubit][set_at[0],set_at[1],set_at[2],set_at[3]] =\ add_operator else: raise Exception("set_at needs to be either of length 2 or 4") def update_container(self, qubit: int, update_dir: list, add_operator: np.ndarray): """ This should mimick a dynamic array update_dir: e.g. [1,1,0,0] -> extend dimension along where there's a 1 the last two dimensions are always 2x2 only """ old_shape = self.container[qubit].shape # print(old_shape) if not len(update_dir) == 4: if len(update_dir) == 2: update_dir += [0, 0] else: raise Exception("update_dir needs to be either of length 2 or 4") if update_dir[2] or update_dir[3]: raise Exception("Last two dims must be zero.") new_shape = tuple(update_dir[i]+old_shape[i] for i in range(len(update_dir))) new_tensor = np.zeros(new_shape, dtype=np.complex) # Copy old values new_tensor[:old_shape[0],:old_shape[1],:,:] = self.container[qubit][:,:,:,:] # Add new values new_tensor[new_shape[0]-1,new_shape[1]-1,:,:] = add_operator[:,:] # Overwrite container self.container[qubit] = new_tensor def compress_mpo(self): """ Compression of MPO via SVD """ n_qubits = len(self.container) for q in range(n_qubits): my_shape = self.container[q].shape self.container[q] =\ self.container[q].reshape((my_shape[0], my_shape[1], -1)) # Go forwards for q in range(n_qubits-1): # Apply permutation [0 1 2] -> [0 2 1] my_tensor = np.swapaxes(self.container[q], 1, 2) my_tensor = my_tensor.reshape((-1, my_tensor.shape[2])) # full_matrices flag corresponds to 'econ' -> no zero-singular values u, s, vh = np.linalg.svd(my_tensor, full_matrices=False) # Count the non-zero singular values num_nonzeros = len(np.argwhere(s>EPS)) # Construct matrix from square root of singular values s = np.diag(np.sqrt(s[:num_nonzeros])) u = u[:,:num_nonzeros] vh = vh[:num_nonzeros,:] # Distribute weights to left- and right singular vectors (@ = np.matmul) u = u @ s vh = s @ vh # Apply permutation [0 1 2] -> [0 2 1] u = u.reshape((self.container[q].shape[0],\ self.container[q].shape[2], -1)) self.container[q] = np.swapaxes(u, 1, 2) self.container[q+1] = tn.ncon([vh, self.container[q+1]], [(-1, 1),(1, -2, -3)]) # Go backwards for q in range(n_qubits-1, 0, -1): my_tensor = self.container[q] my_tensor = my_tensor.reshape((self.container[q].shape[0], -1)) # full_matrices flag corresponds to 'econ' -> no zero-singular values u, s, vh = np.linalg.svd(my_tensor, full_matrices=False) # Count the non-zero singular values num_nonzeros = len(np.argwhere(s>EPS)) # Construct matrix from square root of singular values s = np.diag(np.sqrt(s[:num_nonzeros])) u = u[:,:num_nonzeros] vh = vh[:num_nonzeros,:] # Distribute weights to left- and right singular vectors u = u @ s vh = s @ vh self.container[q] = np.reshape(vh, (num_nonzeros, self.container[q].shape[1], self.container[q].shape[2])) self.container[q-1] = tn.ncon([self.container[q-1], u], [(-1, 1, -3),(1, -2)]) for q in range(n_qubits): my_shape = self.container[q].shape self.container[q] = self.container[q].reshape((my_shape[0],\ my_shape[1],2,2)) # TODO maybe make subclass of tn.FiniteMPO if it makes sense #class my_MPO(tn.FiniteMPO): class MyMPO: """ Class building up on tensornetwork FiniteMPO to handle MPO-Hamiltonians """ def __init__(self, hamiltonian: Union[tq.QubitHamiltonian, Text], # tensors: List[Tensor], backend: Optional[Union[AbstractBackend, Text]] = None, n_qubits: Optional[int] = None, name: Optional[Text] = None, maxdim: Optional[int] = 10000) -> None: # TODO: modifiy docstring """ Initialize a finite MPO object Args: tensors: The mpo tensors. backend: An optional backend. Defaults to the defaulf backend of TensorNetwork. name: An optional name for the MPO. """ self.hamiltonian = hamiltonian self.maxdim = maxdim if n_qubits: self._n_qubits = n_qubits else: self._n_qubits = self.get_n_qubits() @property def n_qubits(self): return self._n_qubits def make_mpo_from_hamiltonian(self): intermediate = self.openfermion_to_intermediate() # for i in range(len(intermediate)): # print(intermediate[i].coefficient) # print(intermediate[i].operators) # print(intermediate[i].positions) self.mpo = self.intermediate_to_mpo(intermediate) def openfermion_to_intermediate(self): # Here, have either a QubitHamiltonian or a file with a of-operator # Start with Qubithamiltonian def get_pauli_matrix(string): pauli_matrices = { 'I': np.array([[1, 0], [0, 1]], dtype=np.complex), 'Z': np.array([[1, 0], [0, -1]], dtype=np.complex), 'X': np.array([[0, 1], [1, 0]], dtype=np.complex), 'Y': np.array([[0, -1j], [1j, 0]], dtype=np.complex) } return pauli_matrices[string.upper()] intermediate = [] first = True # Store all paulistrings in intermediate format for paulistring in self.hamiltonian.paulistrings: coefficient = paulistring.coeff # print(coefficient) operators = [] positions = [] # Only first one should be identity -> distribute over all if first and not paulistring.items(): positions += [] operators += [] first = False elif not first and not paulistring.items(): raise Exception("Only first Pauli should be identity.") # Get operators and where they act for k,v in paulistring.items(): positions += [k] operators += [get_pauli_matrix(v)] tmp_op = SubOperator(coefficient=coefficient, operators=operators, positions=positions) intermediate += [tmp_op] # print("len intermediate = num Pauli strings", len(intermediate)) return intermediate def build_single_mpo(self, intermediate, j): # Set MPO Container n_qubits = self._n_qubits mpo = MPOContainer(n_qubits=n_qubits) # *********************************************************************** # Set first entries (of which we know that they are 2x2-matrices) # Typically, this is an identity my_coefficient = intermediate[j].coefficient my_positions = intermediate[j].positions my_operators = intermediate[j].operators for q in range(n_qubits): if not q in my_positions: mpo.set_tensor(qubit=q, set_at=[0,0], add_operator=np.complex(my_coefficient)**(1/n_qubits)* np.eye(2)) elif q in my_positions: my_pos_index = my_positions.index(q) mpo.set_tensor(qubit=q, set_at=[0,0], add_operator=np.complex(my_coefficient)**(1/n_qubits)* my_operators[my_pos_index]) # *********************************************************************** # All other entries # while (j smaller than number of intermediates left) and mpo.dim() <= self.maxdim # Re-write this based on positions keyword! j += 1 while j < len(intermediate) and mpo.get_dim() < self.maxdim: # """ my_coefficient = intermediate[j].coefficient my_positions = intermediate[j].positions my_operators = intermediate[j].operators for q in range(n_qubits): # It is guaranteed that every index appears only once in positions if q == 0: update_dir = [0,1] elif q == n_qubits-1: update_dir = [1,0] else: update_dir = [1,1] # If there's an operator on my position, add that if q in my_positions: my_pos_index = my_positions.index(q) mpo.update_container(qubit=q, update_dir=update_dir, add_operator= np.complex(my_coefficient)**(1/n_qubits)* my_operators[my_pos_index]) # Else add an identity else: mpo.update_container(qubit=q, update_dir=update_dir, add_operator= np.complex(my_coefficient)**(1/n_qubits)* np.eye(2)) if not j % 100: mpo.compress_mpo() #print("\t\tAt iteration ", j, " MPO has dimension ", mpo.get_dim()) j += 1 mpo.compress_mpo() #print("\tAt final iteration ", j-1, " MPO has dimension ", mpo.get_dim()) return mpo, j def intermediate_to_mpo(self, intermediate): n_qubits = self._n_qubits # TODO Change to multiple MPOs mpo_list = [] j_global = 0 num_mpos = 0 # Start with 0, then final one is correct while j_global < len(intermediate): current_mpo, j_global = self.build_single_mpo(intermediate, j_global) mpo_list += [current_mpo] num_mpos += 1 return mpo_list def construct_matrix(self): # TODO extend to lists of MPOs ''' Recover matrix, e.g. to compare with Hamiltonian that we get from tq ''' mpo = self.mpo # Contract over all bond indices # mpo.container has indices [bond, bond, physical, physical] n_qubits = self._n_qubits d = int(2**(n_qubits/2)) first = True H = None #H = np.zeros((d,d,d,d), dtype='complex') # Define network nodes # | | | | # -O--O--...--O--O- # | | | | for m in mpo: assert(n_qubits == len(m.container)) nodes = [tn.Node(m.container[q], name=str(q)) for q in range(n_qubits)] # Connect network (along double -- above) for q in range(n_qubits-1): nodes[q][1] ^ nodes[q+1][0] # Collect dangling edges (free indices) edges = [] # Left dangling edge edges += [nodes[0].get_edge(0)] # Right dangling edge edges += [nodes[-1].get_edge(1)] # Upper dangling edges for q in range(n_qubits): edges += [nodes[q].get_edge(2)] # Lower dangling edges for q in range(n_qubits): edges += [nodes[q].get_edge(3)] # Contract between all nodes along non-dangling edges res = tn.contractors.auto(nodes, output_edge_order=edges) # Reshape to get tensor of order 4 (get rid of left- and right open indices # and combine top&bottom into one) if isinstance(res.tensor, torch.Tensor): H_m = res.tensor.numpy() if not first: H += H_m else: H = H_m first = False return H.reshape((d,d,d,d))
14,354
36.480418
99
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_2.7/do_annealing.py
import tequila as tq import numpy as np import pickle from pathos.multiprocessing import ProcessingPool as Pool from parallel_annealing import * #from dummy_par import * from mutation_options import * from single_thread_annealing import * def find_best_instructions(instructions_dict): """ This function finds the instruction with the best fitness args: instructions_dict: A dictionary with the "Instructions" objects the corresponding fitness values as values """ best_instructions = None best_fitness = 10000000 for key in instructions_dict: if instructions_dict[key][1] <= best_fitness: best_instructions = instructions_dict[key][0] best_fitness = instructions_dict[key][1] return best_instructions, best_fitness def simulated_annealing(num_population, num_offsprings, actions_ratio, hamiltonian, max_epochs=100, min_epochs=1, tol=1e-6, type_energy_eval="wfn", cluster_circuit=None, patience = 20, num_processors=4, T_0=1.0, alpha=0.9, max_non_cliffords=0, verbose=False, beta=0.5, starting_energy=None): """ this function tries to find the clifford circuit that best lowers the energy of the hamiltonian using simulated annealing. params: - num_population = number of members in a generation - num_offsprings = number of mutations carried on every member - num_processors = number of processors to use for parallelization - T_0 = initial temperature - alpha = temperature decay - beta = parameter to adjust temperature on resetting after running out of patience - max_epochs = max iterations for optimizing - min_epochs = min iterations for optimizing - tol = minimum change in energy required, otherwise terminate optimization - verbose = display energies/decisions at iterations of not - hamiltonian = original hamiltonian - actions_ratio = The ratio of the different actions for mutations - type_energy_eval = keyword specifying the type of optimization method to use for energy minimization - cluster_circuit = the reference circuit to which clifford gates are added - patience = the number of epochs before resetting the optimization """ if verbose: print("Starting to Optimize Cluster circuit", flush=True) num_qubits = len(hamiltonian.qubits) if verbose: print("Initializing Generation", flush=True) # restart = False if previous_instructions is None\ # else True restart = False instructions_dict = {} instructions_list = [] current_fitness_list = [] fitness, wfn = None, None # pre-initialize with None for instruction_id in range(num_population): instructions = None if restart: try: instructions = Instructions(n_qubits=num_qubits, alpha=alpha, T_0=T_0, beta=beta, patience=patience, max_non_cliffords=max_non_cliffords, reference_energy=starting_energy) instructions.gates = pickle.load(open("instruct_gates.pickle", "rb")) instructions.positions = pickle.load(open("instruct_positions.pickle", "rb")) instructions.best_reference_wfn = pickle.load(open("best_reference_wfn.pickle", "rb")) print("Added a guess from previous runs", flush=True) fitness, wfn = evaluate_fitness(instructions=instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) except Exception as e: print(e) raise Exception("Did not find a guess from previous runs") # pass restart = False #print(instructions._str()) else: failed = True while failed: instructions = Instructions(n_qubits=num_qubits, alpha=alpha, T_0=T_0, beta=beta, patience=patience, max_non_cliffords=max_non_cliffords, reference_energy=starting_energy) instructions.prune() fitness, wfn = evaluate_fitness(instructions=instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) # if fitness <= starting_energy: failed = False instructions.set_reference_wfn(wfn) current_fitness_list.append(fitness) instructions_list.append(instructions) instructions_dict[instruction_id] = (instructions, fitness) if verbose: print("First Generation details: \n", flush=True) for key in instructions_dict: print("Initial Instructions number: ", key, flush=True) instructions_dict[key][0]._str() print("Initial fitness values: ", instructions_dict[key][1], flush=True) best_instructions, best_energy = find_best_instructions(instructions_dict) if verbose: print("Best member of the Generation: \n", flush=True) print("Instructions: ", flush=True) best_instructions._str() print("fitness value: ", best_energy, flush=True) pickle.dump(best_instructions.gates, open("instruct_gates.pickle", "wb")) pickle.dump(best_instructions.positions, open("instruct_positions.pickle", "wb")) pickle.dump(best_instructions.best_reference_wfn, open("best_reference_wfn.pickle", "wb")) epoch = 0 previous_best_energy = best_energy converged = False has_improved_before = False dts = [] #pool = multiprocessing.Pool(processes=num_processors) while (epoch < max_epochs): print("Epoch: ", epoch, flush=True) import time t0 = time.time() if num_processors == 1: st_evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, type_energy_eval, cluster_circuit) else: evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, num_processors, type_energy_eval, cluster_circuit) t1 = time.time() dts += [t1-t0] best_instructions, best_energy = find_best_instructions(instructions_dict) if verbose: print("Best member of the Generation: \n", flush=True) print("Instructions: ", flush=True) best_instructions._str() print("fitness value: ", best_energy, flush=True) # A bit confusing, but: # Want that current best energy has improved something previous, is better than # some starting energy and achieves some convergence criterion has_improved_before = True if np.abs(best_energy - previous_best_energy) < 0\ else False if np.abs(best_energy - previous_best_energy) < tol and has_improved_before: if starting_energy is not None: converged = True if best_energy < starting_energy else False else: converged = True else: converged = False if best_energy < previous_best_energy: previous_best_energy = best_energy epoch += 1 pickle.dump(best_instructions.gates, open("instruct_gates.pickle", "wb")) pickle.dump(best_instructions.positions, open("instruct_positions.pickle", "wb")) pickle.dump(best_instructions.best_reference_wfn, open("best_reference_wfn.pickle", "wb")) #pool.close() if converged: print("Converged after ", epoch, " iterations.", flush=True) print("Best energy:", best_energy, flush=True) print("\t with instructions", best_instructions.gates, best_instructions.positions, flush=True) print("\t optimal parameters", best_instructions.best_reference_wfn, flush=True) print("average time: ", np.average(dts), flush=True) print("overall time: ", np.sum(dts), flush=True) # best_instructions.replace_UCCXc_with_UCC(number=max_non_cliffords) pickle.dump(best_instructions.gates, open("instruct_gates.pickle", "wb")) pickle.dump(best_instructions.positions, open("instruct_positions.pickle", "wb")) pickle.dump(best_instructions.best_reference_wfn, open("best_reference_wfn.pickle", "wb")) def replace_cliff_with_non_cliff(num_population, num_offsprings, actions_ratio, hamiltonian, max_epochs=100, min_epochs=1, tol=1e-6, type_energy_eval="wfn", cluster_circuit=None, patience = 20, num_processors=4, T_0=1.0, alpha=0.9, max_non_cliffords=0, verbose=False, beta=0.5, starting_energy=None): """ this function tries to find the clifford circuit that best lowers the energy of the hamiltonian using simulated annealing. params: - num_population = number of members in a generation - num_offsprings = number of mutations carried on every member - num_processors = number of processors to use for parallelization - T_0 = initial temperature - alpha = temperature decay - beta = parameter to adjust temperature on resetting after running out of patience - max_epochs = max iterations for optimizing - min_epochs = min iterations for optimizing - tol = minimum change in energy required, otherwise terminate optimization - verbose = display energies/decisions at iterations of not - hamiltonian = original hamiltonian - actions_ratio = The ratio of the different actions for mutations - type_energy_eval = keyword specifying the type of optimization method to use for energy minimization - cluster_circuit = the reference circuit to which clifford gates are added - patience = the number of epochs before resetting the optimization """ if verbose: print("Starting to replace clifford gates Cluster circuit with non-clifford gates one at a time", flush=True) num_qubits = len(hamiltonian.qubits) #get the best clifford object instructions = Instructions(n_qubits=num_qubits, alpha=alpha, T_0=T_0, beta=beta, patience=patience, max_non_cliffords=max_non_cliffords, reference_energy=starting_energy) instructions.gates = pickle.load(open("instruct_gates.pickle", "rb")) instructions.positions = pickle.load(open("instruct_positions.pickle", "rb")) instructions.best_reference_wfn = pickle.load(open("best_reference_wfn.pickle", "rb")) fitness, wfn = evaluate_fitness(instructions=instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) if verbose: print("Initial energy after previous Clifford optimization is",\ fitness, flush=True) print("Starting with instructions", instructions.gates, instructions.positions, flush=True) instructions_dict = {} instructions_dict[0] = (instructions, fitness) for gate_id, (gate, position) in enumerate(zip(instructions.gates, instructions.positions)): print(gate) altered_instructions = copy.deepcopy(instructions) # skip if controlled rotation if gate[0]=='C': continue altered_instructions.replace_cg_w_ncg(gate_id) # altered_instructions.max_non_cliffords = 1 # TODO why is this set to 1?? altered_instructions.max_non_cliffords = max_non_cliffords #clifford_circuit, init_angles = build_circuit(instructions) #print(clifford_circuit, init_angles) #folded_hamiltonian = perform_folding(hamiltonian, clifford_circuit) #folded_hamiltonian2 = (convert_PQH_to_tq_QH(folded_hamiltonian))() #print(folded_hamiltonian) #clifford_circuit, init_angles = build_circuit(altered_instructions) #print(clifford_circuit, init_angles) #folded_hamiltonian = perform_folding(hamiltonian, clifford_circuit) #folded_hamiltonian1 = (convert_PQH_to_tq_QH(folded_hamiltonian))(init_angles) #print(folded_hamiltonian1 - folded_hamiltonian2) #print(folded_hamiltonian) #raise Exception("teste") counter = 0 success = False while not success: counter += 1 try: fitness, wfn = evaluate_fitness(instructions=altered_instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) success = True except Exception as e: print(e) if counter > 5: print("This replacement failed more than 5 times") success = True instructions_dict[gate_id+1] = (altered_instructions, fitness) #circuit = build_circuit(altered_instructions) #tq.draw(circuit,backend="cirq") best_instructions, best_energy = find_best_instructions(instructions_dict) print("best instrucitons after the non-clifford opimizaton") print("Best energy:", best_energy, flush=True) print("\t with instructions", best_instructions.gates, best_instructions.positions, flush=True)
13,155
46.154122
187
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_2.7/scipy_optimizer.py
import numpy, copy, scipy, typing, numbers from tequila import BitString, BitNumbering, BitStringLSB from tequila.utils.keymap import KeyMapRegisterToSubregister from tequila.circuit.compiler import change_basis from tequila.utils import to_float import tequila as tq from tequila.objective import Objective from tequila.optimizers.optimizer_scipy import OptimizerSciPy, SciPyResults from tequila.objective.objective import assign_variable, Variable, format_variable_dictionary, format_variable_list from tequila.circuit.noise import NoiseModel #from tequila.optimizers._containers import _EvalContainer, _GradContainer, _HessContainer, _QngContainer from vqe_utils import * class _EvalContainer: """ Overwrite the call function Container Class to access scipy and keep the optimization history. This class is used by the SciPy optimizer and should not be used elsewhere. Attributes --------- objective: the objective to evaluate. param_keys: the dictionary mapping parameter keys to positions in a numpy array. samples: the number of samples to evaluate objective with. save_history: whether or not to save, in a history, information about each time __call__ occurs. print_level dictates the verbosity of printing during call. N: the length of param_keys. history: if save_history, a list of energies received from every __call__ history_angles: if save_history, a list of angles sent to __call__. """ def __init__(self, Hamiltonian, unitary, param_keys, Ham_derivatives= None, Eval=None, passive_angles=None, samples=1024, save_history=True, print_level: int = 3): self.Hamiltonian = Hamiltonian self.unitary = unitary self.samples = samples self.param_keys = param_keys self.N = len(param_keys) self.save_history = save_history self.print_level = print_level self.passive_angles = passive_angles self.Eval = Eval self.infostring = None self.Ham_derivatives = Ham_derivatives if save_history: self.history = [] self.history_angles = [] def __call__(self, p, *args, **kwargs): """ call a wrapped objective. Parameters ---------- p: numpy array: Parameters with which to call the objective. args kwargs Returns ------- numpy.array: value of self.objective with p translated into variables, as a numpy array. """ angles = {}#dict((self.param_keys[i], p[i]) for i in range(self.N)) for i in range(self.N): if self.param_keys[i] in self.unitary.extract_variables(): angles[self.param_keys[i]] = p[i] else: angles[self.param_keys[i]] = complex(p[i]) if self.passive_angles is not None: angles = {**angles, **self.passive_angles} vars = format_variable_dictionary(angles) Hamiltonian = self.Hamiltonian(vars) #print(Hamiltonian) #print(self.unitary) #print(vars) Expval = tq.ExpectationValue(H=Hamiltonian, U=self.unitary) #print(Expval) E = tq.simulate(Expval, vars, backend='qulacs', samples=self.samples) self.infostring = "{:15} : {} expectationvalues\n".format("Objective", Expval.count_expectationvalues()) if self.print_level > 2: print("E={:+2.8f}".format(E), " angles=", angles, " samples=", self.samples) elif self.print_level > 1: print("E={:+2.8f}".format(E)) if self.save_history: self.history.append(E) self.history_angles.append(angles) return complex(E) # jax types confuses optimizers class _GradContainer(_EvalContainer): """ Overwrite the call function Container Class to access scipy and keep the optimization history. This class is used by the SciPy optimizer and should not be used elsewhere. see _EvalContainer for details. """ def __call__(self, p, *args, **kwargs): """ call the wrapped qng. Parameters ---------- p: numpy array: Parameters with which to call gradient args kwargs Returns ------- numpy.array: value of self.objective with p translated into variables, as a numpy array. """ Ham_derivatives = self.Ham_derivatives Hamiltonian = self.Hamiltonian unitary = self.unitary dE_vec = numpy.zeros(self.N) memory = dict() #variables = dict((self.param_keys[i], p[i]) for i in range(len(self.param_keys))) variables = {}#dict((self.param_keys[i], p[i]) for i in range(self.N)) for i in range(len(self.param_keys)): if self.param_keys[i] in self.unitary.extract_variables(): variables[self.param_keys[i]] = p[i] else: variables[self.param_keys[i]] = complex(p[i]) if self.passive_angles is not None: variables = {**variables, **self.passive_angles} vars = format_variable_dictionary(variables) expvals = 0 for i in range(self.N): derivative = 0.0 if self.param_keys[i] in list(unitary.extract_variables()): Ham = Hamiltonian(vars) Expval = tq.ExpectationValue(H=Ham, U=unitary) temp_derivative = tq.compile(objective = tq.grad(objective = Expval, variable = self.param_keys[i]),backend='qulacs') expvals += temp_derivative.count_expectationvalues() derivative += temp_derivative if self.param_keys[i] in list(Ham_derivatives.keys()): #print(self.param_keys[i]) Ham = Ham_derivatives[self.param_keys[i]] Ham = convert_PQH_to_tq_QH(Ham) H = Ham(vars) #print(H) #raise Exception("testing") Expval = tq.ExpectationValue(H=H, U=unitary) expvals += Expval.count_expectationvalues() derivative += tq.simulate(Expval, vars, backend='qulacs', samples=self.samples) #print(derivative) #print(type(H)) if isinstance(derivative, float) or isinstance(derivative, numpy.complex64) : dE_vec[i] = derivative else: dE_vec[i] = derivative(variables=variables, samples=self.samples) memory[self.param_keys[i]] = dE_vec[i] self.infostring = "{:15} : {} expectationvalues\n".format("gradient", expvals) self.history.append(memory) return numpy.asarray(dE_vec, dtype=numpy.complex64) class optimize_scipy(OptimizerSciPy): """ overwrite the expectation and gradient container objects """ def initialize_variables(self, all_variables, initial_values, variables): """ Convenience function to format the variables of some objective recieved in calls to optimzers. Parameters ---------- objective: Objective: the objective being optimized. initial_values: dict or string: initial values for the variables of objective, as a dictionary. if string: can be `zero` or `random` if callable: custom function that initializes when keys are passed if None: random initialization between 0 and 2pi (not recommended) variables: list: the variables being optimized over. Returns ------- tuple: active_angles, a dict of those variables being optimized. passive_angles, a dict of those variables NOT being optimized. variables: formatted list of the variables being optimized. """ # bring into right format variables = format_variable_list(variables) initial_values = format_variable_dictionary(initial_values) all_variables = all_variables if variables is None: variables = all_variables if initial_values is None: initial_values = {k: numpy.random.uniform(0, 2 * numpy.pi) for k in all_variables} elif hasattr(initial_values, "lower"): if initial_values.lower() == "zero": initial_values = {k:0.0 for k in all_variables} elif initial_values.lower() == "random": initial_values = {k: numpy.random.uniform(0, 2 * numpy.pi) for k in all_variables} else: raise TequilaOptimizerException("unknown initialization instruction: {}".format(initial_values)) elif callable(initial_values): initial_values = {k: initial_values(k) for k in all_variables} elif isinstance(initial_values, numbers.Number): initial_values = {k: initial_values for k in all_variables} else: # autocomplete initial values, warn if you did detected = False for k in all_variables: if k not in initial_values: initial_values[k] = 0.0 detected = True if detected and not self.silent: warnings.warn("initial_variables given but not complete: Autocompleted with zeroes", TequilaWarning) active_angles = {} for v in variables: active_angles[v] = initial_values[v] passive_angles = {} for k, v in initial_values.items(): if k not in active_angles.keys(): passive_angles[k] = v return active_angles, passive_angles, variables def __call__(self, Hamiltonian, unitary, variables: typing.List[Variable] = None, initial_values: typing.Dict[Variable, numbers.Real] = None, gradient: typing.Dict[Variable, Objective] = None, hessian: typing.Dict[typing.Tuple[Variable, Variable], Objective] = None, reset_history: bool = True, *args, **kwargs) -> SciPyResults: """ Perform optimization using scipy optimizers. Parameters ---------- objective: Objective: the objective to optimize. variables: list, optional: the variables of objective to optimize. If None: optimize all. initial_values: dict, optional: a starting point from which to begin optimization. Will be generated if None. gradient: optional: Information or object used to calculate the gradient of objective. Defaults to None: get analytically. hessian: optional: Information or object used to calculate the hessian of objective. Defaults to None: get analytically. reset_history: bool: Default = True: whether or not to reset all history before optimizing. args kwargs Returns ------- ScipyReturnType: the results of optimization. """ H = convert_PQH_to_tq_QH(Hamiltonian) Ham_variables, Ham_derivatives = H._construct_derivatives() #print("hamvars",Ham_variables) all_variables = copy.deepcopy(Ham_variables) #print(all_variables) for var in unitary.extract_variables(): all_variables.append(var) #print(all_variables) infostring = "{:15} : {}\n".format("Method", self.method) #infostring += "{:15} : {} expectationvalues\n".format("Objective", objective.count_expectationvalues()) if self.save_history and reset_history: self.reset_history() active_angles, passive_angles, variables = self.initialize_variables(all_variables, initial_values, variables) #print(active_angles, passive_angles, variables) # Transform the initial value directory into (ordered) arrays param_keys, param_values = zip(*active_angles.items()) param_values = numpy.array(param_values) # process and initialize scipy bounds bounds = None if self.method_bounds is not None: bounds = {k: None for k in active_angles} for k, v in self.method_bounds.items(): if k in bounds: bounds[k] = v infostring += "{:15} : {}\n".format("bounds", self.method_bounds) names, bounds = zip(*bounds.items()) assert (names == param_keys) # make sure the bounds are not shuffled #print(param_keys, param_values) # do the compilation here to avoid costly recompilation during the optimization #compiled_objective = self.compile_objective(objective=objective, *args, **kwargs) E = _EvalContainer(Hamiltonian = H, unitary = unitary, Eval=None, param_keys=param_keys, samples=self.samples, passive_angles=passive_angles, save_history=self.save_history, print_level=self.print_level) E.print_level = 0 (E(param_values)) E.print_level = self.print_level infostring += E.infostring if gradient is not None: infostring += "{:15} : {}\n".format("grad instr", gradient) if hessian is not None: infostring += "{:15} : {}\n".format("hess_instr", hessian) compile_gradient = self.method in (self.gradient_based_methods + self.hessian_based_methods) compile_hessian = self.method in self.hessian_based_methods dE = None ddE = None # detect if numerical gradients shall be used # switch off compiling if so if isinstance(gradient, str): if gradient.lower() == 'qng': compile_gradient = False if compile_hessian: raise TequilaException('Sorry, QNG and hessian not yet tested together.') combos = get_qng_combos(objective, initial_values=initial_values, backend=self.backend, samples=self.samples, noise=self.noise) dE = _QngContainer(combos=combos, param_keys=param_keys, passive_angles=passive_angles) infostring += "{:15} : QNG {}\n".format("gradient", dE) else: dE = gradient compile_gradient = False if compile_hessian: compile_hessian = False if hessian is None: hessian = gradient infostring += "{:15} : scipy numerical {}\n".format("gradient", dE) infostring += "{:15} : scipy numerical {}\n".format("hessian", ddE) if isinstance(gradient,dict): if gradient['method'] == 'qng': func = gradient['function'] compile_gradient = False if compile_hessian: raise TequilaException('Sorry, QNG and hessian not yet tested together.') combos = get_qng_combos(objective,func=func, initial_values=initial_values, backend=self.backend, samples=self.samples, noise=self.noise) dE = _QngContainer(combos=combos, param_keys=param_keys, passive_angles=passive_angles) infostring += "{:15} : QNG {}\n".format("gradient", dE) if isinstance(hessian, str): ddE = hessian compile_hessian = False if compile_gradient: dE =_GradContainer(Ham_derivatives = Ham_derivatives, unitary = unitary, Hamiltonian = H, Eval= E, param_keys=param_keys, samples=self.samples, passive_angles=passive_angles, save_history=self.save_history, print_level=self.print_level) dE.print_level = 0 (dE(param_values)) dE.print_level = self.print_level infostring += dE.infostring if self.print_level > 0: print(self) print(infostring) print("{:15} : {}\n".format("active variables", len(active_angles))) Es = [] optimizer_instance = self class SciPyCallback: energies = [] gradients = [] hessians = [] angles = [] real_iterations = 0 def __call__(self, *args, **kwargs): self.energies.append(E.history[-1]) self.angles.append(E.history_angles[-1]) if dE is not None and not isinstance(dE, str): self.gradients.append(dE.history[-1]) if ddE is not None and not isinstance(ddE, str): self.hessians.append(ddE.history[-1]) self.real_iterations += 1 if 'callback' in optimizer_instance.kwargs: optimizer_instance.kwargs['callback'](E.history_angles[-1]) callback = SciPyCallback() res = scipy.optimize.minimize(E, x0=param_values, jac=dE, hess=ddE, args=(Es,), method=self.method, tol=self.tol, bounds=bounds, constraints=self.method_constraints, options=self.method_options, callback=callback) # failsafe since callback is not implemented everywhere if callback.real_iterations == 0: real_iterations = range(len(E.history)) if self.save_history: self.history.energies = callback.energies self.history.energy_evaluations = E.history self.history.angles = callback.angles self.history.angles_evaluations = E.history_angles self.history.gradients = callback.gradients self.history.hessians = callback.hessians if dE is not None and not isinstance(dE, str): self.history.gradients_evaluations = dE.history if ddE is not None and not isinstance(ddE, str): self.history.hessians_evaluations = ddE.history # some methods like "cobyla" do not support callback functions if len(self.history.energies) == 0: self.history.energies = E.history self.history.angles = E.history_angles # some scipy methods always give back the last value and not the minimum (e.g. cobyla) ea = sorted(zip(E.history, E.history_angles), key=lambda x: x[0]) E_final = ea[0][0] angles_final = ea[0][1] #dict((param_keys[i], res.x[i]) for i in range(len(param_keys))) angles_final = {**angles_final, **passive_angles} return SciPyResults(energy=E_final, history=self.history, variables=format_variable_dictionary(angles_final), scipy_result=res) def minimize(Hamiltonian, unitary, gradient: typing.Union[str, typing.Dict[Variable, Objective]] = None, hessian: typing.Union[str, typing.Dict[typing.Tuple[Variable, Variable], Objective]] = None, initial_values: typing.Dict[typing.Hashable, numbers.Real] = None, variables: typing.List[typing.Hashable] = None, samples: int = None, maxiter: int = 100, backend: str = None, backend_options: dict = None, noise: NoiseModel = None, device: str = None, method: str = "BFGS", tol: float = 1.e-3, method_options: dict = None, method_bounds: typing.Dict[typing.Hashable, numbers.Real] = None, method_constraints=None, silent: bool = False, save_history: bool = True, *args, **kwargs) -> SciPyResults: """ calls the local optimize_scipy scipy funtion instead and pass down the objective construction down Parameters ---------- objective: Objective : The tequila objective to optimize gradient: typing.Union[str, typing.Dict[Variable, Objective], None] : Default value = None): '2-point', 'cs' or '3-point' for numerical gradient evaluation (does not work in combination with all optimizers), dictionary of variables and tequila objective to define own gradient, None for automatic construction (default) Other options include 'qng' to use the quantum natural gradient. hessian: typing.Union[str, typing.Dict[Variable, Objective], None], optional: '2-point', 'cs' or '3-point' for numerical gradient evaluation (does not work in combination with all optimizers), dictionary (keys:tuple of variables, values:tequila objective) to define own gradient, None for automatic construction (default) initial_values: typing.Dict[typing.Hashable, numbers.Real], optional: Initial values as dictionary of Hashable types (variable keys) and floating point numbers. If given None they will all be set to zero variables: typing.List[typing.Hashable], optional: List of Variables to optimize samples: int, optional: samples/shots to take in every run of the quantum circuits (None activates full wavefunction simulation) maxiter: int : (Default value = 100): max iters to use. backend: str, optional: Simulator backend, will be automatically chosen if set to None backend_options: dict, optional: Additional options for the backend Will be unpacked and passed to the compiled objective in every call noise: NoiseModel, optional: a NoiseModel to apply to all expectation values in the objective. method: str : (Default = "BFGS"): Optimization method (see scipy documentation, or 'available methods') tol: float : (Default = 1.e-3): Convergence tolerance for optimization (see scipy documentation) method_options: dict, optional: Dictionary of options (see scipy documentation) method_bounds: typing.Dict[typing.Hashable, typing.Tuple[float, float]], optional: bounds for the variables (see scipy documentation) method_constraints: optional: (see scipy documentation silent: bool : No printout if True save_history: bool: Save the history throughout the optimization Returns ------- SciPyReturnType: the results of optimization """ if isinstance(gradient, dict) or hasattr(gradient, "items"): if all([isinstance(x, Objective) for x in gradient.values()]): gradient = format_variable_dictionary(gradient) if isinstance(hessian, dict) or hasattr(hessian, "items"): if all([isinstance(x, Objective) for x in hessian.values()]): hessian = {(assign_variable(k[0]), assign_variable([k[1]])): v for k, v in hessian.items()} method_bounds = format_variable_dictionary(method_bounds) # set defaults optimizer = optimize_scipy(save_history=save_history, maxiter=maxiter, method=method, method_options=method_options, method_bounds=method_bounds, method_constraints=method_constraints, silent=silent, backend=backend, backend_options=backend_options, device=device, samples=samples, noise_model=noise, tol=tol, *args, **kwargs) if initial_values is not None: initial_values = {assign_variable(k): v for k, v in initial_values.items()} return optimizer(Hamiltonian, unitary, gradient=gradient, hessian=hessian, initial_values=initial_values, variables=variables, *args, **kwargs)
24,489
42.732143
144
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_2.7/energy_optimization.py
import tequila as tq import numpy as np from tequila.objective.objective import Variable import openfermion from hacked_openfermion_qubit_operator import ParamQubitHamiltonian from typing import Union from vqe_utils import convert_PQH_to_tq_QH, convert_tq_QH_to_PQH,\ fold_unitary_into_hamiltonian from grad_hacked import grad from scipy_optimizer import minimize import scipy import random # guess we could substitute that with numpy.random #TODO import argparse import pickle as pk import sys sys.path.insert(0, '../../../') #sys.path.insert(0, '../') # This needs to be properly integrated somewhere else at some point # from tn_update.qq import contract_energy, optimize_wavefunctions from tn_update.my_mpo import * from tn_update.wfn_optimization import contract_energy_mpo, optimize_wavefunctions_mpo, initialize_wfns_randomly def energy_from_wfn_opti(hamiltonian: tq.QubitHamiltonian, n_qubits: int, guess_wfns=None, TOL=1e-4) -> tuple: ''' Get energy using a tensornetwork based method ~ power method (here as blackbox) ''' d = int(2**(n_qubits/2)) # Build MPO h_mpo = MyMPO(hamiltonian=hamiltonian, n_qubits=n_qubits, maxdim=500) h_mpo.make_mpo_from_hamiltonian() # Optimize wavefunctions based on random guess out = None it = 0 while out is None: # Set up random initial guesses for subsystems it += 1 if guess_wfns is None: psiL_rand = initialize_wfns_randomly(d, n_qubits//2) psiR_rand = initialize_wfns_randomly(d, n_qubits//2) else: psiL_rand = guess_wfns[0] psiR_rand = guess_wfns[1] out = optimize_wavefunctions_mpo(h_mpo, psiL_rand, psiR_rand, TOL=TOL, silent=True) energy_rand = out[0] optimal_wfns = [out[1], out[2]] return energy_rand, optimal_wfns def combine_two_clusters(H: tq.QubitHamiltonian, subsystems: list, circ_list: list) -> float: ''' E = nuc_rep + \sum_j c_j <0_A | U_A+ sigma_j|A U_A | 0_A><0_B | U_B+ sigma_j|B U_B | 0_B> i ) Split up Hamiltonian into vector c = [c_j], all sigmas of system A and system B ii ) Two vectors of ExpectationValues E_A=[E(U_A, sigma_j|A)], E_B=[E(U_B, sigma_j|B)] iii) Minimize vectors from ii) iv ) Perform weighted sum \sum_j c_[j] E_A[j] E_B[j] result = nuc_rep + iv) Finishing touch inspired by private tequila-repo / pair-separated objective This is still rather inefficient/unoptimized Can still prune out near-zero coefficients c_j ''' objective = 0.0 n_subsystems = len(subsystems) # Over all Paulistrings in the Hamiltonian for p_index, pauli in enumerate(H.paulistrings): # Gather coefficient coeff = pauli.coeff.real # Empty dictionary for operations: # to be filled with another dictionary per subsystem, where then # e.g. X(0)Z(1)Y(2)X(4) and subsystems=[[0,1,2],[3,4,5]] # -> ops={ 0: {0: 'X', 1: 'Z', 2: 'Y'}, 1: {4: 'X'} } ops = {} for s_index, sys in enumerate(subsystems): for k, v in pauli.items(): if k in sys: if s_index in ops: ops[s_index][k] = v else: ops[s_index] = {k: v} # If no ops gathered -> identity -> nuclear repulsion if len(ops) == 0: #print ("this should only happen ONCE") objective += coeff # If not just identity: # add objective += c_j * prod_subsys( < Paulistring_j_subsys >_{U_subsys} ) elif len(ops) > 0: obj_tmp = coeff for s_index, sys_pauli in ops.items(): #print (s_index, sys_pauli) H_tmp = QubitHamiltonian.from_paulistrings(PauliString(data=sys_pauli)) E_tmp = ExpectationValue(U=circ_list[s_index], H=H_tmp) obj_tmp *= E_tmp objective += obj_tmp initial_values = {k: 0.0 for k in objective.extract_variables()} random_initial_values = {k: 1e-2*np.random.uniform(-1, 1) for k in objective.extract_variables()} method = 'bfgs' # 'bfgs' # 'l-bfgs-b' # 'cobyla' # 'slsqp' curr_res = tq.minimize(method=method, objective=objective, initial_values=initial_values, gradient='two-point', backend='qulacs', method_options={"finite_diff_rel_step": 1e-3}) return curr_res.energy def energy_from_tq_qcircuit(hamiltonian: Union[tq.QubitHamiltonian, ParamQubitHamiltonian], n_qubits: int, circuit = Union[list, tq.QCircuit], subsystems: list = [[0,1,2,3,4,5]], initial_guess = None)-> tuple: ''' Get minimal energy using tequila ''' result = None # If only one circuit handed over, just run simple VQE if isinstance(circuit, list) and len(circuit) == 1: circuit = circuit[0] if isinstance(circuit, tq.QCircuit): if isinstance(hamiltonian, tq.QubitHamiltonian): E = tq.ExpectationValue(H=hamiltonian, U=circuit) if initial_guess is None: initial_angles = {k: 0.0 for k in E.extract_variables()} else: initial_angles = initial_guess #print ("optimizing non-param...") result = tq.minimize(objective=E, method='l-bfgs-b', silent=True, backend='qulacs', initial_values=initial_angles) #gradient='two-point', backend='qulacs', #method_options={"finite_diff_rel_step": 1e-4}) elif isinstance(hamiltonian, ParamQubitHamiltonian): if initial_guess is None: raise Exception("Need to provide initial guess for this to work.") initial_angles = None else: initial_angles = initial_guess #print ("optimizing param...") result = minimize(hamiltonian, circuit, method='bfgs', initial_values=initial_angles, backend="qulacs", silent=True) # If more circuits handed over, assume subsystems else: # TODO!! implement initial guess for the combine_two_clusters thing #print ("Should not happen for now...") result = combine_two_clusters(hamiltonian, subsystems, circuit) return result.energy, result.angles def mixed_optimization(hamiltonian: ParamQubitHamiltonian, n_qubits: int, initial_guess: Union[dict, list]=None, init_angles: list=None): ''' Minimizes energy using wfn opti and a parametrized Hamiltonian min_{psi, theta fixed} <psi | H(theta) | psi> --> min_{t, p fixed} <p | H(t) | p> ^---------------------------------------------------^ until convergence ''' energy, optimal_state = None, None H_qh = convert_PQH_to_tq_QH(hamiltonian) var_keys, H_derivs = H_qh._construct_derivatives() print("var keys", var_keys, flush=True) print('var dict', init_angles, flush=True) # if not init_angles: # var_vals = [0. for i in range(len(var_keys))] # initialize with 0 # else: # var_vals = init_angles def build_variable_dict(keys, values): assert(len(keys)==len(values)) out = dict() for idx, key in enumerate(keys): out[key] = complex(values[idx]) return out var_dict = init_angles var_vals = [*init_angles.values()] assert(build_variable_dict(var_keys, var_vals) == var_dict) def wrap_energy_eval(psi): ''' like energy_from_wfn_opti but instead of optimize get inner product ''' def energy_eval_fn(x): var_dict = build_variable_dict(var_keys, x) H_qh_fix = H_qh(var_dict) H_mpo = MyMPO(hamiltonian=H_qh_fix, n_qubits=n_qubits, maxdim=500) H_mpo.make_mpo_from_hamiltonian() return contract_energy_mpo(H_mpo, psi[0], psi[1]) return energy_eval_fn def wrap_gradient_eval(psi): ''' call derivatives with updated variable list ''' def gradient_eval_fn(x): variables = build_variable_dict(var_keys, x) deriv_expectations = H_derivs.values() # list of ParamQubitHamiltonian's deriv_qhs = [convert_PQH_to_tq_QH(d) for d in deriv_expectations] deriv_qhs = [d(variables) for d in deriv_qhs] # list of tq.QubitHamiltonian's # print(deriv_qhs) deriv_mpos = [MyMPO(hamiltonian=d, n_qubits=n_qubits, maxdim=500)\ for d in deriv_qhs] # print(deriv_mpos[0].n_qubits) for d in deriv_mpos: d.make_mpo_from_hamiltonian() # deriv_mpos = [d.make_mpo_from_hamiltonian() for d in deriv_mpos] return np.asarray([contract_energy_mpo(d, psi[0], psi[1]) for d in deriv_mpos]) return gradient_eval_fn def do_wfn_opti(values, guess_wfns, TOL): # H_qh = H_qh(H_vars) var_dict = build_variable_dict(var_keys, values) en, psi = energy_from_wfn_opti(H_qh(var_dict), n_qubits=n_qubits, guess_wfns=guess_wfns, TOL=TOL) return en, psi def do_param_opti(psi, x0): result = scipy.optimize.minimize(fun=wrap_energy_eval(psi), jac=wrap_gradient_eval(psi), method='bfgs', x0=x0, options={'maxiter': 4}) # print(result) return result e_prev, psi_prev = 123., None # print("iguess", initial_guess) e_curr, psi_curr = do_wfn_opti(var_vals, initial_guess, 1e-5) print('first eval', e_curr, flush=True) def converged(e_prev, e_curr, TOL=1e-4): return True if np.abs(e_prev-e_curr) < TOL else False it = 0 var_prev = var_vals print("vars before comp", var_prev, flush=True) while not converged(e_prev, e_curr) and it < 50: e_prev, psi_prev = e_curr, psi_curr # print('before param opti') res = do_param_opti(psi_curr, var_prev) var_curr = res['x'] print('curr vars', var_curr, flush=True) e_curr = res['fun'] print('en before wfn opti', e_curr, flush=True) # print("iiiiiguess", psi_prev) e_curr, psi_curr = do_wfn_opti(var_curr, psi_prev, 1e-3) print('en after wfn opti', e_curr, flush=True) it += 1 print('at iteration', it, flush=True) return e_curr, psi_curr # optimize parameters with fixed wavefunction # define/wrap energy function - given |p>, evaluate <p|H(t)|p> ''' def wrap_gradient(objective: typing.Union[Objective, QTensor], no_compile=False, *args, **kwargs): def gradient_fn(variable: Variable = None): return grad(objective: typing.Union[Objective, QTensor], variable: Variable = None, no_compile=False, *args, **kwargs) return grad_fn ''' def minimize_energy(hamiltonian: Union[ParamQubitHamiltonian, tq.QubitHamiltonian], n_qubits: int, type_energy_eval: str='wfn', cluster_circuit: tq.QCircuit=None, initial_guess=None, initial_mixed_angles: dict=None) -> float: ''' Minimizes energy functional either according a power-method inspired shortcut ('wfn') or using a unitary circuit ('qc') ''' if type_energy_eval == 'wfn': if isinstance(hamiltonian, tq.QubitHamiltonian): energy, optimal_state = energy_from_wfn_opti(hamiltonian, n_qubits, initial_guess) elif isinstance(hamiltonian, ParamQubitHamiltonian): init_angles = initial_mixed_angles energy, optimal_state = mixed_optimization(hamiltonian=hamiltonian, n_qubits=n_qubits, initial_guess=initial_guess, init_angles=init_angles) elif type_energy_eval == 'qc': if cluster_circuit is None: raise Exception("Need to hand over circuit!") energy, optimal_state = energy_from_tq_qcircuit(hamiltonian, n_qubits, cluster_circuit, [[0,1,2,3],[4,5,6,7]], initial_guess) else: raise Exception("Option not implemented!") return energy, optimal_state
12,457
43.021201
225
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_2.7/parallel_annealing.py
import tequila as tq import multiprocessing import copy from time import sleep from mutation_options import * from pathos.multiprocessing import ProcessingPool as Pool def evolve_population(hamiltonian, type_energy_eval, cluster_circuit, process_id, num_offsprings, actions_ratio, tasks, results): """ This function carries a single step of the simulated annealing on a single member of the generation args: process_id: A unique identifier for each process num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for mutations tasks: multiprocessing queue to pass family_id, instructions and current_fitness family_id: A unique identifier for each family instructions: An object consisting of the instructions in the quantum circuit current_fitness: Current fitness value of the circuit results: multiprocessing queue to pass results back """ #print('[%s] evaluation routine starts' % process_id) while True: try: #getting parameters for mutation and carrying it family_id, instructions, current_fitness = tasks.get() #check if patience has been exhausted if instructions.patience == 0: instructions.reset_to_best() best_child = 0 best_energy = current_fitness new_generations = {} for off_id in range(1, num_offsprings+1): scheduled_ratio = schedule_actions_ratio(epoch=0, steady_ratio=actions_ratio) action = get_action(scheduled_ratio) updated_instructions = copy.deepcopy(instructions) updated_instructions.update_by_action(action) new_fitness, wfn = evaluate_fitness(updated_instructions, hamiltonian, type_energy_eval, cluster_circuit) updated_instructions.set_reference_wfn(wfn) prob_acceptance = get_prob_acceptance(current_fitness, new_fitness, updated_instructions.T, updated_instructions.reference_energy) # need to figure out in case we have two equals new_generations[str(off_id)] = updated_instructions if best_energy > new_fitness: # now two equals -> "first one" is picked best_child = off_id best_energy = new_fitness # decision = np.random.binomial(1, prob_acceptance) # if decision == 0: if best_child == 0: # Add result to the queue instructions.patience -= 1 #print('Reduced patience -- now ' + str(updated_instructions.patience)) if instructions.patience == 0: if instructions.best_previous_instructions: instructions.reset_to_best() else: instructions.update_T() results.put((family_id, instructions, current_fitness)) else: # Add result to the queue if (best_energy < current_fitness): new_generations[str(best_child)].update_best_previous_instructions() new_generations[str(best_child)].update_T() results.put((family_id, new_generations[str(best_child)], best_energy)) except Exception as eeee: #print('[%s] evaluation routine quits' % process_id) #print(eeee) # Indicate finished results.put(-1) break return def evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, num_processors=4, type_energy_eval='wfn', cluster_circuit=None): """ This function does parallel mutation on all the members of the generation and updates the generation args: num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for sampling instructions_dict: A dictionary with the "Instructions" objects the corresponding fitness values as values num_processors: Number of processors to use for parallel run """ # Define IPC manager manager = multiprocessing.Manager() # Define a list (queue) for tasks and computation results tasks = manager.Queue() results = manager.Queue() processes = [] pool = Pool(processes=num_processors) for i in range(num_processors): process_id = 'P%i' % i # Create the process, and connect it to the worker function new_process = multiprocessing.Process(target=evolve_population, args=(hamiltonian, type_energy_eval, cluster_circuit, process_id, num_offsprings, actions_ratio, tasks, results)) # Add new process to the list of processes processes.append(new_process) # Start the process new_process.start() #print("putting tasks") for family_id in instructions_dict: single_task = (family_id, instructions_dict[family_id][0], instructions_dict[family_id][1]) tasks.put(single_task) # Wait while the workers process - change it to something for our case later # sleep(5) multiprocessing.Barrier(num_processors) #print("after barrier") # Quit the worker processes by sending them -1 for i in range(num_processors): tasks.put(-1) # Read calculation results num_finished_processes = 0 while True: # Read result #print("num fin", num_finished_processes) try: family_id, updated_instructions, new_fitness = results.get() instructions_dict[family_id] = (updated_instructions, new_fitness) except: # Process has finished num_finished_processes += 1 if num_finished_processes == num_processors: break for process in processes: process.join() pool.close()
6,456
38.371951
146
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_2.7/single_thread_annealing.py
import tequila as tq import copy from mutation_options import * def st_evolve_population(hamiltonian, type_energy_eval, cluster_circuit, num_offsprings, actions_ratio, tasks): """ This function carries a single step of the simulated annealing on a single member of the generation args: num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for mutations tasks: a tuple of (family_id, instructions and current_fitness) family_id: A unique identifier for each family instructions: An object consisting of the instructions in the quantum circuit current_fitness: Current fitness value of the circuit """ family_id, instructions, current_fitness = tasks #check if patience has been exhausted if instructions.patience == 0: if instructions.best_previous_instructions: instructions.reset_to_best() best_child = 0 best_energy = current_fitness new_generations = {} for off_id in range(1, num_offsprings+1): scheduled_ratio = schedule_actions_ratio(epoch=0, steady_ratio=actions_ratio) action = get_action(scheduled_ratio) updated_instructions = copy.deepcopy(instructions) updated_instructions.update_by_action(action) new_fitness, wfn = evaluate_fitness(updated_instructions, hamiltonian, type_energy_eval, cluster_circuit) updated_instructions.set_reference_wfn(wfn) prob_acceptance = get_prob_acceptance(current_fitness, new_fitness, updated_instructions.T, updated_instructions.reference_energy) # need to figure out in case we have two equals new_generations[str(off_id)] = updated_instructions if best_energy > new_fitness: # now two equals -> "first one" is picked best_child = off_id best_energy = new_fitness # decision = np.random.binomial(1, prob_acceptance) # if decision == 0: if best_child == 0: # Add result to the queue instructions.patience -= 1 #print('Reduced patience -- now ' + str(updated_instructions.patience)) if instructions.patience == 0: if instructions.best_previous_instructions: instructions.reset_to_best() else: instructions.update_T() results = ((family_id, instructions, current_fitness)) else: # Add result to the queue if (best_energy < current_fitness): new_generations[str(best_child)].update_best_previous_instructions() new_generations[str(best_child)].update_T() results = ((family_id, new_generations[str(best_child)], best_energy)) return results def st_evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, type_energy_eval='wfn', cluster_circuit=None): """ This function does a single threas mutation on all the members of the generation and updates the generation args: num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for sampling instructions_dict: A dictionary with the "Instructions" objects the corresponding fitness values as values """ for family_id in instructions_dict: task = (family_id, instructions_dict[family_id][0], instructions_dict[family_id][1]) results = st_evolve_population(hamiltonian, type_energy_eval, cluster_circuit, num_offsprings, actions_ratio, task) family_id, updated_instructions, new_fitness = results instructions_dict[family_id] = (updated_instructions, new_fitness)
4,005
40.298969
138
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_2.7/mutation_options.py
import argparse import numpy as np import random import copy import tequila as tq from typing import Union from collections import Counter from time import time from vqe_utils import convert_PQH_to_tq_QH, convert_tq_QH_to_PQH,\ fold_unitary_into_hamiltonian from energy_optimization import minimize_energy global_seed = 1 class Instructions: ''' TODO need to put some documentation here ''' def __init__(self, n_qubits, mu=2.0, sigma=0.4, alpha=0.9, T_0=1.0, beta=0.5, patience=10, max_non_cliffords=0, reference_energy=0., number=None): # hardcoded values for now self.num_non_cliffords = 0 self.max_non_cliffords = max_non_cliffords # ------------------------ self.starting_patience = patience self.patience = patience self.mu = mu self.sigma = sigma self.alpha = alpha self.beta = beta self.T_0 = T_0 self.T = T_0 self.gates = self.get_random_gates(number=number) self.n_qubits = n_qubits self.positions = self.get_random_positions() self.best_previous_instructions = {} self.reference_energy = reference_energy self.best_reference_wfn = None self.noncliff_replacements = {} def _str(self): print(self.gates) print(self.positions) def set_reference_wfn(self, reference_wfn): self.best_reference_wfn = reference_wfn def update_T(self, update_type: str = 'regular', best_temp=None): # Regular update if update_type.lower() == 'regular': self.T = self.alpha * self.T # Temperature update if patience ran out elif update_type.lower() == 'patience': self.T = self.beta*best_temp + (1-self.beta)*self.T_0 def get_random_gates(self, number=None): ''' Randomly generates a list of gates. number indicates the number of gates to generate otherwise, number will be drawn from a log normal distribution ''' mu, sigma = self.mu, self.sigma full_options = ['X','Y','Z','S','H','CX', 'CY', 'CZ','SWAP', 'UCC2c', 'UCC4c', 'UCC2', 'UCC4'] clifford_options = ['X','Y','Z','S','H','CX', 'CY', 'CZ','SWAP', 'UCC2c', 'UCC4c'] #non_clifford_options = ['UCC2', 'UCC4'] # Gate distribution, selecting number of gates to add k = np.random.lognormal(mu, sigma) k = np.int(k) if number is not None: k = number # Selecting gate types gates = None if self.num_non_cliffords < self.max_non_cliffords: gates = random.choices(full_options, k=k) # with replacement else: gates = random.choices(clifford_options, k=k) new_num_non_cliffords = 0 if "UCC2" in gates: new_num_non_cliffords += Counter(gates)["UCC2"] if "UCC4" in gates: new_num_non_cliffords += Counter(gates)["UCC4"] if (new_num_non_cliffords+self.num_non_cliffords) <= self.max_non_cliffords: self.num_non_cliffords += new_num_non_cliffords else: extra_cliffords = (new_num_non_cliffords+self.num_non_cliffords) - self.max_non_cliffords assert(extra_cliffords >= 0) new_gates = random.choices(clifford_options, k=extra_cliffords) for g in new_gates: try: gates[gates.index("UCC4")] = g except: gates[gates.index("UCC2")] = g self.num_non_cliffords = self.max_non_cliffords if k == 1: if gates == "UCC2c" or gates == "UCC4c": gates = get_string_Cliff_ucc(gates) if gates == "UCC2" or gates == "UCC4": gates = get_string_ucc(gates) else: for ind, gate in enumerate(gates): if gate == "UCC2c" or gate == "UCC4c": gates[ind] = get_string_Cliff_ucc(gate) if gate == "UCC2" or gate == "UCC4": gates[ind] = get_string_ucc(gate) return gates def get_random_positions(self, gates=None): ''' Randomly assign gates to qubits. ''' if gates is None: gates = self.gates n_qubits = self.n_qubits single_qubit = ['X','Y','Z','S','H'] # two_qubit = ['CX','CY','CZ', 'SWAP'] two_qubit = ['CX', 'CY', 'CZ', 'SWAP', 'UCC2c', 'UCC2'] four_qubit = ['UCC4c', 'UCC4'] qubits = list(range(0, n_qubits)) q_positions = [] for gate in gates: if gate in four_qubit: p = random.sample(qubits, k=4) if gate in two_qubit: p = random.sample(qubits, k=2) if gate in single_qubit: p = random.sample(qubits, k=1) if "UCC2" in gate: p = random.sample(qubits, k=2) if "UCC4" in gate: p = random.sample(qubits, k=4) q_positions.append(p) return q_positions def delete(self, number=None): ''' Randomly drops some gates from a clifford instruction set if not specified, the number of gates to drop is sampled from a uniform distribution over all the gates ''' gates = copy.deepcopy(self.gates) positions = copy.deepcopy(self.positions) n_qubits = self.n_qubits if number is not None: num_to_drop = number else: num_to_drop = random.sample(range(1,len(gates)-1), k=1)[0] action_indices = random.sample(range(0,len(gates)-1), k=num_to_drop) for index in sorted(action_indices, reverse=True): if "UCC2_" in str(gates[index]) or "UCC4_" in str(gates[index]): self.num_non_cliffords -= 1 del gates[index] del positions[index] self.gates = gates self.positions = positions #print ('deleted {} gates'.format(num_to_drop)) def add(self, number=None): ''' adds a random selection of clifford gates to the end of a clifford instruction set if number is not specified, the number of gates to add will be drawn from a log normal distribution ''' gates = copy.deepcopy(self.gates) positions = copy.deepcopy(self.positions) n_qubits = self.n_qubits added_instructions = self.get_new_instructions(number=number) gates.extend(added_instructions['gates']) positions.extend(added_instructions['positions']) self.gates = gates self.positions = positions #print ('added {} gates'.format(len(added_instructions['gates']))) def change(self, number=None): ''' change a random number of gates and qubit positions in a clifford instruction set if not specified, the number of gates to change is sampled from a uniform distribution over all the gates ''' gates = copy.deepcopy(self.gates) positions = copy.deepcopy(self.positions) n_qubits = self.n_qubits if number is not None: num_to_change = number else: num_to_change = random.sample(range(1,len(gates)), k=1)[0] action_indices = random.sample(range(0,len(gates)-1), k=num_to_change) added_instructions = self.get_new_instructions(number=num_to_change) for i in range(num_to_change): gates[action_indices[i]] = added_instructions['gates'][i] positions[action_indices[i]] = added_instructions['positions'][i] self.gates = gates self.positions = positions #print ('changed {} gates'.format(len(added_instructions['gates']))) # TODO to be debugged! def prune(self): ''' Prune instructions to remove redundant operations: --> first gate should go beyond subsystems (this assumes expressible enough subsystem-ciruits #TODO later -> this needs subsystem information in here! --> 2 subsequent gates that are their respective inverse can be removed #TODO this might change the number of qubits acted on in theory? ''' pass #print ("DEBUG PRUNE FUNCTION!") # gates = copy.deepcopy(self.gates) # positions = copy.deepcopy(self.positions) # for g_index in range(len(gates)-1): # if (gates[g_index] == gates[g_index+1] and not 'S' in gates[g_index])\ # or (gates[g_index] == 'S' and gates[g_index+1] == 'S-dag')\ # or (gates[g_index] == 'S-dag' and gates[g_index+1] == 'S'): # print(len(gates)) # if positions[g_index] == positions[g_index+1]: # self.gates.pop(g_index) # self.positions.pop(g_index) def update_by_action(self, action: str): ''' Updates instruction dictionary -> Either adds, deletes or changes gates ''' if action == 'delete': try: self.delete() # In case there are too few gates to delete except: pass elif action == 'add': self.add() elif action == 'change': self.change() else: raise Exception("Unknown action type " + action + ".") self.prune() def update_best_previous_instructions(self): ''' Overwrites the best previous instructions with the current ones. ''' self.best_previous_instructions['gates'] = copy.deepcopy(self.gates) self.best_previous_instructions['positions'] = copy.deepcopy(self.positions) self.best_previous_instructions['T'] = copy.deepcopy(self.T) def reset_to_best(self): ''' Overwrites the current instructions with best previous ones. ''' #print ('Patience ran out... resetting to best previous instructions.') self.gates = copy.deepcopy(self.best_previous_instructions['gates']) self.positions = copy.deepcopy(self.best_previous_instructions['positions']) self.patience = copy.deepcopy(self.starting_patience) self.update_T(update_type='patience', best_temp=copy.deepcopy(self.best_previous_instructions['T'])) def get_new_instructions(self, number=None): ''' Returns a a clifford instruction set, a dictionary of gates and qubit positions for building a clifford circuit ''' mu = self.mu sigma = self.sigma n_qubits = self.n_qubits instruction = {} gates = self.get_random_gates(number=number) q_positions = self.get_random_positions(gates) assert(len(q_positions) == len(gates)) instruction['gates'] = gates instruction['positions'] = q_positions # instruction['n_qubits'] = n_qubits # instruction['patience'] = patience # instruction['best_previous_options'] = {} return instruction def replace_cg_w_ncg(self, gate_id): ''' replaces a set of Clifford gates with corresponding non-Cliffords ''' print("gates before", self.gates, flush=True) gate = self.gates[gate_id] if gate == 'X': gate = "Rx" elif gate == 'Y': gate = "Ry" elif gate == 'Z': gate = "Rz" elif gate == 'S': gate = "S_nc" #gate = "Rz" elif gate == 'H': gate = "H_nc" # this does not work??????? # gate = "Ry" elif gate == 'CX': gate = "CRx" elif gate == 'CY': gate = "CRy" elif gate == 'CZ': gate = "CRz" elif gate == 'SWAP':#find a way to change this as well pass # gate = "SWAP" elif "UCC2c" in str(gate): pre_gate = gate.split("_")[0] mid_gate = gate.split("_")[-1] gate = pre_gate + "_" + "UCC2" + "_" +mid_gate elif "UCC4c" in str(gate): pre_gate = gate.split("_")[0] mid_gate = gate.split("_")[-1] gate = pre_gate + "_" + "UCC4" + "_" + mid_gate self.gates[gate_id] = gate print("gates after", self.gates, flush=True) def build_circuit(instructions): ''' constructs a tequila circuit from a clifford instruction set ''' gates = instructions.gates q_positions = instructions.positions init_angles = {} clifford_circuit = tq.QCircuit() # for i in range(1, len(gates)): # TODO len(q_positions) not == len(gates) for i in range(len(gates)): if len(q_positions[i]) == 2: q1, q2 = q_positions[i] elif len(q_positions[i]) == 1: q1 = q_positions[i] q2 = None elif not len(q_positions[i]) == 4: raise Exception("q_positions[i] must have length 1, 2 or 4...") if gates[i] == 'X': clifford_circuit += tq.gates.X(q1) if gates[i] == 'Y': clifford_circuit += tq.gates.Y(q1) if gates[i] == 'Z': clifford_circuit += tq.gates.Z(q1) if gates[i] == 'S': clifford_circuit += tq.gates.S(q1) if gates[i] == 'H': clifford_circuit += tq.gates.H(q1) if gates[i] == 'CX': clifford_circuit += tq.gates.CX(q1, q2) if gates[i] == 'CY': #using generators clifford_circuit += tq.gates.S(q2) clifford_circuit += tq.gates.CX(q1, q2) clifford_circuit += tq.gates.S(q2).dagger() if gates[i] == 'CZ': #using generators clifford_circuit += tq.gates.H(q2) clifford_circuit += tq.gates.CX(q1, q2) clifford_circuit += tq.gates.H(q2) if gates[i] == 'SWAP': clifford_circuit += tq.gates.CX(q1, q2) clifford_circuit += tq.gates.CX(q2, q1) clifford_circuit += tq.gates.CX(q1, q2) if "UCC2c" in str(gates[i]) or "UCC4c" in str(gates[i]): clifford_circuit += get_clifford_UCC_circuit(gates[i], q_positions[i]) # NON-CLIFFORD STUFF FROM HERE ON global global_seed if gates[i] == "S_nc": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.S(q1) clifford_circuit += tq.gates.Rz(angle=var_name, target=q1) if gates[i] == "H_nc": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.H(q1) clifford_circuit += tq.gates.Ry(angle=var_name, target=q1) if gates[i] == "Rx": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.X(q1) clifford_circuit += tq.gates.Rx(angle=var_name, target=q1) if gates[i] == "Ry": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.Y(q1) clifford_circuit += tq.gates.Ry(angle=var_name, target=q1) if gates[i] == "Rz": global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0 clifford_circuit += tq.gates.Z(q1) clifford_circuit += tq.gates.Rz(angle=var_name, target=q1) if gates[i] == "CRx": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = np.pi clifford_circuit += tq.gates.Rx(angle=var_name, target=q2, control=q1) if gates[i] == "CRy": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = np.pi clifford_circuit += tq.gates.Ry(angle=var_name, target=q2, control=q1) if gates[i] == "CRz": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = np.pi clifford_circuit += tq.gates.Rz(angle=var_name, target=q2, control=q1) def get_ucc_init_angles(gate): angle = None pre_gate = gate.split("_")[0] mid_gate = gate.split("_")[-1] if mid_gate == 'Z': angle = 0. elif mid_gate == 'S': angle = 0. elif mid_gate == 'S-dag': angle = 0. else: raise Exception("This should not happen -- center/mid gate should be Z,S,S_dag.") return angle if "UCC2_" in str(gates[i]) or "UCC4_" in str(gates[i]): uccc_circuit = get_non_clifford_UCC_circuit(gates[i], q_positions[i]) clifford_circuit += uccc_circuit try: var_name = uccc_circuit.extract_variables()[0] init_angles[var_name]= get_ucc_init_angles(gates[i]) except: init_angles = {} return clifford_circuit, init_angles def get_non_clifford_UCC_circuit(gate, positions): """ """ pre_cir_dic = {"X":tq.gates.X, "Y":tq.gates.Y, "H":tq.gates.H, "I":None} pre_gate = gate.split("_")[0] pre_gates = pre_gate.split(*"#") pre_circuit = tq.QCircuit() for i, pos in enumerate(positions): try: pre_circuit += pre_cir_dic[pre_gates[i]](pos) except: pass for i, pos in enumerate(positions[:-1]): pre_circuit += tq.gates.CX(pos, positions[i+1]) global global_seed mid_gate = gate.split("_")[-1] mid_circuit = tq.QCircuit() if mid_gate == "S": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit += tq.gates.S(positions[-1]) mid_circuit += tq.gates.Rz(angle=tq.Variable(var_name), target=positions[-1]) elif mid_gate == "S-dag": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit += tq.gates.S(positions[-1]).dagger() mid_circuit += tq.gates.Rz(angle=tq.Variable(var_name), target=positions[-1]) elif mid_gate == "Z": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit += tq.gates.Z(positions[-1]) mid_circuit += tq.gates.Rz(angle=tq.Variable(var_name), target=positions[-1]) return pre_circuit + mid_circuit + pre_circuit.dagger() def get_string_Cliff_ucc(gate): """ this function randomly sample basis change and mid circuit elements for a ucc-type clifford circuit and adds it to the gate """ pre_circ_comp = ["X", "Y", "H", "I"] mid_circ_comp = ["S", "S-dag", "Z"] p = None if "UCC2c" in gate: p = random.sample(pre_circ_comp, k=2) elif "UCC4c" in gate: p = random.sample(pre_circ_comp, k=4) pre_gate = "#".join([str(item) for item in p]) mid_gate = random.sample(mid_circ_comp, k=1)[0] return str(pre_gate + "_" + gate + "_" + mid_gate) def get_string_ucc(gate): """ this function randomly sample basis change and mid circuit elements for a ucc-type clifford circuit and adds it to the gate """ pre_circ_comp = ["X", "Y", "H", "I"] p = None if "UCC2" in gate: p = random.sample(pre_circ_comp, k=2) elif "UCC4" in gate: p = random.sample(pre_circ_comp, k=4) pre_gate = "#".join([str(item) for item in p]) mid_gate = str(random.random() * 2 * np.pi) return str(pre_gate + "_" + gate + "_" + mid_gate) def get_clifford_UCC_circuit(gate, positions): """ This function creates an approximate UCC excitation circuit using only clifford Gates """ #pre_circ_comp = ["X", "Y", "H", "I"] pre_cir_dic = {"X":tq.gates.X, "Y":tq.gates.Y, "H":tq.gates.H, "I":None} pre_gate = gate.split("_")[0] pre_gates = pre_gate.split(*"#") #pre_gates = [] #if gate == "UCC2": # pre_gates = random.choices(pre_circ_comp, k=2) #if gate == "UCC4": # pre_gates = random.choices(pre_circ_comp, k=4) pre_circuit = tq.QCircuit() for i, pos in enumerate(positions): try: pre_circuit += pre_cir_dic[pre_gates[i]](pos) except: pass for i, pos in enumerate(positions[:-1]): pre_circuit += tq.gates.CX(pos, positions[i+1]) #mid_circ_comp = ["S", "S-dag", "Z"] #mid_gate = random.sample(mid_circ_comp, k=1)[0] mid_gate = gate.split("_")[-1] mid_circuit = tq.QCircuit() if mid_gate == "S": mid_circuit += tq.gates.S(positions[-1]) elif mid_gate == "S-dag": mid_circuit += tq.gates.S(positions[-1]).dagger() elif mid_gate == "Z": mid_circuit += tq.gates.Z(positions[-1]) return pre_circuit + mid_circuit + pre_circuit.dagger() def get_UCC_circuit(gate, positions): """ This function creates an UCC excitation circuit """ #pre_circ_comp = ["X", "Y", "H", "I"] pre_cir_dic = {"X":tq.gates.X, "Y":tq.gates.Y, "H":tq.gates.H, "I":None} pre_gate = gate.split("_")[0] pre_gates = pre_gate.split(*"#") pre_circuit = tq.QCircuit() for i, pos in enumerate(positions): try: pre_circuit += pre_cir_dic[pre_gates[i]](pos) except: pass for i, pos in enumerate(positions[:-1]): pre_circuit += tq.gates.CX(pos, positions[i+1]) mid_gate_val = gate.split("_")[-1] global global_seed np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit = tq.gates.Rz(target=positions[-1], angle=tq.Variable(var_name)) # mid_circ_comp = ["S", "S-dag", "Z"] # mid_gate = random.sample(mid_circ_comp, k=1)[0] # mid_circuit = tq.QCircuit() # if mid_gate == "S": # mid_circuit += tq.gates.S(positions[-1]) # elif mid_gate == "S-dag": # mid_circuit += tq.gates.S(positions[-1]).dagger() # elif mid_gate == "Z": # mid_circuit += tq.gates.Z(positions[-1]) return pre_circuit + mid_circuit + pre_circuit.dagger() def schedule_actions_ratio(epoch: int, action_options: list = ['delete', 'change', 'add'], decay: int = 30, steady_ratio: Union[tuple, list] = [0.2, 0.6, 0.2]) -> list: delete, change, add = tuple(steady_ratio) actions_ratio = [] for action in action_options: if action == 'delete': actions_ratio += [ delete*(1-np.exp(-1*epoch / decay)) ] elif action == 'change': actions_ratio += [ change*(1-np.exp(-1*epoch / decay)) ] elif action == 'add': actions_ratio += [ (1-add)*np.exp(-1*epoch / decay) + add ] else: print('Action type ', action, ' not defined!') # unnecessary for current schedule # if not np.isclose(np.sum(actions_ratio), 1.0): # actions_ratio /= np.sum(actions_ratio) return actions_ratio def get_action(ratio: list = [0.20,0.60,0.20]): ''' randomly chooses an action from delete, change, add ratio denotes the multinomial probabilities ''' choice = np.random.multinomial(n=1, pvals = ratio, size = 1) index = np.where(choice[0] == 1) action_options = ['delete', 'change', 'add'] action = action_options[index[0].item()] return action def get_prob_acceptance(E_curr, E_prev, T, reference_energy): ''' Computes acceptance probability of a certain action based on change in energy ''' delta_E = E_curr - E_prev prob = 0 if delta_E < 0 and E_curr < reference_energy: prob = 1 else: if E_curr < reference_energy: prob = np.exp(-delta_E/T) else: prob = 0 return prob def perform_folding(hamiltonian, circuit): # QubitHamiltonian -> ParamQubitHamiltonian param_hamiltonian = convert_tq_QH_to_PQH(hamiltonian) gates = circuit.gates # Go backwards gates.reverse() for gate in gates: # print("\t folding", gate) param_hamiltonian = (fold_unitary_into_hamiltonian(gate, param_hamiltonian)) # hamiltonian = convert_PQH_to_tq_QH(param_hamiltonian)() hamiltonian = param_hamiltonian return hamiltonian def evaluate_fitness(instructions, hamiltonian: tq.QubitHamiltonian, type_energy_eval: str, cluster_circuit: tq.QCircuit=None) -> tuple: ''' Evaluates fitness=objective=energy given a system for a set of instructions ''' #print ("evaluating fitness") n_qubits = instructions.n_qubits clifford_circuit, init_angles = build_circuit(instructions) # tq.draw(clifford_circuit, backend="cirq") ## TODO check if cluster_circuit is parametrized t0 = time() t1 = None folded_hamiltonian = perform_folding(hamiltonian, clifford_circuit) t1 = time() #print ("\tfolding took ", t1-t0) parametrized = len(clifford_circuit.extract_variables()) > 0 initial_guess = None if not parametrized: folded_hamiltonian = (convert_PQH_to_tq_QH(folded_hamiltonian))() elif parametrized: # TODO clifford_circuit is both ref + rest; so nomenclature is shit here variables = [gate.extract_variables() for gate in clifford_circuit.gates\ if gate.extract_variables()] variables = np.array(variables).flatten().tolist() # TODO this initial_guess is absolutely useless rn and is just causing problems if called initial_guess = { k: 0.1 for k in variables } if instructions.best_reference_wfn is not None: initial_guess = instructions.best_reference_wfn E_new, optimal_state = minimize_energy(hamiltonian=folded_hamiltonian, n_qubits=n_qubits, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit, initial_guess=initial_guess,\ initial_mixed_angles=init_angles) t2 = time() #print ("evaluated fitness; comp was ", t2-t1) #print ("current fitness: ", E_new) return E_new, optimal_state
26,497
34.096689
191
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_2.7/hacked_openfermion_qubit_operator.py
import tequila as tq import sympy import copy #from param_hamiltonian import get_geometry, generate_ucc_ansatz from hacked_openfermion_symbolic_operator import SymbolicOperator # Define products of all Pauli operators for symbolic multiplication. _PAULI_OPERATOR_PRODUCTS = { ('I', 'I'): (1., 'I'), ('I', 'X'): (1., 'X'), ('X', 'I'): (1., 'X'), ('I', 'Y'): (1., 'Y'), ('Y', 'I'): (1., 'Y'), ('I', 'Z'): (1., 'Z'), ('Z', 'I'): (1., 'Z'), ('X', 'X'): (1., 'I'), ('Y', 'Y'): (1., 'I'), ('Z', 'Z'): (1., 'I'), ('X', 'Y'): (1.j, 'Z'), ('X', 'Z'): (-1.j, 'Y'), ('Y', 'X'): (-1.j, 'Z'), ('Y', 'Z'): (1.j, 'X'), ('Z', 'X'): (1.j, 'Y'), ('Z', 'Y'): (-1.j, 'X') } _clifford_h_products = { ('I') : (1., 'I'), ('X') : (1., 'Z'), ('Y') : (-1., 'Y'), ('Z') : (1., 'X') } _clifford_s_products = { ('I') : (1., 'I'), ('X') : (-1., 'Y'), ('Y') : (1., 'X'), ('Z') : (1., 'Z') } _clifford_s_dag_products = { ('I') : (1., 'I'), ('X') : (1., 'Y'), ('Y') : (-1., 'X'), ('Z') : (1., 'Z') } _clifford_cx_products = { ('I', 'I'): (1., 'I', 'I'), ('I', 'X'): (1., 'I', 'X'), ('I', 'Y'): (1., 'Z', 'Y'), ('I', 'Z'): (1., 'Z', 'Z'), ('X', 'I'): (1., 'X', 'X'), ('X', 'X'): (1., 'X', 'I'), ('X', 'Y'): (1., 'Y', 'Z'), ('X', 'Z'): (-1., 'Y', 'Y'), ('Y', 'I'): (1., 'Y', 'X'), ('Y', 'X'): (1., 'Y', 'I'), ('Y', 'Y'): (-1., 'X', 'Z'), ('Y', 'Z'): (1., 'X', 'Y'), ('Z', 'I'): (1., 'Z', 'I'), ('Z', 'X'): (1., 'Z', 'X'), ('Z', 'Y'): (1., 'I', 'Y'), ('Z', 'Z'): (1., 'I', 'Z'), } _clifford_cy_products = { ('I', 'I'): (1., 'I', 'I'), ('I', 'X'): (1., 'Z', 'X'), ('I', 'Y'): (1., 'I', 'Y'), ('I', 'Z'): (1., 'Z', 'Z'), ('X', 'I'): (1., 'X', 'Y'), ('X', 'X'): (-1., 'Y', 'Z'), ('X', 'Y'): (1., 'X', 'I'), ('X', 'Z'): (-1., 'Y', 'X'), ('Y', 'I'): (1., 'Y', 'Y'), ('Y', 'X'): (1., 'X', 'Z'), ('Y', 'Y'): (1., 'Y', 'I'), ('Y', 'Z'): (-1., 'X', 'X'), ('Z', 'I'): (1., 'Z', 'I'), ('Z', 'X'): (1., 'I', 'X'), ('Z', 'Y'): (1., 'Z', 'Y'), ('Z', 'Z'): (1., 'I', 'Z'), } _clifford_cz_products = { ('I', 'I'): (1., 'I', 'I'), ('I', 'X'): (1., 'Z', 'X'), ('I', 'Y'): (1., 'Z', 'Y'), ('I', 'Z'): (1., 'I', 'Z'), ('X', 'I'): (1., 'X', 'Z'), ('X', 'X'): (-1., 'Y', 'Y'), ('X', 'Y'): (-1., 'Y', 'X'), ('X', 'Z'): (1., 'X', 'I'), ('Y', 'I'): (1., 'Y', 'Z'), ('Y', 'X'): (-1., 'X', 'Y'), ('Y', 'Y'): (1., 'X', 'X'), ('Y', 'Z'): (1., 'Y', 'I'), ('Z', 'I'): (1., 'Z', 'I'), ('Z', 'X'): (1., 'I', 'X'), ('Z', 'Y'): (1., 'I', 'Y'), ('Z', 'Z'): (1., 'Z', 'Z'), } COEFFICIENT_TYPES = (int, float, complex, sympy.Expr, tq.Variable) class ParamQubitHamiltonian(SymbolicOperator): @property def actions(self): """The allowed actions.""" return ('X', 'Y', 'Z') @property def action_strings(self): """The string representations of the allowed actions.""" return ('X', 'Y', 'Z') @property def action_before_index(self): """Whether action comes before index in string representations.""" return True @property def different_indices_commute(self): """Whether factors acting on different indices commute.""" return True def renormalize(self): """Fix the trace norm of an operator to 1""" norm = self.induced_norm(2) if numpy.isclose(norm, 0.0): raise ZeroDivisionError('Cannot renormalize empty or zero operator') else: self /= norm def _simplify(self, term, coefficient=1.0): """Simplify a term using commutator and anti-commutator relations.""" if not term: return coefficient, term term = sorted(term, key=lambda factor: factor[0]) new_term = [] left_factor = term[0] for right_factor in term[1:]: left_index, left_action = left_factor right_index, right_action = right_factor # Still on the same qubit, keep simplifying. if left_index == right_index: new_coefficient, new_action = _PAULI_OPERATOR_PRODUCTS[ left_action, right_action] left_factor = (left_index, new_action) coefficient *= new_coefficient # Reached different qubit, save result and re-initialize. else: if left_action != 'I': new_term.append(left_factor) left_factor = right_factor # Save result of final iteration. if left_factor[1] != 'I': new_term.append(left_factor) return coefficient, tuple(new_term) def _clifford_simplify_h(self, qubit): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 for left, right in term: if left == qubit: coeff, new_pauli = _clifford_h_products[right] new_term.append(tuple((left, new_pauli))) else: new_term.append(tuple((left,right))) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self def _clifford_simplify_s(self, qubit): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 for left, right in term: if left == qubit: coeff, new_pauli = _clifford_s_products[right] new_term.append(tuple((left, new_pauli))) else: new_term.append(tuple((left,right))) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self def _clifford_simplify_s_dag(self, qubit): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 for left, right in term: if left == qubit: coeff, new_pauli = _clifford_s_dag_products[right] new_term.append(tuple((left, new_pauli))) else: new_term.append(tuple((left,right))) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self def _clifford_simplify_control_g(self, axis, control_q, target_q): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 target = "I" control = "I" for left, right in term: if left == control_q: control = right elif left == target_q: target = right else: new_term.append(tuple((left,right))) new_c = "I" new_t = "I" if not (target == "I" and control == "I"): if axis == "X": coeff, new_c, new_t = _clifford_cx_products[control, target] if axis == "Y": coeff, new_c, new_t = _clifford_cy_products[control, target] if axis == "Z": coeff, new_c, new_t = _clifford_cz_products[control, target] if new_c != "I": new_term.append(tuple((control_q, new_c))) if new_t != "I": new_term.append(tuple((target_q, new_t))) new_term = sorted(new_term, key=lambda factor: factor[0]) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self if __name__ == "__main__": """geometry = get_geometry("H2", 0.714) print(geometry) basis_set = 'sto-3g' ref_anz, uccsd_anz, ham = generate_ucc_ansatz(geometry, basis_set) print(ham) b_ham = tq.grouping.binary_rep.BinaryHamiltonian.init_from_qubit_hamiltonian(ham) c_ham = tq.grouping.binary_rep.BinaryHamiltonian.init_from_qubit_hamiltonian(ham) print(b_ham) print(b_ham.get_binary()) print(b_ham.get_coeff()) param = uccsd_anz.extract_variables() print(param) for term in b_ham.binary_terms: print(term.coeff) term.set_coeff(param[0]) print(term.coeff) print(b_ham.get_coeff()) d_ham = c_ham.to_qubit_hamiltonian() + b_ham.to_qubit_hamiltonian() """ term = [(2,'X'), (0,'Y'), (3, 'Z')] coeff = tq.Variable("a") coeff = coeff *2.j print(coeff) print(type(coeff)) print(coeff({"a":1})) ham = ParamQubitHamiltonian(term= term, coefficient=coeff) print(ham.terms) print(str(ham)) for term in ham.terms: print(ham.terms[term]({"a":1,"b":2})) term = [(2,'X'), (0,'Z'), (3, 'Z')] coeff = tq.Variable("b") print(coeff({"b":1})) b_ham = ParamQubitHamiltonian(term= term, coefficient=coeff) print(b_ham.terms) print(str(b_ham)) for term in b_ham.terms: print(b_ham.terms[term]({"a":1,"b":2})) coeff = tq.Variable("a")*tq.Variable("b") print(coeff) print(coeff({"a":1,"b":2})) ham *= b_ham print(ham.terms) print(str(ham)) for term in ham.terms: coeff = (ham.terms[term]) print(coeff) print(coeff({"a":1,"b":2})) ham = ham*2. print(ham.terms) print(str(ham))
9,918
29.614198
85
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_2.7/HEA.py
import tequila as tq import numpy as np from tequila import gates as tq_g from tequila.objective.objective import Variable def generate_HEA(num_qubits, circuit_id=11, num_layers=1): """ This function generates different types of hardware efficient circuits as in this paper https://onlinelibrary.wiley.com/doi/full/10.1002/qute.201900070 param: num_qubits (int) -> the number of qubits in the circuit param: circuit_id (int) -> the type of hardware efficient circuit param: num_layers (int) -> the number of layers of the HEA input: num_qubits -> 4 circuit_id -> 11 num_layers -> 1 returns: ansatz (tq.QCircuit()) -> a circuit as shown below 0: ───Ry(0.318309886183791*pi*f((y0,))_0)───Rz(0.318309886183791*pi*f((z0,))_1)───@───────────────────────────────────────────────────────────────────────────────────── │ 1: ───Ry(0.318309886183791*pi*f((y1,))_2)───Rz(0.318309886183791*pi*f((z1,))_3)───X───Ry(0.318309886183791*pi*f((y4,))_8)────Rz(0.318309886183791*pi*f((z4,))_9)────@─── │ 2: ───Ry(0.318309886183791*pi*f((y2,))_4)───Rz(0.318309886183791*pi*f((z2,))_5)───@───Ry(0.318309886183791*pi*f((y5,))_10)───Rz(0.318309886183791*pi*f((z5,))_11)───X─── │ 3: ───Ry(0.318309886183791*pi*f((y3,))_6)───Rz(0.318309886183791*pi*f((z3,))_7)───X───────────────────────────────────────────────────────────────────────────────────── """ circuit = tq.QCircuit() qubits = [i for i in range(num_qubits)] if circuit_id == 1: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 2: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.CNOT(target=qubit, control=qubits[ind]) return circuit elif circuit_id == 3: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=qubit, control=qubits[ind]) count += 1 return circuit elif circuit_id == 4: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=qubit, control=qubits[ind]) count += 1 return circuit elif circuit_id == 5: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): for target in qubits: if control != target: variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=target, control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 6: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=qubits[ind+1], control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=qubits[ind+1], control=control) count += 1 return circuit elif circuit_id == 7: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): for target in qubits: if control != target: variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=target, control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 8: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=qubits[ind+1], control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=qubits[ind+1], control=control) count += 1 return circuit elif circuit_id == 9: count = 0 for _ in range(num_layers): for qubit in qubits: circuit += tq_g.H(qubit) for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.Z(target=qubit, control=qubits[ind]) for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 10: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.Z(target=qubit, control=qubits[ind]) circuit += tq_g.Z(target=qubits[0], control=qubits[-1]) for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 11: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: circuit += tq_g.X(target=qubits[ind+1], control=control) for ind, qubit in enumerate(qubits[1:-1]): variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: circuit += tq_g.X(target=qubits[ind+1], control=control) return circuit elif circuit_id == 12: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: circuit += tq_g.Z(target=qubits[ind+1], control=control) for ind, control in enumerate(qubits[1:-1]): variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = control) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = control) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: circuit += tq_g.Z(target=qubits[ind+1], control=control) return circuit elif circuit_id == 13: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubit, control=qubits[ind]) count += 1 variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubits[0], control=qubits[-1]) count += 1 for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=qubit, target=qubits[ind]) count += 1 variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=qubits[0], target=qubits[-1]) count += 1 return circuit elif circuit_id == 14: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubit, control=qubits[ind]) count += 1 variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubits[0], control=qubits[-1]) count += 1 for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=qubit, target=qubits[ind]) count += 1 variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=qubits[0], target=qubits[-1]) count += 1 return circuit elif circuit_id == 15: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.X(target=qubit, control=qubits[ind]) circuit += tq_g.X(control=qubits[-1], target=qubits[0]) for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.X(control=qubit, target=qubits[ind]) circuit += tq_g.X(target=qubits[-1], control=qubits[0]) return circuit elif circuit_id == 16: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=control, target=qubits[ind+1]) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=control, target=qubits[ind+1]) count += 1 return circuit elif circuit_id == 17: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=control, target=qubits[ind+1]) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=control, target=qubits[ind+1]) count += 1 return circuit elif circuit_id == 18: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[:-1]): variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubit, control=qubits[ind+1]) count += 1 variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubits[-1], control=qubits[0]) count += 1 return circuit elif circuit_id == 19: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[:-1]): variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubit, control=qubits[ind+1]) count += 1 variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubits[-1], control=qubits[0]) count += 1 return circuit
18,425
45.530303
172
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_2.7/grad_hacked.py
from tequila.circuit.compiler import CircuitCompiler from tequila.objective.objective import Objective, ExpectationValueImpl, Variable, \ assign_variable, identity, FixedVariable from tequila import TequilaException from tequila.objective import QTensor from tequila.simulators.simulator_api import compile import typing from numpy import vectorize from tequila.autograd_imports import jax, __AUTOGRAD__BACKEND__ def grad(objective: typing.Union[Objective, QTensor], variable: Variable = None, no_compile=False, *args, **kwargs): ''' wrapper function for getting the gradients of Objectives,ExpectationValues, Unitaries (including single gates), and Transforms. :param obj (QCircuit,ParametrizedGateImpl,Objective,ExpectationValue,Transform,Variable): structure to be differentiated :param variables (list of Variable): parameter with respect to which obj should be differentiated. default None: total gradient. return: dictionary of Objectives, if called on gate, circuit, exp.value, or objective; if Variable or Transform, returns number. ''' if variable is None: # None means that all components are created variables = objective.extract_variables() result = {} if len(variables) == 0: raise TequilaException("Error in gradient: Objective has no variables") for k in variables: assert (k is not None) result[k] = grad(objective, k, no_compile=no_compile) return result else: variable = assign_variable(variable) if isinstance(objective, QTensor): f = lambda x: grad(objective=x, variable=variable, *args, **kwargs) ff = vectorize(f) return ff(objective) if variable not in objective.extract_variables(): return Objective() if no_compile: compiled = objective else: compiler = CircuitCompiler(multitarget=True, trotterized=True, hadamard_power=True, power=True, controlled_phase=True, controlled_rotation=True, gradient_mode=True) compiled = compiler(objective, variables=[variable]) if variable not in compiled.extract_variables(): raise TequilaException("Error in taking gradient. Objective does not depend on variable {} ".format(variable)) if isinstance(objective, ExpectationValueImpl): return __grad_expectationvalue(E=objective, variable=variable) elif objective.is_expectationvalue(): return __grad_expectationvalue(E=compiled.args[-1], variable=variable) elif isinstance(compiled, Objective) or (hasattr(compiled, "args") and hasattr(compiled, "transformation")): return __grad_objective(objective=compiled, variable=variable) else: raise TequilaException("Gradient not implemented for other types than ExpectationValue and Objective.") def __grad_objective(objective: Objective, variable: Variable): args = objective.args transformation = objective.transformation dO = None processed_expectationvalues = {} for i, arg in enumerate(args): if __AUTOGRAD__BACKEND__ == "jax": df = jax.grad(transformation, argnums=i, holomorphic=True) elif __AUTOGRAD__BACKEND__ == "autograd": df = jax.grad(transformation, argnum=i) else: raise TequilaException("Can't differentiate without autograd or jax") # We can detect one simple case where the outer derivative is const=1 if transformation is None or transformation == identity: outer = 1.0 else: outer = Objective(args=args, transformation=df) if hasattr(arg, "U"): # save redundancies if arg in processed_expectationvalues: inner = processed_expectationvalues[arg] else: inner = __grad_inner(arg=arg, variable=variable) processed_expectationvalues[arg] = inner else: # this means this inner derivative is purely variable dependent inner = __grad_inner(arg=arg, variable=variable) if inner == 0.0: # don't pile up zero expectationvalues continue if dO is None: dO = outer * inner else: dO = dO + outer * inner if dO is None: raise TequilaException("caught None in __grad_objective") return dO # def __grad_vector_objective(objective: Objective, variable: Variable): # argsets = objective.argsets # transformations = objective._transformations # outputs = [] # for pos in range(len(objective)): # args = argsets[pos] # transformation = transformations[pos] # dO = None # # processed_expectationvalues = {} # for i, arg in enumerate(args): # if __AUTOGRAD__BACKEND__ == "jax": # df = jax.grad(transformation, argnums=i) # elif __AUTOGRAD__BACKEND__ == "autograd": # df = jax.grad(transformation, argnum=i) # else: # raise TequilaException("Can't differentiate without autograd or jax") # # # We can detect one simple case where the outer derivative is const=1 # if transformation is None or transformation == identity: # outer = 1.0 # else: # outer = Objective(args=args, transformation=df) # # if hasattr(arg, "U"): # # save redundancies # if arg in processed_expectationvalues: # inner = processed_expectationvalues[arg] # else: # inner = __grad_inner(arg=arg, variable=variable) # processed_expectationvalues[arg] = inner # else: # # this means this inner derivative is purely variable dependent # inner = __grad_inner(arg=arg, variable=variable) # # if inner == 0.0: # # don't pile up zero expectationvalues # continue # # if dO is None: # dO = outer * inner # else: # dO = dO + outer * inner # # if dO is None: # dO = Objective() # outputs.append(dO) # if len(outputs) == 1: # return outputs[0] # return outputs def __grad_inner(arg, variable): ''' a modified loop over __grad_objective, which gets derivatives all the way down to variables, return 1 or 0 when a variable is (isnt) identical to var. :param arg: a transform or variable object, to be differentiated :param variable: the Variable with respect to which par should be differentiated. :ivar var: the string representation of variable ''' assert (isinstance(variable, Variable)) if isinstance(arg, Variable): if arg == variable: return 1.0 else: return 0.0 elif isinstance(arg, FixedVariable): return 0.0 elif isinstance(arg, ExpectationValueImpl): return __grad_expectationvalue(arg, variable=variable) elif hasattr(arg, "abstract_expectationvalue"): E = arg.abstract_expectationvalue dE = __grad_expectationvalue(E, variable=variable) return compile(dE, **arg._input_args) else: return __grad_objective(objective=arg, variable=variable) def __grad_expectationvalue(E: ExpectationValueImpl, variable: Variable): ''' implements the analytic partial derivative of a unitary as it would appear in an expectation value. See the paper. :param unitary: the unitary whose gradient should be obtained :param variables (list, dict, str): the variables with respect to which differentiation should be performed. :return: vector (as dict) of dU/dpi as Objective (without hamiltonian) ''' hamiltonian = E.H unitary = E.U if not (unitary.verify()): raise TequilaException("error in grad_expectationvalue unitary is {}".format(unitary)) # fast return if possible if variable not in unitary.extract_variables(): return 0.0 param_gates = unitary._parameter_map[variable] dO = Objective() for idx_g in param_gates: idx, g = idx_g dOinc = __grad_shift_rule(unitary, g, idx, variable, hamiltonian) dO += dOinc assert dO is not None return dO def __grad_shift_rule(unitary, g, i, variable, hamiltonian): ''' function for getting the gradients of directly differentiable gates. Expects precompiled circuits. :param unitary: QCircuit: the QCircuit object containing the gate to be differentiated :param g: a parametrized: the gate being differentiated :param i: Int: the position in unitary at which g appears :param variable: Variable or String: the variable with respect to which gate g is being differentiated :param hamiltonian: the hamiltonian with respect to which unitary is to be measured, in the case that unitary is contained within an ExpectationValue :return: an Objective, whose calculation yields the gradient of g w.r.t variable ''' # possibility for overwride in custom gate construction if hasattr(g, "shifted_gates"): inner_grad = __grad_inner(g.parameter, variable) shifted = g.shifted_gates() dOinc = Objective() for x in shifted: w, g = x Ux = unitary.replace_gates(positions=[i], circuits=[g]) wx = w * inner_grad Ex = Objective.ExpectationValue(U=Ux, H=hamiltonian) dOinc += wx * Ex return dOinc else: raise TequilaException('No shift found for gate {}\nWas the compiler called?'.format(g))
9,886
38.548
132
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_2.7/vqe_utils.py
import tequila as tq import numpy as np from hacked_openfermion_qubit_operator import ParamQubitHamiltonian from openfermion import QubitOperator from HEA import * def get_ansatz_circuit(ansatz_type, geometry, basis_set=None, trotter_steps = 1, name=None, circuit_id=None,num_layers=1): """ This function generates the ansatz for the molecule and the Hamiltonian param: ansatz_type (str) -> the type of the ansatz ('UCCSD, UpCCGSD, SPA, HEA') param: geometry (str) -> the geometry of the molecule param: basis_set (str) -> the basis set for wchich the ansatz has to generated param: trotter_steps (int) -> the number of trotter step to be used in the trotter decomposition param: name (str) -> the name for the madness molecule param: circuit_id (int) -> the type of hardware efficient ansatz param: num_layers (int) -> the number of layers of the HEA e.g.: input: ansatz_type -> "UCCSD" geometry -> "H 0.0 0.0 0.0\nH 0.0 0.0 0.714" basis_set -> 'sto-3g' trotter_steps -> 1 name -> None circuit_id -> None num_layers -> 1 returns: ucc_ansatz (tq.QCircuit()) -> a circuit printed below: circuit: FermionicExcitation(target=(0, 1, 2, 3), control=(), parameter=Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = []) FermionicExcitation(target=(0, 1, 2, 3), control=(), parameter=Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = []) Hamiltonian (tq.QubitHamiltonian()) -> -0.0621+0.1755Z(0)+0.1755Z(1)-0.2358Z(2)-0.2358Z(3)+0.1699Z(0)Z(1) +0.0449Y(0)X(1)X(2)Y(3)-0.0449Y(0)Y(1)X(2)X(3)-0.0449X(0)X(1)Y(2)Y(3) +0.0449X(0)Y(1)Y(2)X(3)+0.1221Z(0)Z(2)+0.1671Z(0)Z(3)+0.1671Z(1)Z(2) +0.1221Z(1)Z(3)+0.1756Z(2)Z(3) fci_ener (float) -> """ ham = tq.QubitHamiltonian() fci_ener = 0.0 ansatz = tq.QCircuit() if ansatz_type == "UCCSD": molecule = tq.Molecule(geometry=geometry, basis_set=basis_set) ansatz = molecule.make_uccsd_ansatz(trotter_steps) ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy(method="fci") elif ansatz_type == "UCCS": molecule = tq.Molecule(geometry=geometry, basis_set=basis_set, backend='psi4') ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy("fci") indices = molecule.make_upccgsd_indices(key='UCCS') print("indices are:", indices) ansatz = molecule.make_upccgsd_layer(indices=indices, include_singles=True, include_doubles=False) elif ansatz_type == "UpCCGSD": molecule = tq.Molecule(name=name, geometry=geometry, n_pno=None) ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy("fci") ansatz = molecule.make_upccgsd_ansatz() elif ansatz_type == "SPA": molecule = tq.Molecule(name=name, geometry=geometry, n_pno=None) ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy("fci") ansatz = molecule.make_upccgsd_ansatz(name="SPA") elif ansatz_type == "HEA": molecule = tq.Molecule(geometry=geometry, basis_set=basis_set) ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy(method="fci") ansatz = generate_HEA(molecule.n_orbitals * 2, circuit_id) else: raise Exception("not implemented any other ansatz, please choose from 'UCCSD, UpCCGSD, SPA, HEA'") return ansatz, ham, fci_ener def get_generator_for_gates(unitary): """ This function takes a unitary gate and returns the generator of the the gate so that it can be padded to the Hamiltonian param: unitary (tq.QGateImpl()) -> the unitary circuit element that has to be converted to a paulistring e.g.: input: unitary -> a FermionicGateImpl object as the one printed below FermionicExcitation(target=(0, 1, 2, 3), control=(), parameter=Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = []) returns: parameter (tq.Variable()) -> (1, 0, 1, 0) generator (tq.QubitHamiltonian()) -> -0.1250Y(0)Y(1)Y(2)X(3)+0.1250Y(0)X(1)Y(2)Y(3) +0.1250X(0)X(1)Y(2)X(3)+0.1250X(0)Y(1)Y(2)Y(3) -0.1250Y(0)X(1)X(2)X(3)-0.1250Y(0)Y(1)X(2)Y(3) -0.1250X(0)Y(1)X(2)X(3)+0.1250X(0)X(1)X(2)Y(3) null_proj (tq.QubitHamiltonian()) -> -0.1250Z(0)Z(1)+0.1250Z(1)Z(3)+0.1250Z(0)Z(3) +0.1250Z(1)Z(2)+0.1250Z(0)Z(2)-0.1250Z(2)Z(3) -0.1250Z(0)Z(1)Z(2)Z(3) """ try: parameter = None generator = None null_proj = None if isinstance(unitary, tq.quantumchemistry.qc_base.FermionicGateImpl): parameter = unitary.extract_variables() generator = unitary.generator null_proj = unitary.p0 else: #getting parameter if unitary.is_parametrized(): parameter = unitary.extract_variables() else: parameter = [None] try: generator = unitary.make_generator(include_controls=True) except: generator = unitary.generator() """if len(parameter) == 0: parameter = [tq.objective.objective.assign_variable(unitary.parameter)]""" return parameter[0], generator, null_proj except Exception as e: print("An Exception happened, details :",e) pass def fold_unitary_into_hamiltonian(unitary, Hamiltonian): """ This function return a list of the resulting Hamiltonian terms after folding the paulistring correspondig to the unitary into the Hamiltonian param: unitary (tq.QGateImpl()) -> the unitary to be folded into the Hamiltonian param: Hamiltonian (ParamQubitHamiltonian()) -> the Hamiltonian of the system e.g.: input: unitary -> a FermionicGateImpl object as the one printed below FermionicExcitation(target=(0, 1, 2, 3), control=(), parameter=Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = []) Hamiltonian -> -0.06214952615456104 [] + -0.044941923860490916 [X0 X1 Y2 Y3] + 0.044941923860490916 [X0 Y1 Y2 X3] + 0.044941923860490916 [Y0 X1 X2 Y3] + -0.044941923860490916 [Y0 Y1 X2 X3] + 0.17547360045040505 [Z0] + 0.16992958569230643 [Z0 Z1] + 0.12212314332112947 [Z0 Z2] + 0.1670650671816204 [Z0 Z3] + 0.17547360045040508 [Z1] + 0.1670650671816204 [Z1 Z2] + 0.12212314332112947 [Z1 Z3] + -0.23578915712819945 [Z2] + 0.17561918557144712 [Z2 Z3] + -0.23578915712819945 [Z3] returns: folded_hamiltonian (ParamQubitHamiltonian()) -> Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [X0 X1 X2 X3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [X0 X1 Y2 Y3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [X0 Y1 X2 Y3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [X0 Y1 Y2 X3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Y0 X1 X2 Y3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Y0 X1 Y2 X3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Y0 Y1 X2 X3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Y0 Y1 Y2 Y3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z1] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z1 Z2] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z1 Z2 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z1 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z2] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z2 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z1] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z1 Z2] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z1 Z2 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z1 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z2] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z2 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z3] """ folded_hamiltonian = ParamQubitHamiltonian() if isinstance(unitary, tq.circuit._gates_impl.DifferentiableGateImpl) and not isinstance(unitary, tq.circuit._gates_impl.PhaseGateImpl): variable, generator, null_proj = get_generator_for_gates(unitary) # print(generator) # print(null_proj) #converting into ParamQubitHamiltonian() c_generator = convert_tq_QH_to_PQH(generator) """c_null_proj = convert_tq_QH_to_PQH(null_proj) print(variable) prod1 = (null_proj*ham*generator - generator*ham*null_proj) print(prod1) #print((Hamiltonian*c_generator)) prod2 = convert_PQH_to_tq_QH(c_null_proj*Hamiltonian*c_generator - c_generator*Hamiltonian*c_null_proj)({var:0.1 for var in variable.extract_variables()}) print(prod2) assert prod1 ==prod2 raise Exception("testing")""" #print("starting", flush=True) #handling the parameterize gates if variable is not None: #print("folding generator") # adding the term: cos^2(\theta)*H temp_ham = ParamQubitHamiltonian().identity() temp_ham *= Hamiltonian temp_ham *= (variable.apply(tq.numpy.cos)**2) #print(convert_PQH_to_tq_QH(temp_ham)({var:1. for var in variable.extract_variables()})) folded_hamiltonian += temp_ham #print("step1 done", flush=True) # adding the term: sin^2(\theta)*G*H*G temp_ham = ParamQubitHamiltonian().identity() temp_ham *= c_generator temp_ham *= Hamiltonian temp_ham *= c_generator temp_ham *= (variable.apply(tq.numpy.sin)**2) #print(convert_PQH_to_tq_QH(temp_ham)({var:1. for var in variable.extract_variables()})) folded_hamiltonian += temp_ham #print("step2 done", flush=True) # adding the term: i*cos^2(\theta)8sin^2(\theta)*(G*H -H*G) temp_ham1 = ParamQubitHamiltonian().identity() temp_ham1 *= c_generator temp_ham1 *= Hamiltonian temp_ham2 = ParamQubitHamiltonian().identity() temp_ham2 *= Hamiltonian temp_ham2 *= c_generator temp_ham = temp_ham1 - temp_ham2 temp_ham *= 1.0j temp_ham *= variable.apply(tq.numpy.sin) * variable.apply(tq.numpy.cos) #print(convert_PQH_to_tq_QH(temp_ham)({var:1. for var in variable.extract_variables()})) folded_hamiltonian += temp_ham #print("step3 done", flush=True) #handling the non-paramterized gates else: raise Exception("This function is not implemented yet") # adding the term: G*H*G folded_hamiltonian += c_generator*Hamiltonian*c_generator #print("Halfway there", flush=True) #handle the FermionicGateImpl gates if null_proj is not None: print("folding null projector") c_null_proj = convert_tq_QH_to_PQH(null_proj) #print("step4 done", flush=True) # adding the term: (1-cos(\theta))^2*P0*H*P0 temp_ham = ParamQubitHamiltonian().identity() temp_ham *= c_null_proj temp_ham *= Hamiltonian temp_ham *= c_null_proj temp_ham *= ((1-variable.apply(tq.numpy.cos))**2) folded_hamiltonian += temp_ham #print("step5 done", flush=True) # adding the term: 2*cos(\theta)*(1-cos(\theta))*(P0*H +H*P0) temp_ham1 = ParamQubitHamiltonian().identity() temp_ham1 *= c_null_proj temp_ham1 *= Hamiltonian temp_ham2 = ParamQubitHamiltonian().identity() temp_ham2 *= Hamiltonian temp_ham2 *= c_null_proj temp_ham = temp_ham1 + temp_ham2 temp_ham *= (variable.apply(tq.numpy.cos)*(1-variable.apply(tq.numpy.cos))) folded_hamiltonian += temp_ham #print("step6 done", flush=True) # adding the term: i*sin(\theta)*(1-cos(\theta))*(G*H*P0 - P0*H*G) temp_ham1 = ParamQubitHamiltonian().identity() temp_ham1 *= c_generator temp_ham1 *= Hamiltonian temp_ham1 *= c_null_proj temp_ham2 = ParamQubitHamiltonian().identity() temp_ham2 *= c_null_proj temp_ham2 *= Hamiltonian temp_ham2 *= c_generator temp_ham = temp_ham1 - temp_ham2 temp_ham *= 1.0j temp_ham *= (variable.apply(tq.numpy.sin)*(1-variable.apply(tq.numpy.cos))) folded_hamiltonian += temp_ham #print("step7 done", flush=True) elif isinstance(unitary, tq.circuit._gates_impl.PhaseGateImpl): if np.isclose(unitary.parameter, np.pi/2.0): return Hamiltonian._clifford_simplify_s(unitary.qubits[0]) elif np.isclose(unitary.parameter, -1.*np.pi/2.0): return Hamiltonian._clifford_simplify_s_dag(unitary.qubits[0]) else: raise Exception("Only DifferentiableGateImpl, PhaseGateImpl(S), Pauligate(X,Y,Z), Controlled(X,Y,Z) and Hadamrd(H) implemented yet") elif isinstance(unitary, tq.circuit._gates_impl.QGateImpl): if unitary.is_controlled(): if unitary.name == "X": return Hamiltonian._clifford_simplify_control_g("X", unitary.control[0], unitary.target[0]) elif unitary.name == "Y": return Hamiltonian._clifford_simplify_control_g("Y", unitary.control[0], unitary.target[0]) elif unitary.name == "Z": return Hamiltonian._clifford_simplify_control_g("Z", unitary.control[0], unitary.target[0]) else: raise Exception("Only DifferentiableGateImpl, PhaseGateImpl(S), Pauligate(X,Y,Z), Controlled(X,Y,Z) and Hadamrd(H) implemented yet") else: if unitary.name == "X": gate = convert_tq_QH_to_PQH(tq.paulis.X(unitary.qubits[0])) return gate*Hamiltonian*gate elif unitary.name == "Y": gate = convert_tq_QH_to_PQH(tq.paulis.Y(unitary.qubits[0])) return gate*Hamiltonian*gate elif unitary.name == "Z": gate = convert_tq_QH_to_PQH(tq.paulis.Z(unitary.qubits[0])) return gate*Hamiltonian*gate elif unitary.name == "H": return Hamiltonian._clifford_simplify_h(unitary.qubits[0]) else: raise Exception("Only DifferentiableGateImpl, PhaseGateImpl(S), Pauligate(X,Y,Z), Controlled(X,Y,Z) and Hadamrd(H) implemented yet") else: raise Exception("Only DifferentiableGateImpl, PhaseGateImpl(S), Pauligate(X,Y,Z), Controlled(X,Y,Z) and Hadamrd(H) implemented yet") return folded_hamiltonian def convert_tq_QH_to_PQH(Hamiltonian): """ This function takes the tequila QubitHamiltonian object and converts into a ParamQubitHamiltonian object. param: Hamiltonian (tq.QubitHamiltonian()) -> the Hamiltonian to be converted e.g: input: Hamiltonian -> -0.0621+0.1755Z(0)+0.1755Z(1)-0.2358Z(2)-0.2358Z(3)+0.1699Z(0)Z(1) +0.0449Y(0)X(1)X(2)Y(3)-0.0449Y(0)Y(1)X(2)X(3)-0.0449X(0)X(1)Y(2)Y(3) +0.0449X(0)Y(1)Y(2)X(3)+0.1221Z(0)Z(2)+0.1671Z(0)Z(3)+0.1671Z(1)Z(2) +0.1221Z(1)Z(3)+0.1756Z(2)Z(3) returns: param_hamiltonian (ParamQubitHamiltonian()) -> -0.06214952615456104 [] + -0.044941923860490916 [X0 X1 Y2 Y3] + 0.044941923860490916 [X0 Y1 Y2 X3] + 0.044941923860490916 [Y0 X1 X2 Y3] + -0.044941923860490916 [Y0 Y1 X2 X3] + 0.17547360045040505 [Z0] + 0.16992958569230643 [Z0 Z1] + 0.12212314332112947 [Z0 Z2] + 0.1670650671816204 [Z0 Z3] + 0.17547360045040508 [Z1] + 0.1670650671816204 [Z1 Z2] + 0.12212314332112947 [Z1 Z3] + -0.23578915712819945 [Z2] + 0.17561918557144712 [Z2 Z3] + -0.23578915712819945 [Z3] """ param_hamiltonian = ParamQubitHamiltonian() Hamiltonian = Hamiltonian.to_openfermion() for term in Hamiltonian.terms: param_hamiltonian += ParamQubitHamiltonian(term = term, coefficient = Hamiltonian.terms[term]) return param_hamiltonian class convert_PQH_to_tq_QH: def __init__(self, Hamiltonian): self.param_hamiltonian = Hamiltonian def __call__(self,variables=None): """ This function takes the ParamQubitHamiltonian object and converts into a tequila QubitHamiltonian object. param: param_hamiltonian (ParamQubitHamiltonian()) -> the Hamiltonian to be converted param: variables (dict) -> a dictionary with the values of the variables in the Hamiltonian coefficient e.g: input: param_hamiltonian -> a [Y0 X2 Z3] + b [Z0 X2 Z3] variables -> {"a":1,"b":2} returns: Hamiltonian (tq.QubitHamiltonian()) -> +1.0000Y(0)X(2)Z(3)+2.0000Z(0)X(2)Z(3) """ Hamiltonian = tq.QubitHamiltonian() for term in self.param_hamiltonian.terms: val = self.param_hamiltonian.terms[term]# + self.param_hamiltonian.imag_terms[term]*1.0j if isinstance(val, tq.Variable) or isinstance(val, tq.objective.objective.Objective): try: for key in variables.keys(): variables[key] = variables[key] #print(variables) val = val(variables) #print(val) except Exception as e: print(e) raise Exception("You forgot to pass the dictionary with the values of the variables") Hamiltonian += tq.QubitHamiltonian(QubitOperator(term=term, coefficient=val)) return Hamiltonian def _construct_derivatives(self, variables=None): """ """ derivatives = {} variable_names = [] for term in self.param_hamiltonian.terms: val = self.param_hamiltonian.terms[term]# + self.param_hamiltonian.imag_terms[term]*1.0j #print(val) if isinstance(val, tq.Variable) or isinstance(val, tq.objective.objective.Objective): variable = val.extract_variables() for var in list(variable): from grad_hacked import grad derivative = ParamQubitHamiltonian(term = term, coefficient = grad(val, var)) if var not in variable_names: variable_names.append(var) if var not in list(derivatives.keys()): derivatives[var] = derivative else: derivatives[var] += derivative return variable_names, derivatives def get_geometry(name, b_l): """ This is utility fucntion that generates tehe geometry string of a Molecule param: name (str) -> name of the molecule param: b_l (float) -> the bond length of the molecule e.g.: input: name -> "H2" b_l -> 0.714 returns: geo_str (str) -> "H 0.0 0.0 0.0\nH 0.0 0.0 0.714" """ geo_str = None if name == "LiH": geo_str = "H 0.0 0.0 0.0\nLi 0.0 0.0 {0}".format(b_l) elif name == "H2": geo_str = "H 0.0 0.0 0.0\nH 0.0 0.0 {0}".format(b_l) elif name == "BeH2": geo_str = "H 0.0 0.0 {0}\nH 0.0 0.0 {1}\nBe 0.0 0.0 0.0".format(b_l,-1*b_l) elif name == "N2": geo_str = "N 0.0 0.0 0.0\nN 0.0 0.0 {0}".format(b_l) elif name == "H4": geo_str = "H 0.0 0.0 0.0\nH 0.0 0.0 {0}\nH 0.0 0.0 {1}\nH 0.0 0.0 {2}".format(b_l,-1*b_l,2*b_l) return geo_str
27,934
51.807183
162
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_2.7/hacked_openfermion_symbolic_operator.py
import abc import copy import itertools import re import warnings import sympy import tequila as tq from tequila.objective.objective import Objective, Variable from openfermion.config import EQ_TOLERANCE COEFFICIENT_TYPES = (int, float, complex, sympy.Expr, Variable, Objective) class SymbolicOperator(metaclass=abc.ABCMeta): """Base class for FermionOperator and QubitOperator. A SymbolicOperator stores an object which represents a weighted sum of terms; each term is a product of individual factors of the form (`index`, `action`), where `index` is a nonnegative integer and the possible values for `action` are determined by the subclass. For instance, for the subclass FermionOperator, `action` can be 1 or 0, indicating raising or lowering, and for QubitOperator, `action` is from the set {'X', 'Y', 'Z'}. The coefficients of the terms are stored in a dictionary whose keys are the terms. SymbolicOperators of the same type can be added or multiplied together. Note: Adding SymbolicOperators is faster using += (as this is done by in-place addition). Specifying the coefficient during initialization is faster than multiplying a SymbolicOperator with a scalar. Attributes: actions (tuple): A tuple of objects representing the possible actions. e.g. for FermionOperator, this is (1, 0). action_strings (tuple): A tuple of string representations of actions. These should be in one-to-one correspondence with actions and listed in the same order. e.g. for FermionOperator, this is ('^', ''). action_before_index (bool): A boolean indicating whether in string representations, the action should come before the index. different_indices_commute (bool): A boolean indicating whether factors acting on different indices commute. terms (dict): **key** (tuple of tuples): A dictionary storing the coefficients of the terms in the operator. The keys are the terms. A term is a product of individual factors; each factor is represented by a tuple of the form (`index`, `action`), and these tuples are collected into a larger tuple which represents the term as the product of its factors. """ @staticmethod def _issmall(val, tol=EQ_TOLERANCE): '''Checks whether a value is near-zero Parses the allowed coefficients above for near-zero tests. Args: val (COEFFICIENT_TYPES) -- the value to be tested tol (float) -- tolerance for inequality ''' if isinstance(val, sympy.Expr): if sympy.simplify(abs(val) < tol) == True: return True return False if isinstance(val, tq.Variable) or isinstance(val, tq.objective.objective.Objective): return False if abs(val) < tol: return True return False @abc.abstractproperty def actions(self): """The allowed actions. Returns a tuple of objects representing the possible actions. """ pass @abc.abstractproperty def action_strings(self): """The string representations of the allowed actions. Returns a tuple containing string representations of the possible actions, in the same order as the `actions` property. """ pass @abc.abstractproperty def action_before_index(self): """Whether action comes before index in string representations. Example: For QubitOperator, the actions are ('X', 'Y', 'Z') and the string representations look something like 'X0 Z2 Y3'. So the action comes before the index, and this function should return True. For FermionOperator, the string representations look like '0^ 1 2^ 3'. The action comes after the index, so this function should return False. """ pass @abc.abstractproperty def different_indices_commute(self): """Whether factors acting on different indices commute.""" pass __hash__ = None def __init__(self, term=None, coefficient=1.): if not isinstance(coefficient, COEFFICIENT_TYPES): raise ValueError('Coefficient must be a numeric type.') # Initialize the terms dictionary self.terms = {} # Detect if the input is the string representation of a sum of terms; # if so, initialization needs to be handled differently if isinstance(term, str) and '[' in term: self._long_string_init(term, coefficient) return # Zero operator: leave the terms dictionary empty if term is None: return # Parse the term # Sequence input if isinstance(term, (list, tuple)): term = self._parse_sequence(term) # String input elif isinstance(term, str): term = self._parse_string(term) # Invalid input type else: raise ValueError('term specified incorrectly.') # Simplify the term coefficient, term = self._simplify(term, coefficient=coefficient) # Add the term to the dictionary self.terms[term] = coefficient def _long_string_init(self, long_string, coefficient): r""" Initialization from a long string representation. e.g. For FermionOperator: '1.5 [2^ 3] + 1.4 [3^ 0]' """ pattern = r'(.*?)\[(.*?)\]' # regex for a term for match in re.findall(pattern, long_string, flags=re.DOTALL): # Determine the coefficient for this term coef_string = re.sub(r"\s+", "", match[0]) if coef_string and coef_string[0] == '+': coef_string = coef_string[1:].strip() if coef_string == '': coef = 1.0 elif coef_string == '-': coef = -1.0 else: try: if 'j' in coef_string: if coef_string[0] == '-': coef = -complex(coef_string[1:]) else: coef = complex(coef_string) else: coef = float(coef_string) except ValueError: raise ValueError( 'Invalid coefficient {}.'.format(coef_string)) coef *= coefficient # Parse the term, simpify it and add to the dict term = self._parse_string(match[1]) coef, term = self._simplify(term, coefficient=coef) if term not in self.terms: self.terms[term] = coef else: self.terms[term] += coef def _validate_factor(self, factor): """Check that a factor of a term is valid.""" if len(factor) != 2: raise ValueError('Invalid factor {}.'.format(factor)) index, action = factor if action not in self.actions: raise ValueError('Invalid action in factor {}. ' 'Valid actions are: {}'.format( factor, self.actions)) if not isinstance(index, int) or index < 0: raise ValueError('Invalid index in factor {}. ' 'The index should be a non-negative ' 'integer.'.format(factor)) def _simplify(self, term, coefficient=1.0): """Simplifies a term.""" if self.different_indices_commute: term = sorted(term, key=lambda factor: factor[0]) return coefficient, tuple(term) def _parse_sequence(self, term): """Parse a term given as a sequence type (i.e., list, tuple, etc.). e.g. For QubitOperator: [('X', 2), ('Y', 0), ('Z', 3)] -> (('Y', 0), ('X', 2), ('Z', 3)) """ if not term: # Empty sequence return () elif isinstance(term[0], int): # Single factor self._validate_factor(term) return (tuple(term),) else: # Check that all factors in the term are valid for factor in term: self._validate_factor(factor) # Return a tuple return tuple(term) def _parse_string(self, term): """Parse a term given as a string. e.g. For FermionOperator: "2^ 3" -> ((2, 1), (3, 0)) """ factors = term.split() # Convert the string representations of the factors to tuples processed_term = [] for factor in factors: # Get the index and action string if self.action_before_index: # The index is at the end of the string; find where it starts. if not factor[-1].isdigit(): raise ValueError('Invalid factor {}.'.format(factor)) index_start = len(factor) - 1 while index_start > 0 and factor[index_start - 1].isdigit(): index_start -= 1 if factor[index_start - 1] == '-': raise ValueError('Invalid index in factor {}. ' 'The index should be a non-negative ' 'integer.'.format(factor)) index = int(factor[index_start:]) action_string = factor[:index_start] else: # The index is at the beginning of the string; find where # it ends if factor[0] == '-': raise ValueError('Invalid index in factor {}. ' 'The index should be a non-negative ' 'integer.'.format(factor)) if not factor[0].isdigit(): raise ValueError('Invalid factor {}.'.format(factor)) index_end = 1 while (index_end <= len(factor) - 1 and factor[index_end].isdigit()): index_end += 1 index = int(factor[:index_end]) action_string = factor[index_end:] # Convert the action string to an action if action_string in self.action_strings: action = self.actions[self.action_strings.index(action_string)] else: raise ValueError('Invalid action in factor {}. ' 'Valid actions are: {}'.format( factor, self.action_strings)) # Add the factor to the list as a tuple processed_term.append((index, action)) # Return a tuple return tuple(processed_term) @property def constant(self): """The value of the constant term.""" return self.terms.get((), 0.0) @constant.setter def constant(self, value): self.terms[()] = value @classmethod def zero(cls): """ Returns: additive_identity (SymbolicOperator): A symbolic operator o with the property that o+x = x+o = x for all operators x of the same class. """ return cls(term=None) @classmethod def identity(cls): """ Returns: multiplicative_identity (SymbolicOperator): A symbolic operator u with the property that u*x = x*u = x for all operators x of the same class. """ return cls(term=()) def __str__(self): """Return an easy-to-read string representation.""" if not self.terms: return '0' string_rep = '' for term, coeff in sorted(self.terms.items()): if self._issmall(coeff): continue tmp_string = '{} ['.format(coeff) for factor in term: index, action = factor action_string = self.action_strings[self.actions.index(action)] if self.action_before_index: tmp_string += '{}{} '.format(action_string, index) else: tmp_string += '{}{} '.format(index, action_string) string_rep += '{}] +\n'.format(tmp_string.strip()) return string_rep[:-3] def __repr__(self): return str(self) def __imul__(self, multiplier): """In-place multiply (*=) with scalar or operator of the same type. Default implementation is to multiply coefficients and concatenate terms. Args: multiplier(complex float, or SymbolicOperator): multiplier Returns: product (SymbolicOperator): Mutated self. """ # Handle scalars. if isinstance(multiplier, COEFFICIENT_TYPES): for term in self.terms: self.terms[term] *= multiplier return self # Handle operator of the same type elif isinstance(multiplier, self.__class__): result_terms = dict() for left_term in self.terms: for right_term in multiplier.terms: left_coefficient = self.terms[left_term] right_coefficient = multiplier.terms[right_term] new_coefficient = left_coefficient * right_coefficient new_term = left_term + right_term new_coefficient, new_term = self._simplify( new_term, coefficient=new_coefficient) # Update result dict. if new_term in result_terms: result_terms[new_term] += new_coefficient else: result_terms[new_term] = new_coefficient self.terms = result_terms return self # Invalid multiplier type else: raise TypeError('Cannot multiply {} with {}'.format( self.__class__.__name__, multiplier.__class__.__name__)) def __mul__(self, multiplier): """Return self * multiplier for a scalar, or a SymbolicOperator. Args: multiplier: A scalar, or a SymbolicOperator. Returns: product (SymbolicOperator) Raises: TypeError: Invalid type cannot be multiply with SymbolicOperator. """ if isinstance(multiplier, COEFFICIENT_TYPES + (type(self),)): product = copy.deepcopy(self) product *= multiplier return product else: raise TypeError('Object of invalid type cannot multiply with ' + type(self) + '.') def __iadd__(self, addend): """In-place method for += addition of SymbolicOperator. Args: addend (SymbolicOperator, or scalar): The operator to add. If scalar, adds to the constant term Returns: sum (SymbolicOperator): Mutated self. Raises: TypeError: Cannot add invalid type. """ if isinstance(addend, type(self)): for term in addend.terms: self.terms[term] = (self.terms.get(term, 0.0) + addend.terms[term]) if self._issmall(self.terms[term]): del self.terms[term] elif isinstance(addend, COEFFICIENT_TYPES): self.constant += addend else: raise TypeError('Cannot add invalid type to {}.'.format(type(self))) return self def __add__(self, addend): """ Args: addend (SymbolicOperator): The operator to add. Returns: sum (SymbolicOperator) """ summand = copy.deepcopy(self) summand += addend return summand def __radd__(self, addend): """ Args: addend (SymbolicOperator): The operator to add. Returns: sum (SymbolicOperator) """ return self + addend def __isub__(self, subtrahend): """In-place method for -= subtraction of SymbolicOperator. Args: subtrahend (A SymbolicOperator, or scalar): The operator to subtract if scalar, subtracts from the constant term. Returns: difference (SymbolicOperator): Mutated self. Raises: TypeError: Cannot subtract invalid type. """ if isinstance(subtrahend, type(self)): for term in subtrahend.terms: self.terms[term] = (self.terms.get(term, 0.0) - subtrahend.terms[term]) if self._issmall(self.terms[term]): del self.terms[term] elif isinstance(subtrahend, COEFFICIENT_TYPES): self.constant -= subtrahend else: raise TypeError('Cannot subtract invalid type from {}.'.format( type(self))) return self def __sub__(self, subtrahend): """ Args: subtrahend (SymbolicOperator): The operator to subtract. Returns: difference (SymbolicOperator) """ minuend = copy.deepcopy(self) minuend -= subtrahend return minuend def __rsub__(self, subtrahend): """ Args: subtrahend (SymbolicOperator): The operator to subtract. Returns: difference (SymbolicOperator) """ return -1 * self + subtrahend def __rmul__(self, multiplier): """ Return multiplier * self for a scalar. We only define __rmul__ for scalars because the left multiply exist for SymbolicOperator and left multiply is also queried as the default behavior. Args: multiplier: A scalar to multiply by. Returns: product: A new instance of SymbolicOperator. Raises: TypeError: Object of invalid type cannot multiply SymbolicOperator. """ if not isinstance(multiplier, COEFFICIENT_TYPES): raise TypeError('Object of invalid type cannot multiply with ' + type(self) + '.') return self * multiplier def __truediv__(self, divisor): """ Return self / divisor for a scalar. Note: This is always floating point division. Args: divisor: A scalar to divide by. Returns: A new instance of SymbolicOperator. Raises: TypeError: Cannot divide local operator by non-scalar type. """ if not isinstance(divisor, COEFFICIENT_TYPES): raise TypeError('Cannot divide ' + type(self) + ' by non-scalar type.') return self * (1.0 / divisor) def __div__(self, divisor): """ For compatibility with Python 2. """ return self.__truediv__(divisor) def __itruediv__(self, divisor): if not isinstance(divisor, COEFFICIENT_TYPES): raise TypeError('Cannot divide ' + type(self) + ' by non-scalar type.') self *= (1.0 / divisor) return self def __idiv__(self, divisor): """ For compatibility with Python 2. """ return self.__itruediv__(divisor) def __neg__(self): """ Returns: negation (SymbolicOperator) """ return -1 * self def __pow__(self, exponent): """Exponentiate the SymbolicOperator. Args: exponent (int): The exponent with which to raise the operator. Returns: exponentiated (SymbolicOperator) Raises: ValueError: Can only raise SymbolicOperator to non-negative integer powers. """ # Handle invalid exponents. if not isinstance(exponent, int) or exponent < 0: raise ValueError( 'exponent must be a non-negative int, but was {} {}'.format( type(exponent), repr(exponent))) # Initialized identity. exponentiated = self.__class__(()) # Handle non-zero exponents. for _ in range(exponent): exponentiated *= self return exponentiated def __eq__(self, other): """Approximate numerical equality (not true equality).""" return self.isclose(other) def __ne__(self, other): return not (self == other) def __iter__(self): self._iter = iter(self.terms.items()) return self def __next__(self): term, coefficient = next(self._iter) return self.__class__(term=term, coefficient=coefficient) def isclose(self, other, tol=EQ_TOLERANCE): """Check if other (SymbolicOperator) is close to self. Comparison is done for each term individually. Return True if the difference between each term in self and other is less than EQ_TOLERANCE Args: other(SymbolicOperator): SymbolicOperator to compare against. """ if not isinstance(self, type(other)): return NotImplemented # terms which are in both: for term in set(self.terms).intersection(set(other.terms)): a = self.terms[term] b = other.terms[term] if not (isinstance(a, sympy.Expr) or isinstance(b, sympy.Expr)): tol *= max(1, abs(a), abs(b)) if self._issmall(a - b, tol) is False: return False # terms only in one (compare to 0.0 so only abs_tol) for term in set(self.terms).symmetric_difference(set(other.terms)): if term in self.terms: if self._issmall(self.terms[term], tol) is False: return False else: if self._issmall(other.terms[term], tol) is False: return False return True def compress(self, abs_tol=EQ_TOLERANCE): """ Eliminates all terms with coefficients close to zero and removes small imaginary and real parts. Args: abs_tol(float): Absolute tolerance, must be at least 0.0 """ new_terms = {} for term in self.terms: coeff = self.terms[term] if isinstance(coeff, sympy.Expr): if sympy.simplify(sympy.im(coeff) <= abs_tol) == True: coeff = sympy.re(coeff) if sympy.simplify(sympy.re(coeff) <= abs_tol) == True: coeff = 1j * sympy.im(coeff) if (sympy.simplify(abs(coeff) <= abs_tol) != True): new_terms[term] = coeff continue if isinstance(val, tq.Variable) or isinstance(val, tq.objective.objective.Objective): continue # Remove small imaginary and real parts if abs(coeff.imag) <= abs_tol: coeff = coeff.real if abs(coeff.real) <= abs_tol: coeff = 1.j * coeff.imag # Add the term if the coefficient is large enough if abs(coeff) > abs_tol: new_terms[term] = coeff self.terms = new_terms def induced_norm(self, order=1): r""" Compute the induced p-norm of the operator. If we represent an operator as :math: `\sum_{j} w_j H_j` where :math: `w_j` are scalar coefficients then this norm is :math: `\left(\sum_{j} \| w_j \|^p \right)^{\frac{1}{p}} where :math: `p` is the order of the induced norm Args: order(int): the order of the induced norm. """ norm = 0. for coefficient in self.terms.values(): norm += abs(coefficient)**order return norm**(1. / order) def many_body_order(self): """Compute the many-body order of a SymbolicOperator. The many-body order of a SymbolicOperator is the maximum length of a term with nonzero coefficient. Returns: int """ if not self.terms: # Zero operator return 0 else: return max( len(term) for term, coeff in self.terms.items() if (self._issmall(coeff) is False)) @classmethod def accumulate(cls, operators, start=None): """Sums over SymbolicOperators.""" total = copy.deepcopy(start or cls.zero()) for operator in operators: total += operator return total def get_operators(self): """Gets a list of operators with a single term. Returns: operators([self.__class__]): A generator of the operators in self. """ for term, coefficient in self.terms.items(): yield self.__class__(term, coefficient) def get_operator_groups(self, num_groups): """Gets a list of operators with a few terms. Args: num_groups(int): How many operators to get in the end. Returns: operators([self.__class__]): A list of operators summing up to self. """ if num_groups < 1: warnings.warn('Invalid num_groups {} < 1.'.format(num_groups), RuntimeWarning) num_groups = 1 operators = self.get_operators() num_groups = min(num_groups, len(self.terms)) for i in range(num_groups): yield self.accumulate( itertools.islice(operators, len(range(i, len(self.terms), num_groups))))
25,797
35.697013
97
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.2/main.py
import tequila as tq import numpy as np from tequila.objective.objective import Variable import openfermion from typing import Union from vqe_utils import convert_PQH_to_tq_QH, convert_tq_QH_to_PQH,\ fold_unitary_into_hamiltonian from energy_optimization import * from do_annealing import * import random # guess we could substitute that with numpy.random #TODO import argparse import pickle as pk import matplotlib.pyplot as plt # Main hyperparameters mu = 2.0 # lognormal dist mean sigma = 0.4 # lognormal dist std T_0 = 1.0 # T_0, initial starting temperature # max_epochs = 25 # num_epochs, max number of iterations max_epochs = 20 # num_epochs, max number of iterations min_epochs = 2 # num_epochs, max number of iterations5 # min_epochs = 20 # num_epochs, max number of iterations tol = 1e-6 # minimum change in energy required, otherwise terminate optimization actions_ratio = [.15, .6, .25] patience = 100 beta = 0.5 max_non_cliffords = 0 type_energy_eval='wfn' num_population = 24 num_offsprings = 20 num_processors = 8 #tuning, input as lists. # parser.add_argument('--alphas', type = float, nargs = '+', help='alpha, temperature decay', required=True) alphas = [0.9] # alpha, temperature decay' #Required be = False h2 = True n2 = False name_prefix = '../../data/' # Construct qubit-Hamiltonian #num_active = 3 #active_orbitals = list(range(num_active)) if be: R1 = rrrr R2 = 1.2 geometry = "be 0.0 0.0 0.0\nh 0.0 0.0 {R1}\nh 0.0 0.0 -{R2}" name = "/h/292/philipps/software/moldata/beh2/beh2_{R1:2.2f}_{R2:2.2f}_180" # adapt of you move data mol = tq.Molecule(name=name.format(R1=R1, R2=R2), geometry=geometry.format(R1=R1,R2=R2), n_pno=None) lqm = mol.local_qubit_map(hcb=False) H = mol.make_hamiltonian().map_qubits(lqm).simplify() #print("FCI ENERGY: ", mol.compute_energy(method="fci")) U_spa = mol.make_upccgsd_ansatz(name="SPA").map_qubits(lqm) U = U_spa elif n2: R1 = rrrr geometry = "N 0.0 0.0 0.0\nN 0.0 0.0 {R1}" # name = "/home/abhinav/matter_lab/moldata/n2/n2_{R1:2.2f}" # adapt of you move data name = "/h/292/philipps/software/moldata/n2/n2_{R1:2.2f}" # adapt of you move data mol = tq.Molecule(name=name.format(R1=R1), geometry=geometry.format(R1=R1), n_pno=None) lqm = mol.local_qubit_map(hcb=False) H = mol.make_hamiltonian().map_qubits(lqm).simplify() # print("FCI ENERGY: ", mol.compute_energy(method="fci")) print("Skip FCI calculation, take old data...") U_spa = mol.make_upccgsd_ansatz(name="SPA").map_qubits(lqm) U = U_spa elif h2: active_orbitals = list(range(3)) mol = tq.Molecule(geometry='H 0.0 0.0 0.0\n H 0.0 0.0 1.2', basis_set='6-31g', active_orbitals=active_orbitals, backend='psi4') H = mol.make_hamiltonian().simplify() print("FCI ENERGY: ", mol.compute_energy(method="fci")) U = mol.make_uccsd_ansatz(trotter_steps=1) # Alternatively, get qubit-Hamiltonian from openfermion/externally # with open("ham_6qubits.txt") as hamstring_file: """if be: with open("ham_beh2_3_3.txt") as hamstring_file: hamstring = hamstring_file.read() #print(hamstring) H = tq.QubitHamiltonian().from_string(string=hamstring, openfermion_format=True) elif h2: with open("ham_6qubits.txt") as hamstring_file: hamstring = hamstring_file.read() #print(hamstring) H = tq.QubitHamiltonian().from_string(string=hamstring, openfermion_format=True)""" n_qubits = len(H.qubits) ''' Option 'wfn': "Shortcut" via wavefunction-optimization using MPO-rep of Hamiltonian Option 'qc': Need to input a proper quantum circuit ''' # Clifford optimization in the context of reduced-size quantum circuits starting_E = 123.456 reference = True if reference: if type_energy_eval.lower() == 'wfn': starting_E, _ = minimize_energy(hamiltonian=H, n_qubits=n_qubits, type_energy_eval='wfn') print('starting energy wfn: {:.5f}'.format(starting_E), flush=True) elif type_energy_eval.lower() == 'qc': starting_E, _ = minimize_energy(hamiltonian=H, n_qubits=n_qubits, type_energy_eval='qc', cluster_circuit=U) print('starting energy spa: {:.5f}'.format(starting_E)) else: raise Exception("type_energy_eval must be either 'wfn' or 'qc', but is", type_energy_eval) starting_E, _ = minimize_energy(hamiltonian=H, n_qubits=n_qubits, type_energy_eval='wfn') """for alpha in alphas: print('Starting optimization, alpha = {:3f}'.format(alpha)) # print('Energy to beat', minimize_energy(H, n_qubits, 'wfn')[0]) simulated_annealing(hamiltonian=H, num_population=num_population, num_offsprings=num_offsprings, num_processors=num_processors, tol=tol, max_epochs=max_epochs, min_epochs=min_epochs, T_0=T_0, alpha=alpha, actions_ratio=actions_ratio, max_non_cliffords=max_non_cliffords, verbose=True, patience=patience, beta=beta, type_energy_eval=type_energy_eval.lower(), cluster_circuit=U, starting_energy=starting_E)""" alter_cliffords = True if alter_cliffords: print("starting to replace cliffords with non-clifford gates to see if that improves the current fitness") replace_cliff_with_non_cliff(hamiltonian=H, num_population=num_population, num_offsprings=num_offsprings, num_processors=num_processors, tol=tol, max_epochs=max_epochs, min_epochs=min_epochs, T_0=T_0, alpha=alphas[0], actions_ratio=actions_ratio, max_non_cliffords=max_non_cliffords, verbose=True, patience=patience, beta=beta, type_energy_eval=type_energy_eval.lower(), cluster_circuit=U, starting_energy=starting_E) # accepted_E, tested_E, decisions, instructions_list, best_instructions, temp, best_E = simulated_annealing(hamiltonian=H, # population=4, # num_mutations=2, # num_processors=1, # tol=opt.tol, max_epochs=opt.max_epochs, # min_epochs=opt.min_epochs, T_0=opt.T_0, alpha=alpha, # mu=opt.mu, sigma=opt.sigma, verbose=True, prev_E = starting_E, patience = 10, beta = 0.5, # energy_eval='qc', # eval_circuit=U # print(best_E) # print(best_instructions) # print(len(accepted_E)) # plt.plot(accepted_E) # plt.show() # #pickling data # data = {'accepted_energies': accepted_E, 'tested_energies': tested_E, # 'decisions': decisions, 'instructions': instructions_list, # 'best_instructions': best_instructions, 'temperature': temp, # 'best_energy': best_E} # f_name = '{}{}_alpha_{:.2f}.pk'.format(opt.name_prefix, r, alpha) # pk.dump(data, open(f_name, 'wb')) # print('Finished optimization, data saved in {}'.format(f_name))
7,368
40.869318
129
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.2/my_mpo.py
import numpy as np import tensornetwork as tn from tensornetwork.backends.abstract_backend import AbstractBackend tn.set_default_backend("pytorch") #tn.set_default_backend("numpy") from typing import List, Union, Text, Optional, Any, Type Tensor = Any import tequila as tq import torch EPS = 1e-12 class SubOperator: """ This is just a helper class to store coefficient, operators and positions in an intermediate format """ def __init__(self, coefficient: float, operators: List, positions: List ): self._coefficient = coefficient self._operators = operators self._positions = positions @property def coefficient(self): return self._coefficient @property def operators(self): return self._operators @property def positions(self): return self._positions class MPOContainer: """ Class that handles the MPO. Is able to set values at certain positions, update containers (wannabe-equivalent to dynamic arrays) and compress the MPO """ def __init__(self, n_qubits: int, ): self.n_qubits = n_qubits self.container = [ np.zeros((1,1,2,2), dtype=np.complex) for q in range(self.n_qubits) ] def get_dim(self): """ Returns max dimension of container """ d = 1 for q in range(len(self.container)): d = max(d, self.container[q].shape[0]) return d def set_tensor(self, qubit: int, set_at: list, add_operator: Union[np.ndarray, float]): """ set_at: where to put data """ # Set a matrix if len(set_at) == 2: self.container[qubit][set_at[0],set_at[1],:,:] = add_operator[:,:] # Set specific values elif len(set_at) == 4: self.container[qubit][set_at[0],set_at[1],set_at[2],set_at[3]] =\ add_operator else: raise Exception("set_at needs to be either of length 2 or 4") def update_container(self, qubit: int, update_dir: list, add_operator: np.ndarray): """ This should mimick a dynamic array update_dir: e.g. [1,1,0,0] -> extend dimension along where there's a 1 the last two dimensions are always 2x2 only """ old_shape = self.container[qubit].shape # print(old_shape) if not len(update_dir) == 4: if len(update_dir) == 2: update_dir += [0, 0] else: raise Exception("update_dir needs to be either of length 2 or 4") if update_dir[2] or update_dir[3]: raise Exception("Last two dims must be zero.") new_shape = tuple(update_dir[i]+old_shape[i] for i in range(len(update_dir))) new_tensor = np.zeros(new_shape, dtype=np.complex) # Copy old values new_tensor[:old_shape[0],:old_shape[1],:,:] = self.container[qubit][:,:,:,:] # Add new values new_tensor[new_shape[0]-1,new_shape[1]-1,:,:] = add_operator[:,:] # Overwrite container self.container[qubit] = new_tensor def compress_mpo(self): """ Compression of MPO via SVD """ n_qubits = len(self.container) for q in range(n_qubits): my_shape = self.container[q].shape self.container[q] =\ self.container[q].reshape((my_shape[0], my_shape[1], -1)) # Go forwards for q in range(n_qubits-1): # Apply permutation [0 1 2] -> [0 2 1] my_tensor = np.swapaxes(self.container[q], 1, 2) my_tensor = my_tensor.reshape((-1, my_tensor.shape[2])) # full_matrices flag corresponds to 'econ' -> no zero-singular values u, s, vh = np.linalg.svd(my_tensor, full_matrices=False) # Count the non-zero singular values num_nonzeros = len(np.argwhere(s>EPS)) # Construct matrix from square root of singular values s = np.diag(np.sqrt(s[:num_nonzeros])) u = u[:,:num_nonzeros] vh = vh[:num_nonzeros,:] # Distribute weights to left- and right singular vectors (@ = np.matmul) u = u @ s vh = s @ vh # Apply permutation [0 1 2] -> [0 2 1] u = u.reshape((self.container[q].shape[0],\ self.container[q].shape[2], -1)) self.container[q] = np.swapaxes(u, 1, 2) self.container[q+1] = tn.ncon([vh, self.container[q+1]], [(-1, 1),(1, -2, -3)]) # Go backwards for q in range(n_qubits-1, 0, -1): my_tensor = self.container[q] my_tensor = my_tensor.reshape((self.container[q].shape[0], -1)) # full_matrices flag corresponds to 'econ' -> no zero-singular values u, s, vh = np.linalg.svd(my_tensor, full_matrices=False) # Count the non-zero singular values num_nonzeros = len(np.argwhere(s>EPS)) # Construct matrix from square root of singular values s = np.diag(np.sqrt(s[:num_nonzeros])) u = u[:,:num_nonzeros] vh = vh[:num_nonzeros,:] # Distribute weights to left- and right singular vectors u = u @ s vh = s @ vh self.container[q] = np.reshape(vh, (num_nonzeros, self.container[q].shape[1], self.container[q].shape[2])) self.container[q-1] = tn.ncon([self.container[q-1], u], [(-1, 1, -3),(1, -2)]) for q in range(n_qubits): my_shape = self.container[q].shape self.container[q] = self.container[q].reshape((my_shape[0],\ my_shape[1],2,2)) # TODO maybe make subclass of tn.FiniteMPO if it makes sense #class my_MPO(tn.FiniteMPO): class MyMPO: """ Class building up on tensornetwork FiniteMPO to handle MPO-Hamiltonians """ def __init__(self, hamiltonian: Union[tq.QubitHamiltonian, Text], # tensors: List[Tensor], backend: Optional[Union[AbstractBackend, Text]] = None, n_qubits: Optional[int] = None, name: Optional[Text] = None, maxdim: Optional[int] = 10000) -> None: # TODO: modifiy docstring """ Initialize a finite MPO object Args: tensors: The mpo tensors. backend: An optional backend. Defaults to the defaulf backend of TensorNetwork. name: An optional name for the MPO. """ self.hamiltonian = hamiltonian self.maxdim = maxdim if n_qubits: self._n_qubits = n_qubits else: self._n_qubits = self.get_n_qubits() @property def n_qubits(self): return self._n_qubits def make_mpo_from_hamiltonian(self): intermediate = self.openfermion_to_intermediate() # for i in range(len(intermediate)): # print(intermediate[i].coefficient) # print(intermediate[i].operators) # print(intermediate[i].positions) self.mpo = self.intermediate_to_mpo(intermediate) def openfermion_to_intermediate(self): # Here, have either a QubitHamiltonian or a file with a of-operator # Start with Qubithamiltonian def get_pauli_matrix(string): pauli_matrices = { 'I': np.array([[1, 0], [0, 1]], dtype=np.complex), 'Z': np.array([[1, 0], [0, -1]], dtype=np.complex), 'X': np.array([[0, 1], [1, 0]], dtype=np.complex), 'Y': np.array([[0, -1j], [1j, 0]], dtype=np.complex) } return pauli_matrices[string.upper()] intermediate = [] first = True # Store all paulistrings in intermediate format for paulistring in self.hamiltonian.paulistrings: coefficient = paulistring.coeff # print(coefficient) operators = [] positions = [] # Only first one should be identity -> distribute over all if first and not paulistring.items(): positions += [] operators += [] first = False elif not first and not paulistring.items(): raise Exception("Only first Pauli should be identity.") # Get operators and where they act for k,v in paulistring.items(): positions += [k] operators += [get_pauli_matrix(v)] tmp_op = SubOperator(coefficient=coefficient, operators=operators, positions=positions) intermediate += [tmp_op] # print("len intermediate = num Pauli strings", len(intermediate)) return intermediate def build_single_mpo(self, intermediate, j): # Set MPO Container n_qubits = self._n_qubits mpo = MPOContainer(n_qubits=n_qubits) # *********************************************************************** # Set first entries (of which we know that they are 2x2-matrices) # Typically, this is an identity my_coefficient = intermediate[j].coefficient my_positions = intermediate[j].positions my_operators = intermediate[j].operators for q in range(n_qubits): if not q in my_positions: mpo.set_tensor(qubit=q, set_at=[0,0], add_operator=np.complex(my_coefficient)**(1/n_qubits)* np.eye(2)) elif q in my_positions: my_pos_index = my_positions.index(q) mpo.set_tensor(qubit=q, set_at=[0,0], add_operator=np.complex(my_coefficient)**(1/n_qubits)* my_operators[my_pos_index]) # *********************************************************************** # All other entries # while (j smaller than number of intermediates left) and mpo.dim() <= self.maxdim # Re-write this based on positions keyword! j += 1 while j < len(intermediate) and mpo.get_dim() < self.maxdim: # """ my_coefficient = intermediate[j].coefficient my_positions = intermediate[j].positions my_operators = intermediate[j].operators for q in range(n_qubits): # It is guaranteed that every index appears only once in positions if q == 0: update_dir = [0,1] elif q == n_qubits-1: update_dir = [1,0] else: update_dir = [1,1] # If there's an operator on my position, add that if q in my_positions: my_pos_index = my_positions.index(q) mpo.update_container(qubit=q, update_dir=update_dir, add_operator= np.complex(my_coefficient)**(1/n_qubits)* my_operators[my_pos_index]) # Else add an identity else: mpo.update_container(qubit=q, update_dir=update_dir, add_operator= np.complex(my_coefficient)**(1/n_qubits)* np.eye(2)) if not j % 100: mpo.compress_mpo() #print("\t\tAt iteration ", j, " MPO has dimension ", mpo.get_dim()) j += 1 mpo.compress_mpo() #print("\tAt final iteration ", j-1, " MPO has dimension ", mpo.get_dim()) return mpo, j def intermediate_to_mpo(self, intermediate): n_qubits = self._n_qubits # TODO Change to multiple MPOs mpo_list = [] j_global = 0 num_mpos = 0 # Start with 0, then final one is correct while j_global < len(intermediate): current_mpo, j_global = self.build_single_mpo(intermediate, j_global) mpo_list += [current_mpo] num_mpos += 1 return mpo_list def construct_matrix(self): # TODO extend to lists of MPOs ''' Recover matrix, e.g. to compare with Hamiltonian that we get from tq ''' mpo = self.mpo # Contract over all bond indices # mpo.container has indices [bond, bond, physical, physical] n_qubits = self._n_qubits d = int(2**(n_qubits/2)) first = True H = None #H = np.zeros((d,d,d,d), dtype='complex') # Define network nodes # | | | | # -O--O--...--O--O- # | | | | for m in mpo: assert(n_qubits == len(m.container)) nodes = [tn.Node(m.container[q], name=str(q)) for q in range(n_qubits)] # Connect network (along double -- above) for q in range(n_qubits-1): nodes[q][1] ^ nodes[q+1][0] # Collect dangling edges (free indices) edges = [] # Left dangling edge edges += [nodes[0].get_edge(0)] # Right dangling edge edges += [nodes[-1].get_edge(1)] # Upper dangling edges for q in range(n_qubits): edges += [nodes[q].get_edge(2)] # Lower dangling edges for q in range(n_qubits): edges += [nodes[q].get_edge(3)] # Contract between all nodes along non-dangling edges res = tn.contractors.auto(nodes, output_edge_order=edges) # Reshape to get tensor of order 4 (get rid of left- and right open indices # and combine top&bottom into one) if isinstance(res.tensor, torch.Tensor): H_m = res.tensor.numpy() if not first: H += H_m else: H = H_m first = False return H.reshape((d,d,d,d))
14,354
36.480418
99
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.2/do_annealing.py
import tequila as tq import numpy as np import pickle from pathos.multiprocessing import ProcessingPool as Pool from parallel_annealing import * #from dummy_par import * from mutation_options import * from single_thread_annealing import * def find_best_instructions(instructions_dict): """ This function finds the instruction with the best fitness args: instructions_dict: A dictionary with the "Instructions" objects the corresponding fitness values as values """ best_instructions = None best_fitness = 10000000 for key in instructions_dict: if instructions_dict[key][1] <= best_fitness: best_instructions = instructions_dict[key][0] best_fitness = instructions_dict[key][1] return best_instructions, best_fitness def simulated_annealing(num_population, num_offsprings, actions_ratio, hamiltonian, max_epochs=100, min_epochs=1, tol=1e-6, type_energy_eval="wfn", cluster_circuit=None, patience = 20, num_processors=4, T_0=1.0, alpha=0.9, max_non_cliffords=0, verbose=False, beta=0.5, starting_energy=None): """ this function tries to find the clifford circuit that best lowers the energy of the hamiltonian using simulated annealing. params: - num_population = number of members in a generation - num_offsprings = number of mutations carried on every member - num_processors = number of processors to use for parallelization - T_0 = initial temperature - alpha = temperature decay - beta = parameter to adjust temperature on resetting after running out of patience - max_epochs = max iterations for optimizing - min_epochs = min iterations for optimizing - tol = minimum change in energy required, otherwise terminate optimization - verbose = display energies/decisions at iterations of not - hamiltonian = original hamiltonian - actions_ratio = The ratio of the different actions for mutations - type_energy_eval = keyword specifying the type of optimization method to use for energy minimization - cluster_circuit = the reference circuit to which clifford gates are added - patience = the number of epochs before resetting the optimization """ if verbose: print("Starting to Optimize Cluster circuit", flush=True) num_qubits = len(hamiltonian.qubits) if verbose: print("Initializing Generation", flush=True) # restart = False if previous_instructions is None\ # else True restart = False instructions_dict = {} instructions_list = [] current_fitness_list = [] fitness, wfn = None, None # pre-initialize with None for instruction_id in range(num_population): instructions = None if restart: try: instructions = Instructions(n_qubits=num_qubits, alpha=alpha, T_0=T_0, beta=beta, patience=patience, max_non_cliffords=max_non_cliffords, reference_energy=starting_energy) instructions.gates = pickle.load(open("instruct_gates.pickle", "rb")) instructions.positions = pickle.load(open("instruct_positions.pickle", "rb")) instructions.best_reference_wfn = pickle.load(open("best_reference_wfn.pickle", "rb")) print("Added a guess from previous runs", flush=True) fitness, wfn = evaluate_fitness(instructions=instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) except Exception as e: print(e) raise Exception("Did not find a guess from previous runs") # pass restart = False #print(instructions._str()) else: failed = True while failed: instructions = Instructions(n_qubits=num_qubits, alpha=alpha, T_0=T_0, beta=beta, patience=patience, max_non_cliffords=max_non_cliffords, reference_energy=starting_energy) instructions.prune() fitness, wfn = evaluate_fitness(instructions=instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) # if fitness <= starting_energy: failed = False instructions.set_reference_wfn(wfn) current_fitness_list.append(fitness) instructions_list.append(instructions) instructions_dict[instruction_id] = (instructions, fitness) if verbose: print("First Generation details: \n", flush=True) for key in instructions_dict: print("Initial Instructions number: ", key, flush=True) instructions_dict[key][0]._str() print("Initial fitness values: ", instructions_dict[key][1], flush=True) best_instructions, best_energy = find_best_instructions(instructions_dict) if verbose: print("Best member of the Generation: \n", flush=True) print("Instructions: ", flush=True) best_instructions._str() print("fitness value: ", best_energy, flush=True) pickle.dump(best_instructions.gates, open("instruct_gates.pickle", "wb")) pickle.dump(best_instructions.positions, open("instruct_positions.pickle", "wb")) pickle.dump(best_instructions.best_reference_wfn, open("best_reference_wfn.pickle", "wb")) epoch = 0 previous_best_energy = best_energy converged = False has_improved_before = False dts = [] #pool = multiprocessing.Pool(processes=num_processors) while (epoch < max_epochs): print("Epoch: ", epoch, flush=True) import time t0 = time.time() if num_processors == 1: st_evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, type_energy_eval, cluster_circuit) else: evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, num_processors, type_energy_eval, cluster_circuit) t1 = time.time() dts += [t1-t0] best_instructions, best_energy = find_best_instructions(instructions_dict) if verbose: print("Best member of the Generation: \n", flush=True) print("Instructions: ", flush=True) best_instructions._str() print("fitness value: ", best_energy, flush=True) # A bit confusing, but: # Want that current best energy has improved something previous, is better than # some starting energy and achieves some convergence criterion has_improved_before = True if np.abs(best_energy - previous_best_energy) < 0\ else False if np.abs(best_energy - previous_best_energy) < tol and has_improved_before: if starting_energy is not None: converged = True if best_energy < starting_energy else False else: converged = True else: converged = False if best_energy < previous_best_energy: previous_best_energy = best_energy epoch += 1 pickle.dump(best_instructions.gates, open("instruct_gates.pickle", "wb")) pickle.dump(best_instructions.positions, open("instruct_positions.pickle", "wb")) pickle.dump(best_instructions.best_reference_wfn, open("best_reference_wfn.pickle", "wb")) #pool.close() if converged: print("Converged after ", epoch, " iterations.", flush=True) print("Best energy:", best_energy, flush=True) print("\t with instructions", best_instructions.gates, best_instructions.positions, flush=True) print("\t optimal parameters", best_instructions.best_reference_wfn, flush=True) print("average time: ", np.average(dts), flush=True) print("overall time: ", np.sum(dts), flush=True) # best_instructions.replace_UCCXc_with_UCC(number=max_non_cliffords) pickle.dump(best_instructions.gates, open("instruct_gates.pickle", "wb")) pickle.dump(best_instructions.positions, open("instruct_positions.pickle", "wb")) pickle.dump(best_instructions.best_reference_wfn, open("best_reference_wfn.pickle", "wb")) def replace_cliff_with_non_cliff(num_population, num_offsprings, actions_ratio, hamiltonian, max_epochs=100, min_epochs=1, tol=1e-6, type_energy_eval="wfn", cluster_circuit=None, patience = 20, num_processors=4, T_0=1.0, alpha=0.9, max_non_cliffords=0, verbose=False, beta=0.5, starting_energy=None): """ this function tries to find the clifford circuit that best lowers the energy of the hamiltonian using simulated annealing. params: - num_population = number of members in a generation - num_offsprings = number of mutations carried on every member - num_processors = number of processors to use for parallelization - T_0 = initial temperature - alpha = temperature decay - beta = parameter to adjust temperature on resetting after running out of patience - max_epochs = max iterations for optimizing - min_epochs = min iterations for optimizing - tol = minimum change in energy required, otherwise terminate optimization - verbose = display energies/decisions at iterations of not - hamiltonian = original hamiltonian - actions_ratio = The ratio of the different actions for mutations - type_energy_eval = keyword specifying the type of optimization method to use for energy minimization - cluster_circuit = the reference circuit to which clifford gates are added - patience = the number of epochs before resetting the optimization """ if verbose: print("Starting to replace clifford gates Cluster circuit with non-clifford gates one at a time", flush=True) num_qubits = len(hamiltonian.qubits) #get the best clifford object instructions = Instructions(n_qubits=num_qubits, alpha=alpha, T_0=T_0, beta=beta, patience=patience, max_non_cliffords=max_non_cliffords, reference_energy=starting_energy) instructions.gates = pickle.load(open("instruct_gates.pickle", "rb")) instructions.positions = pickle.load(open("instruct_positions.pickle", "rb")) instructions.best_reference_wfn = pickle.load(open("best_reference_wfn.pickle", "rb")) fitness, wfn = evaluate_fitness(instructions=instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) if verbose: print("Initial energy after previous Clifford optimization is",\ fitness, flush=True) print("Starting with instructions", instructions.gates, instructions.positions, flush=True) instructions_dict = {} instructions_dict[0] = (instructions, fitness) for gate_id, (gate, position) in enumerate(zip(instructions.gates, instructions.positions)): print(gate) altered_instructions = copy.deepcopy(instructions) # skip if controlled rotation if gate[0]=='C': continue altered_instructions.replace_cg_w_ncg(gate_id) # altered_instructions.max_non_cliffords = 1 # TODO why is this set to 1?? altered_instructions.max_non_cliffords = max_non_cliffords #clifford_circuit, init_angles = build_circuit(instructions) #print(clifford_circuit, init_angles) #folded_hamiltonian = perform_folding(hamiltonian, clifford_circuit) #folded_hamiltonian2 = (convert_PQH_to_tq_QH(folded_hamiltonian))() #print(folded_hamiltonian) #clifford_circuit, init_angles = build_circuit(altered_instructions) #print(clifford_circuit, init_angles) #folded_hamiltonian = perform_folding(hamiltonian, clifford_circuit) #folded_hamiltonian1 = (convert_PQH_to_tq_QH(folded_hamiltonian))(init_angles) #print(folded_hamiltonian1 - folded_hamiltonian2) #print(folded_hamiltonian) #raise Exception("teste") counter = 0 success = False while not success: counter += 1 try: fitness, wfn = evaluate_fitness(instructions=altered_instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) success = True except Exception as e: print(e) if counter > 5: print("This replacement failed more than 5 times") success = True instructions_dict[gate_id+1] = (altered_instructions, fitness) #circuit = build_circuit(altered_instructions) #tq.draw(circuit,backend="cirq") best_instructions, best_energy = find_best_instructions(instructions_dict) print("best instrucitons after the non-clifford opimizaton") print("Best energy:", best_energy, flush=True) print("\t with instructions", best_instructions.gates, best_instructions.positions, flush=True)
13,155
46.154122
187
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.2/scipy_optimizer.py
import numpy, copy, scipy, typing, numbers from tequila import BitString, BitNumbering, BitStringLSB from tequila.utils.keymap import KeyMapRegisterToSubregister from tequila.circuit.compiler import change_basis from tequila.utils import to_float import tequila as tq from tequila.objective import Objective from tequila.optimizers.optimizer_scipy import OptimizerSciPy, SciPyResults from tequila.objective.objective import assign_variable, Variable, format_variable_dictionary, format_variable_list from tequila.circuit.noise import NoiseModel #from tequila.optimizers._containers import _EvalContainer, _GradContainer, _HessContainer, _QngContainer from vqe_utils import * class _EvalContainer: """ Overwrite the call function Container Class to access scipy and keep the optimization history. This class is used by the SciPy optimizer and should not be used elsewhere. Attributes --------- objective: the objective to evaluate. param_keys: the dictionary mapping parameter keys to positions in a numpy array. samples: the number of samples to evaluate objective with. save_history: whether or not to save, in a history, information about each time __call__ occurs. print_level dictates the verbosity of printing during call. N: the length of param_keys. history: if save_history, a list of energies received from every __call__ history_angles: if save_history, a list of angles sent to __call__. """ def __init__(self, Hamiltonian, unitary, param_keys, Ham_derivatives= None, Eval=None, passive_angles=None, samples=1024, save_history=True, print_level: int = 3): self.Hamiltonian = Hamiltonian self.unitary = unitary self.samples = samples self.param_keys = param_keys self.N = len(param_keys) self.save_history = save_history self.print_level = print_level self.passive_angles = passive_angles self.Eval = Eval self.infostring = None self.Ham_derivatives = Ham_derivatives if save_history: self.history = [] self.history_angles = [] def __call__(self, p, *args, **kwargs): """ call a wrapped objective. Parameters ---------- p: numpy array: Parameters with which to call the objective. args kwargs Returns ------- numpy.array: value of self.objective with p translated into variables, as a numpy array. """ angles = {}#dict((self.param_keys[i], p[i]) for i in range(self.N)) for i in range(self.N): if self.param_keys[i] in self.unitary.extract_variables(): angles[self.param_keys[i]] = p[i] else: angles[self.param_keys[i]] = complex(p[i]) if self.passive_angles is not None: angles = {**angles, **self.passive_angles} vars = format_variable_dictionary(angles) Hamiltonian = self.Hamiltonian(vars) #print(Hamiltonian) #print(self.unitary) #print(vars) Expval = tq.ExpectationValue(H=Hamiltonian, U=self.unitary) #print(Expval) E = tq.simulate(Expval, vars, backend='qulacs', samples=self.samples) self.infostring = "{:15} : {} expectationvalues\n".format("Objective", Expval.count_expectationvalues()) if self.print_level > 2: print("E={:+2.8f}".format(E), " angles=", angles, " samples=", self.samples) elif self.print_level > 1: print("E={:+2.8f}".format(E)) if self.save_history: self.history.append(E) self.history_angles.append(angles) return complex(E) # jax types confuses optimizers class _GradContainer(_EvalContainer): """ Overwrite the call function Container Class to access scipy and keep the optimization history. This class is used by the SciPy optimizer and should not be used elsewhere. see _EvalContainer for details. """ def __call__(self, p, *args, **kwargs): """ call the wrapped qng. Parameters ---------- p: numpy array: Parameters with which to call gradient args kwargs Returns ------- numpy.array: value of self.objective with p translated into variables, as a numpy array. """ Ham_derivatives = self.Ham_derivatives Hamiltonian = self.Hamiltonian unitary = self.unitary dE_vec = numpy.zeros(self.N) memory = dict() #variables = dict((self.param_keys[i], p[i]) for i in range(len(self.param_keys))) variables = {}#dict((self.param_keys[i], p[i]) for i in range(self.N)) for i in range(len(self.param_keys)): if self.param_keys[i] in self.unitary.extract_variables(): variables[self.param_keys[i]] = p[i] else: variables[self.param_keys[i]] = complex(p[i]) if self.passive_angles is not None: variables = {**variables, **self.passive_angles} vars = format_variable_dictionary(variables) expvals = 0 for i in range(self.N): derivative = 0.0 if self.param_keys[i] in list(unitary.extract_variables()): Ham = Hamiltonian(vars) Expval = tq.ExpectationValue(H=Ham, U=unitary) temp_derivative = tq.compile(objective = tq.grad(objective = Expval, variable = self.param_keys[i]),backend='qulacs') expvals += temp_derivative.count_expectationvalues() derivative += temp_derivative if self.param_keys[i] in list(Ham_derivatives.keys()): #print(self.param_keys[i]) Ham = Ham_derivatives[self.param_keys[i]] Ham = convert_PQH_to_tq_QH(Ham) H = Ham(vars) #print(H) #raise Exception("testing") Expval = tq.ExpectationValue(H=H, U=unitary) expvals += Expval.count_expectationvalues() derivative += tq.simulate(Expval, vars, backend='qulacs', samples=self.samples) #print(derivative) #print(type(H)) if isinstance(derivative, float) or isinstance(derivative, numpy.complex64) : dE_vec[i] = derivative else: dE_vec[i] = derivative(variables=variables, samples=self.samples) memory[self.param_keys[i]] = dE_vec[i] self.infostring = "{:15} : {} expectationvalues\n".format("gradient", expvals) self.history.append(memory) return numpy.asarray(dE_vec, dtype=numpy.complex64) class optimize_scipy(OptimizerSciPy): """ overwrite the expectation and gradient container objects """ def initialize_variables(self, all_variables, initial_values, variables): """ Convenience function to format the variables of some objective recieved in calls to optimzers. Parameters ---------- objective: Objective: the objective being optimized. initial_values: dict or string: initial values for the variables of objective, as a dictionary. if string: can be `zero` or `random` if callable: custom function that initializes when keys are passed if None: random initialization between 0 and 2pi (not recommended) variables: list: the variables being optimized over. Returns ------- tuple: active_angles, a dict of those variables being optimized. passive_angles, a dict of those variables NOT being optimized. variables: formatted list of the variables being optimized. """ # bring into right format variables = format_variable_list(variables) initial_values = format_variable_dictionary(initial_values) all_variables = all_variables if variables is None: variables = all_variables if initial_values is None: initial_values = {k: numpy.random.uniform(0, 2 * numpy.pi) for k in all_variables} elif hasattr(initial_values, "lower"): if initial_values.lower() == "zero": initial_values = {k:0.0 for k in all_variables} elif initial_values.lower() == "random": initial_values = {k: numpy.random.uniform(0, 2 * numpy.pi) for k in all_variables} else: raise TequilaOptimizerException("unknown initialization instruction: {}".format(initial_values)) elif callable(initial_values): initial_values = {k: initial_values(k) for k in all_variables} elif isinstance(initial_values, numbers.Number): initial_values = {k: initial_values for k in all_variables} else: # autocomplete initial values, warn if you did detected = False for k in all_variables: if k not in initial_values: initial_values[k] = 0.0 detected = True if detected and not self.silent: warnings.warn("initial_variables given but not complete: Autocompleted with zeroes", TequilaWarning) active_angles = {} for v in variables: active_angles[v] = initial_values[v] passive_angles = {} for k, v in initial_values.items(): if k not in active_angles.keys(): passive_angles[k] = v return active_angles, passive_angles, variables def __call__(self, Hamiltonian, unitary, variables: typing.List[Variable] = None, initial_values: typing.Dict[Variable, numbers.Real] = None, gradient: typing.Dict[Variable, Objective] = None, hessian: typing.Dict[typing.Tuple[Variable, Variable], Objective] = None, reset_history: bool = True, *args, **kwargs) -> SciPyResults: """ Perform optimization using scipy optimizers. Parameters ---------- objective: Objective: the objective to optimize. variables: list, optional: the variables of objective to optimize. If None: optimize all. initial_values: dict, optional: a starting point from which to begin optimization. Will be generated if None. gradient: optional: Information or object used to calculate the gradient of objective. Defaults to None: get analytically. hessian: optional: Information or object used to calculate the hessian of objective. Defaults to None: get analytically. reset_history: bool: Default = True: whether or not to reset all history before optimizing. args kwargs Returns ------- ScipyReturnType: the results of optimization. """ H = convert_PQH_to_tq_QH(Hamiltonian) Ham_variables, Ham_derivatives = H._construct_derivatives() #print("hamvars",Ham_variables) all_variables = copy.deepcopy(Ham_variables) #print(all_variables) for var in unitary.extract_variables(): all_variables.append(var) #print(all_variables) infostring = "{:15} : {}\n".format("Method", self.method) #infostring += "{:15} : {} expectationvalues\n".format("Objective", objective.count_expectationvalues()) if self.save_history and reset_history: self.reset_history() active_angles, passive_angles, variables = self.initialize_variables(all_variables, initial_values, variables) #print(active_angles, passive_angles, variables) # Transform the initial value directory into (ordered) arrays param_keys, param_values = zip(*active_angles.items()) param_values = numpy.array(param_values) # process and initialize scipy bounds bounds = None if self.method_bounds is not None: bounds = {k: None for k in active_angles} for k, v in self.method_bounds.items(): if k in bounds: bounds[k] = v infostring += "{:15} : {}\n".format("bounds", self.method_bounds) names, bounds = zip(*bounds.items()) assert (names == param_keys) # make sure the bounds are not shuffled #print(param_keys, param_values) # do the compilation here to avoid costly recompilation during the optimization #compiled_objective = self.compile_objective(objective=objective, *args, **kwargs) E = _EvalContainer(Hamiltonian = H, unitary = unitary, Eval=None, param_keys=param_keys, samples=self.samples, passive_angles=passive_angles, save_history=self.save_history, print_level=self.print_level) E.print_level = 0 (E(param_values)) E.print_level = self.print_level infostring += E.infostring if gradient is not None: infostring += "{:15} : {}\n".format("grad instr", gradient) if hessian is not None: infostring += "{:15} : {}\n".format("hess_instr", hessian) compile_gradient = self.method in (self.gradient_based_methods + self.hessian_based_methods) compile_hessian = self.method in self.hessian_based_methods dE = None ddE = None # detect if numerical gradients shall be used # switch off compiling if so if isinstance(gradient, str): if gradient.lower() == 'qng': compile_gradient = False if compile_hessian: raise TequilaException('Sorry, QNG and hessian not yet tested together.') combos = get_qng_combos(objective, initial_values=initial_values, backend=self.backend, samples=self.samples, noise=self.noise) dE = _QngContainer(combos=combos, param_keys=param_keys, passive_angles=passive_angles) infostring += "{:15} : QNG {}\n".format("gradient", dE) else: dE = gradient compile_gradient = False if compile_hessian: compile_hessian = False if hessian is None: hessian = gradient infostring += "{:15} : scipy numerical {}\n".format("gradient", dE) infostring += "{:15} : scipy numerical {}\n".format("hessian", ddE) if isinstance(gradient,dict): if gradient['method'] == 'qng': func = gradient['function'] compile_gradient = False if compile_hessian: raise TequilaException('Sorry, QNG and hessian not yet tested together.') combos = get_qng_combos(objective,func=func, initial_values=initial_values, backend=self.backend, samples=self.samples, noise=self.noise) dE = _QngContainer(combos=combos, param_keys=param_keys, passive_angles=passive_angles) infostring += "{:15} : QNG {}\n".format("gradient", dE) if isinstance(hessian, str): ddE = hessian compile_hessian = False if compile_gradient: dE =_GradContainer(Ham_derivatives = Ham_derivatives, unitary = unitary, Hamiltonian = H, Eval= E, param_keys=param_keys, samples=self.samples, passive_angles=passive_angles, save_history=self.save_history, print_level=self.print_level) dE.print_level = 0 (dE(param_values)) dE.print_level = self.print_level infostring += dE.infostring if self.print_level > 0: print(self) print(infostring) print("{:15} : {}\n".format("active variables", len(active_angles))) Es = [] optimizer_instance = self class SciPyCallback: energies = [] gradients = [] hessians = [] angles = [] real_iterations = 0 def __call__(self, *args, **kwargs): self.energies.append(E.history[-1]) self.angles.append(E.history_angles[-1]) if dE is not None and not isinstance(dE, str): self.gradients.append(dE.history[-1]) if ddE is not None and not isinstance(ddE, str): self.hessians.append(ddE.history[-1]) self.real_iterations += 1 if 'callback' in optimizer_instance.kwargs: optimizer_instance.kwargs['callback'](E.history_angles[-1]) callback = SciPyCallback() res = scipy.optimize.minimize(E, x0=param_values, jac=dE, hess=ddE, args=(Es,), method=self.method, tol=self.tol, bounds=bounds, constraints=self.method_constraints, options=self.method_options, callback=callback) # failsafe since callback is not implemented everywhere if callback.real_iterations == 0: real_iterations = range(len(E.history)) if self.save_history: self.history.energies = callback.energies self.history.energy_evaluations = E.history self.history.angles = callback.angles self.history.angles_evaluations = E.history_angles self.history.gradients = callback.gradients self.history.hessians = callback.hessians if dE is not None and not isinstance(dE, str): self.history.gradients_evaluations = dE.history if ddE is not None and not isinstance(ddE, str): self.history.hessians_evaluations = ddE.history # some methods like "cobyla" do not support callback functions if len(self.history.energies) == 0: self.history.energies = E.history self.history.angles = E.history_angles # some scipy methods always give back the last value and not the minimum (e.g. cobyla) ea = sorted(zip(E.history, E.history_angles), key=lambda x: x[0]) E_final = ea[0][0] angles_final = ea[0][1] #dict((param_keys[i], res.x[i]) for i in range(len(param_keys))) angles_final = {**angles_final, **passive_angles} return SciPyResults(energy=E_final, history=self.history, variables=format_variable_dictionary(angles_final), scipy_result=res) def minimize(Hamiltonian, unitary, gradient: typing.Union[str, typing.Dict[Variable, Objective]] = None, hessian: typing.Union[str, typing.Dict[typing.Tuple[Variable, Variable], Objective]] = None, initial_values: typing.Dict[typing.Hashable, numbers.Real] = None, variables: typing.List[typing.Hashable] = None, samples: int = None, maxiter: int = 100, backend: str = None, backend_options: dict = None, noise: NoiseModel = None, device: str = None, method: str = "BFGS", tol: float = 1.e-3, method_options: dict = None, method_bounds: typing.Dict[typing.Hashable, numbers.Real] = None, method_constraints=None, silent: bool = False, save_history: bool = True, *args, **kwargs) -> SciPyResults: """ calls the local optimize_scipy scipy funtion instead and pass down the objective construction down Parameters ---------- objective: Objective : The tequila objective to optimize gradient: typing.Union[str, typing.Dict[Variable, Objective], None] : Default value = None): '2-point', 'cs' or '3-point' for numerical gradient evaluation (does not work in combination with all optimizers), dictionary of variables and tequila objective to define own gradient, None for automatic construction (default) Other options include 'qng' to use the quantum natural gradient. hessian: typing.Union[str, typing.Dict[Variable, Objective], None], optional: '2-point', 'cs' or '3-point' for numerical gradient evaluation (does not work in combination with all optimizers), dictionary (keys:tuple of variables, values:tequila objective) to define own gradient, None for automatic construction (default) initial_values: typing.Dict[typing.Hashable, numbers.Real], optional: Initial values as dictionary of Hashable types (variable keys) and floating point numbers. If given None they will all be set to zero variables: typing.List[typing.Hashable], optional: List of Variables to optimize samples: int, optional: samples/shots to take in every run of the quantum circuits (None activates full wavefunction simulation) maxiter: int : (Default value = 100): max iters to use. backend: str, optional: Simulator backend, will be automatically chosen if set to None backend_options: dict, optional: Additional options for the backend Will be unpacked and passed to the compiled objective in every call noise: NoiseModel, optional: a NoiseModel to apply to all expectation values in the objective. method: str : (Default = "BFGS"): Optimization method (see scipy documentation, or 'available methods') tol: float : (Default = 1.e-3): Convergence tolerance for optimization (see scipy documentation) method_options: dict, optional: Dictionary of options (see scipy documentation) method_bounds: typing.Dict[typing.Hashable, typing.Tuple[float, float]], optional: bounds for the variables (see scipy documentation) method_constraints: optional: (see scipy documentation silent: bool : No printout if True save_history: bool: Save the history throughout the optimization Returns ------- SciPyReturnType: the results of optimization """ if isinstance(gradient, dict) or hasattr(gradient, "items"): if all([isinstance(x, Objective) for x in gradient.values()]): gradient = format_variable_dictionary(gradient) if isinstance(hessian, dict) or hasattr(hessian, "items"): if all([isinstance(x, Objective) for x in hessian.values()]): hessian = {(assign_variable(k[0]), assign_variable([k[1]])): v for k, v in hessian.items()} method_bounds = format_variable_dictionary(method_bounds) # set defaults optimizer = optimize_scipy(save_history=save_history, maxiter=maxiter, method=method, method_options=method_options, method_bounds=method_bounds, method_constraints=method_constraints, silent=silent, backend=backend, backend_options=backend_options, device=device, samples=samples, noise_model=noise, tol=tol, *args, **kwargs) if initial_values is not None: initial_values = {assign_variable(k): v for k, v in initial_values.items()} return optimizer(Hamiltonian, unitary, gradient=gradient, hessian=hessian, initial_values=initial_values, variables=variables, *args, **kwargs)
24,489
42.732143
144
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.2/energy_optimization.py
import tequila as tq import numpy as np from tequila.objective.objective import Variable import openfermion from hacked_openfermion_qubit_operator import ParamQubitHamiltonian from typing import Union from vqe_utils import convert_PQH_to_tq_QH, convert_tq_QH_to_PQH,\ fold_unitary_into_hamiltonian from grad_hacked import grad from scipy_optimizer import minimize import scipy import random # guess we could substitute that with numpy.random #TODO import argparse import pickle as pk import sys sys.path.insert(0, '../../../') #sys.path.insert(0, '../') # This needs to be properly integrated somewhere else at some point # from tn_update.qq import contract_energy, optimize_wavefunctions from tn_update.my_mpo import * from tn_update.wfn_optimization import contract_energy_mpo, optimize_wavefunctions_mpo, initialize_wfns_randomly def energy_from_wfn_opti(hamiltonian: tq.QubitHamiltonian, n_qubits: int, guess_wfns=None, TOL=1e-4) -> tuple: ''' Get energy using a tensornetwork based method ~ power method (here as blackbox) ''' d = int(2**(n_qubits/2)) # Build MPO h_mpo = MyMPO(hamiltonian=hamiltonian, n_qubits=n_qubits, maxdim=500) h_mpo.make_mpo_from_hamiltonian() # Optimize wavefunctions based on random guess out = None it = 0 while out is None: # Set up random initial guesses for subsystems it += 1 if guess_wfns is None: psiL_rand = initialize_wfns_randomly(d, n_qubits//2) psiR_rand = initialize_wfns_randomly(d, n_qubits//2) else: psiL_rand = guess_wfns[0] psiR_rand = guess_wfns[1] out = optimize_wavefunctions_mpo(h_mpo, psiL_rand, psiR_rand, TOL=TOL, silent=True) energy_rand = out[0] optimal_wfns = [out[1], out[2]] return energy_rand, optimal_wfns def combine_two_clusters(H: tq.QubitHamiltonian, subsystems: list, circ_list: list) -> float: ''' E = nuc_rep + \sum_j c_j <0_A | U_A+ sigma_j|A U_A | 0_A><0_B | U_B+ sigma_j|B U_B | 0_B> i ) Split up Hamiltonian into vector c = [c_j], all sigmas of system A and system B ii ) Two vectors of ExpectationValues E_A=[E(U_A, sigma_j|A)], E_B=[E(U_B, sigma_j|B)] iii) Minimize vectors from ii) iv ) Perform weighted sum \sum_j c_[j] E_A[j] E_B[j] result = nuc_rep + iv) Finishing touch inspired by private tequila-repo / pair-separated objective This is still rather inefficient/unoptimized Can still prune out near-zero coefficients c_j ''' objective = 0.0 n_subsystems = len(subsystems) # Over all Paulistrings in the Hamiltonian for p_index, pauli in enumerate(H.paulistrings): # Gather coefficient coeff = pauli.coeff.real # Empty dictionary for operations: # to be filled with another dictionary per subsystem, where then # e.g. X(0)Z(1)Y(2)X(4) and subsystems=[[0,1,2],[3,4,5]] # -> ops={ 0: {0: 'X', 1: 'Z', 2: 'Y'}, 1: {4: 'X'} } ops = {} for s_index, sys in enumerate(subsystems): for k, v in pauli.items(): if k in sys: if s_index in ops: ops[s_index][k] = v else: ops[s_index] = {k: v} # If no ops gathered -> identity -> nuclear repulsion if len(ops) == 0: #print ("this should only happen ONCE") objective += coeff # If not just identity: # add objective += c_j * prod_subsys( < Paulistring_j_subsys >_{U_subsys} ) elif len(ops) > 0: obj_tmp = coeff for s_index, sys_pauli in ops.items(): #print (s_index, sys_pauli) H_tmp = QubitHamiltonian.from_paulistrings(PauliString(data=sys_pauli)) E_tmp = ExpectationValue(U=circ_list[s_index], H=H_tmp) obj_tmp *= E_tmp objective += obj_tmp initial_values = {k: 0.0 for k in objective.extract_variables()} random_initial_values = {k: 1e-2*np.random.uniform(-1, 1) for k in objective.extract_variables()} method = 'bfgs' # 'bfgs' # 'l-bfgs-b' # 'cobyla' # 'slsqp' curr_res = tq.minimize(method=method, objective=objective, initial_values=initial_values, gradient='two-point', backend='qulacs', method_options={"finite_diff_rel_step": 1e-3}) return curr_res.energy def energy_from_tq_qcircuit(hamiltonian: Union[tq.QubitHamiltonian, ParamQubitHamiltonian], n_qubits: int, circuit = Union[list, tq.QCircuit], subsystems: list = [[0,1,2,3,4,5]], initial_guess = None)-> tuple: ''' Get minimal energy using tequila ''' result = None # If only one circuit handed over, just run simple VQE if isinstance(circuit, list) and len(circuit) == 1: circuit = circuit[0] if isinstance(circuit, tq.QCircuit): if isinstance(hamiltonian, tq.QubitHamiltonian): E = tq.ExpectationValue(H=hamiltonian, U=circuit) if initial_guess is None: initial_angles = {k: 0.0 for k in E.extract_variables()} else: initial_angles = initial_guess #print ("optimizing non-param...") result = tq.minimize(objective=E, method='l-bfgs-b', silent=True, backend='qulacs', initial_values=initial_angles) #gradient='two-point', backend='qulacs', #method_options={"finite_diff_rel_step": 1e-4}) elif isinstance(hamiltonian, ParamQubitHamiltonian): if initial_guess is None: raise Exception("Need to provide initial guess for this to work.") initial_angles = None else: initial_angles = initial_guess #print ("optimizing param...") result = minimize(hamiltonian, circuit, method='bfgs', initial_values=initial_angles, backend="qulacs", silent=True) # If more circuits handed over, assume subsystems else: # TODO!! implement initial guess for the combine_two_clusters thing #print ("Should not happen for now...") result = combine_two_clusters(hamiltonian, subsystems, circuit) return result.energy, result.angles def mixed_optimization(hamiltonian: ParamQubitHamiltonian, n_qubits: int, initial_guess: Union[dict, list]=None, init_angles: list=None): ''' Minimizes energy using wfn opti and a parametrized Hamiltonian min_{psi, theta fixed} <psi | H(theta) | psi> --> min_{t, p fixed} <p | H(t) | p> ^---------------------------------------------------^ until convergence ''' energy, optimal_state = None, None H_qh = convert_PQH_to_tq_QH(hamiltonian) var_keys, H_derivs = H_qh._construct_derivatives() print("var keys", var_keys, flush=True) print('var dict', init_angles, flush=True) # if not init_angles: # var_vals = [0. for i in range(len(var_keys))] # initialize with 0 # else: # var_vals = init_angles def build_variable_dict(keys, values): assert(len(keys)==len(values)) out = dict() for idx, key in enumerate(keys): out[key] = complex(values[idx]) return out var_dict = init_angles var_vals = [*init_angles.values()] assert(build_variable_dict(var_keys, var_vals) == var_dict) def wrap_energy_eval(psi): ''' like energy_from_wfn_opti but instead of optimize get inner product ''' def energy_eval_fn(x): var_dict = build_variable_dict(var_keys, x) H_qh_fix = H_qh(var_dict) H_mpo = MyMPO(hamiltonian=H_qh_fix, n_qubits=n_qubits, maxdim=500) H_mpo.make_mpo_from_hamiltonian() return contract_energy_mpo(H_mpo, psi[0], psi[1]) return energy_eval_fn def wrap_gradient_eval(psi): ''' call derivatives with updated variable list ''' def gradient_eval_fn(x): variables = build_variable_dict(var_keys, x) deriv_expectations = H_derivs.values() # list of ParamQubitHamiltonian's deriv_qhs = [convert_PQH_to_tq_QH(d) for d in deriv_expectations] deriv_qhs = [d(variables) for d in deriv_qhs] # list of tq.QubitHamiltonian's # print(deriv_qhs) deriv_mpos = [MyMPO(hamiltonian=d, n_qubits=n_qubits, maxdim=500)\ for d in deriv_qhs] # print(deriv_mpos[0].n_qubits) for d in deriv_mpos: d.make_mpo_from_hamiltonian() # deriv_mpos = [d.make_mpo_from_hamiltonian() for d in deriv_mpos] return np.asarray([contract_energy_mpo(d, psi[0], psi[1]) for d in deriv_mpos]) return gradient_eval_fn def do_wfn_opti(values, guess_wfns, TOL): # H_qh = H_qh(H_vars) var_dict = build_variable_dict(var_keys, values) en, psi = energy_from_wfn_opti(H_qh(var_dict), n_qubits=n_qubits, guess_wfns=guess_wfns, TOL=TOL) return en, psi def do_param_opti(psi, x0): result = scipy.optimize.minimize(fun=wrap_energy_eval(psi), jac=wrap_gradient_eval(psi), method='bfgs', x0=x0, options={'maxiter': 4}) # print(result) return result e_prev, psi_prev = 123., None # print("iguess", initial_guess) e_curr, psi_curr = do_wfn_opti(var_vals, initial_guess, 1e-5) print('first eval', e_curr, flush=True) def converged(e_prev, e_curr, TOL=1e-4): return True if np.abs(e_prev-e_curr) < TOL else False it = 0 var_prev = var_vals print("vars before comp", var_prev, flush=True) while not converged(e_prev, e_curr) and it < 50: e_prev, psi_prev = e_curr, psi_curr # print('before param opti') res = do_param_opti(psi_curr, var_prev) var_curr = res['x'] print('curr vars', var_curr, flush=True) e_curr = res['fun'] print('en before wfn opti', e_curr, flush=True) # print("iiiiiguess", psi_prev) e_curr, psi_curr = do_wfn_opti(var_curr, psi_prev, 1e-3) print('en after wfn opti', e_curr, flush=True) it += 1 print('at iteration', it, flush=True) return e_curr, psi_curr # optimize parameters with fixed wavefunction # define/wrap energy function - given |p>, evaluate <p|H(t)|p> ''' def wrap_gradient(objective: typing.Union[Objective, QTensor], no_compile=False, *args, **kwargs): def gradient_fn(variable: Variable = None): return grad(objective: typing.Union[Objective, QTensor], variable: Variable = None, no_compile=False, *args, **kwargs) return grad_fn ''' def minimize_energy(hamiltonian: Union[ParamQubitHamiltonian, tq.QubitHamiltonian], n_qubits: int, type_energy_eval: str='wfn', cluster_circuit: tq.QCircuit=None, initial_guess=None, initial_mixed_angles: dict=None) -> float: ''' Minimizes energy functional either according a power-method inspired shortcut ('wfn') or using a unitary circuit ('qc') ''' if type_energy_eval == 'wfn': if isinstance(hamiltonian, tq.QubitHamiltonian): energy, optimal_state = energy_from_wfn_opti(hamiltonian, n_qubits, initial_guess) elif isinstance(hamiltonian, ParamQubitHamiltonian): init_angles = initial_mixed_angles energy, optimal_state = mixed_optimization(hamiltonian=hamiltonian, n_qubits=n_qubits, initial_guess=initial_guess, init_angles=init_angles) elif type_energy_eval == 'qc': if cluster_circuit is None: raise Exception("Need to hand over circuit!") energy, optimal_state = energy_from_tq_qcircuit(hamiltonian, n_qubits, cluster_circuit, [[0,1,2,3],[4,5,6,7]], initial_guess) else: raise Exception("Option not implemented!") return energy, optimal_state
12,457
43.021201
225
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.2/parallel_annealing.py
import tequila as tq import multiprocessing import copy from time import sleep from mutation_options import * from pathos.multiprocessing import ProcessingPool as Pool def evolve_population(hamiltonian, type_energy_eval, cluster_circuit, process_id, num_offsprings, actions_ratio, tasks, results): """ This function carries a single step of the simulated annealing on a single member of the generation args: process_id: A unique identifier for each process num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for mutations tasks: multiprocessing queue to pass family_id, instructions and current_fitness family_id: A unique identifier for each family instructions: An object consisting of the instructions in the quantum circuit current_fitness: Current fitness value of the circuit results: multiprocessing queue to pass results back """ #print('[%s] evaluation routine starts' % process_id) while True: try: #getting parameters for mutation and carrying it family_id, instructions, current_fitness = tasks.get() #check if patience has been exhausted if instructions.patience == 0: instructions.reset_to_best() best_child = 0 best_energy = current_fitness new_generations = {} for off_id in range(1, num_offsprings+1): scheduled_ratio = schedule_actions_ratio(epoch=0, steady_ratio=actions_ratio) action = get_action(scheduled_ratio) updated_instructions = copy.deepcopy(instructions) updated_instructions.update_by_action(action) new_fitness, wfn = evaluate_fitness(updated_instructions, hamiltonian, type_energy_eval, cluster_circuit) updated_instructions.set_reference_wfn(wfn) prob_acceptance = get_prob_acceptance(current_fitness, new_fitness, updated_instructions.T, updated_instructions.reference_energy) # need to figure out in case we have two equals new_generations[str(off_id)] = updated_instructions if best_energy > new_fitness: # now two equals -> "first one" is picked best_child = off_id best_energy = new_fitness # decision = np.random.binomial(1, prob_acceptance) # if decision == 0: if best_child == 0: # Add result to the queue instructions.patience -= 1 #print('Reduced patience -- now ' + str(updated_instructions.patience)) if instructions.patience == 0: if instructions.best_previous_instructions: instructions.reset_to_best() else: instructions.update_T() results.put((family_id, instructions, current_fitness)) else: # Add result to the queue if (best_energy < current_fitness): new_generations[str(best_child)].update_best_previous_instructions() new_generations[str(best_child)].update_T() results.put((family_id, new_generations[str(best_child)], best_energy)) except Exception as eeee: #print('[%s] evaluation routine quits' % process_id) #print(eeee) # Indicate finished results.put(-1) break return def evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, num_processors=4, type_energy_eval='wfn', cluster_circuit=None): """ This function does parallel mutation on all the members of the generation and updates the generation args: num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for sampling instructions_dict: A dictionary with the "Instructions" objects the corresponding fitness values as values num_processors: Number of processors to use for parallel run """ # Define IPC manager manager = multiprocessing.Manager() # Define a list (queue) for tasks and computation results tasks = manager.Queue() results = manager.Queue() processes = [] pool = Pool(processes=num_processors) for i in range(num_processors): process_id = 'P%i' % i # Create the process, and connect it to the worker function new_process = multiprocessing.Process(target=evolve_population, args=(hamiltonian, type_energy_eval, cluster_circuit, process_id, num_offsprings, actions_ratio, tasks, results)) # Add new process to the list of processes processes.append(new_process) # Start the process new_process.start() #print("putting tasks") for family_id in instructions_dict: single_task = (family_id, instructions_dict[family_id][0], instructions_dict[family_id][1]) tasks.put(single_task) # Wait while the workers process - change it to something for our case later # sleep(5) multiprocessing.Barrier(num_processors) #print("after barrier") # Quit the worker processes by sending them -1 for i in range(num_processors): tasks.put(-1) # Read calculation results num_finished_processes = 0 while True: # Read result #print("num fin", num_finished_processes) try: family_id, updated_instructions, new_fitness = results.get() instructions_dict[family_id] = (updated_instructions, new_fitness) except: # Process has finished num_finished_processes += 1 if num_finished_processes == num_processors: break for process in processes: process.join() pool.close()
6,456
38.371951
146
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.2/single_thread_annealing.py
import tequila as tq import copy from mutation_options import * def st_evolve_population(hamiltonian, type_energy_eval, cluster_circuit, num_offsprings, actions_ratio, tasks): """ This function carries a single step of the simulated annealing on a single member of the generation args: num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for mutations tasks: a tuple of (family_id, instructions and current_fitness) family_id: A unique identifier for each family instructions: An object consisting of the instructions in the quantum circuit current_fitness: Current fitness value of the circuit """ family_id, instructions, current_fitness = tasks #check if patience has been exhausted if instructions.patience == 0: if instructions.best_previous_instructions: instructions.reset_to_best() best_child = 0 best_energy = current_fitness new_generations = {} for off_id in range(1, num_offsprings+1): scheduled_ratio = schedule_actions_ratio(epoch=0, steady_ratio=actions_ratio) action = get_action(scheduled_ratio) updated_instructions = copy.deepcopy(instructions) updated_instructions.update_by_action(action) new_fitness, wfn = evaluate_fitness(updated_instructions, hamiltonian, type_energy_eval, cluster_circuit) updated_instructions.set_reference_wfn(wfn) prob_acceptance = get_prob_acceptance(current_fitness, new_fitness, updated_instructions.T, updated_instructions.reference_energy) # need to figure out in case we have two equals new_generations[str(off_id)] = updated_instructions if best_energy > new_fitness: # now two equals -> "first one" is picked best_child = off_id best_energy = new_fitness # decision = np.random.binomial(1, prob_acceptance) # if decision == 0: if best_child == 0: # Add result to the queue instructions.patience -= 1 #print('Reduced patience -- now ' + str(updated_instructions.patience)) if instructions.patience == 0: if instructions.best_previous_instructions: instructions.reset_to_best() else: instructions.update_T() results = ((family_id, instructions, current_fitness)) else: # Add result to the queue if (best_energy < current_fitness): new_generations[str(best_child)].update_best_previous_instructions() new_generations[str(best_child)].update_T() results = ((family_id, new_generations[str(best_child)], best_energy)) return results def st_evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, type_energy_eval='wfn', cluster_circuit=None): """ This function does a single threas mutation on all the members of the generation and updates the generation args: num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for sampling instructions_dict: A dictionary with the "Instructions" objects the corresponding fitness values as values """ for family_id in instructions_dict: task = (family_id, instructions_dict[family_id][0], instructions_dict[family_id][1]) results = st_evolve_population(hamiltonian, type_energy_eval, cluster_circuit, num_offsprings, actions_ratio, task) family_id, updated_instructions, new_fitness = results instructions_dict[family_id] = (updated_instructions, new_fitness)
4,005
40.298969
138
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.2/mutation_options.py
import argparse import numpy as np import random import copy import tequila as tq from typing import Union from collections import Counter from time import time from vqe_utils import convert_PQH_to_tq_QH, convert_tq_QH_to_PQH,\ fold_unitary_into_hamiltonian from energy_optimization import minimize_energy global_seed = 1 class Instructions: ''' TODO need to put some documentation here ''' def __init__(self, n_qubits, mu=2.0, sigma=0.4, alpha=0.9, T_0=1.0, beta=0.5, patience=10, max_non_cliffords=0, reference_energy=0., number=None): # hardcoded values for now self.num_non_cliffords = 0 self.max_non_cliffords = max_non_cliffords # ------------------------ self.starting_patience = patience self.patience = patience self.mu = mu self.sigma = sigma self.alpha = alpha self.beta = beta self.T_0 = T_0 self.T = T_0 self.gates = self.get_random_gates(number=number) self.n_qubits = n_qubits self.positions = self.get_random_positions() self.best_previous_instructions = {} self.reference_energy = reference_energy self.best_reference_wfn = None self.noncliff_replacements = {} def _str(self): print(self.gates) print(self.positions) def set_reference_wfn(self, reference_wfn): self.best_reference_wfn = reference_wfn def update_T(self, update_type: str = 'regular', best_temp=None): # Regular update if update_type.lower() == 'regular': self.T = self.alpha * self.T # Temperature update if patience ran out elif update_type.lower() == 'patience': self.T = self.beta*best_temp + (1-self.beta)*self.T_0 def get_random_gates(self, number=None): ''' Randomly generates a list of gates. number indicates the number of gates to generate otherwise, number will be drawn from a log normal distribution ''' mu, sigma = self.mu, self.sigma full_options = ['X','Y','Z','S','H','CX', 'CY', 'CZ','SWAP', 'UCC2c', 'UCC4c', 'UCC2', 'UCC4'] clifford_options = ['X','Y','Z','S','H','CX', 'CY', 'CZ','SWAP', 'UCC2c', 'UCC4c'] #non_clifford_options = ['UCC2', 'UCC4'] # Gate distribution, selecting number of gates to add k = np.random.lognormal(mu, sigma) k = np.int(k) if number is not None: k = number # Selecting gate types gates = None if self.num_non_cliffords < self.max_non_cliffords: gates = random.choices(full_options, k=k) # with replacement else: gates = random.choices(clifford_options, k=k) new_num_non_cliffords = 0 if "UCC2" in gates: new_num_non_cliffords += Counter(gates)["UCC2"] if "UCC4" in gates: new_num_non_cliffords += Counter(gates)["UCC4"] if (new_num_non_cliffords+self.num_non_cliffords) <= self.max_non_cliffords: self.num_non_cliffords += new_num_non_cliffords else: extra_cliffords = (new_num_non_cliffords+self.num_non_cliffords) - self.max_non_cliffords assert(extra_cliffords >= 0) new_gates = random.choices(clifford_options, k=extra_cliffords) for g in new_gates: try: gates[gates.index("UCC4")] = g except: gates[gates.index("UCC2")] = g self.num_non_cliffords = self.max_non_cliffords if k == 1: if gates == "UCC2c" or gates == "UCC4c": gates = get_string_Cliff_ucc(gates) if gates == "UCC2" or gates == "UCC4": gates = get_string_ucc(gates) else: for ind, gate in enumerate(gates): if gate == "UCC2c" or gate == "UCC4c": gates[ind] = get_string_Cliff_ucc(gate) if gate == "UCC2" or gate == "UCC4": gates[ind] = get_string_ucc(gate) return gates def get_random_positions(self, gates=None): ''' Randomly assign gates to qubits. ''' if gates is None: gates = self.gates n_qubits = self.n_qubits single_qubit = ['X','Y','Z','S','H'] # two_qubit = ['CX','CY','CZ', 'SWAP'] two_qubit = ['CX', 'CY', 'CZ', 'SWAP', 'UCC2c', 'UCC2'] four_qubit = ['UCC4c', 'UCC4'] qubits = list(range(0, n_qubits)) q_positions = [] for gate in gates: if gate in four_qubit: p = random.sample(qubits, k=4) if gate in two_qubit: p = random.sample(qubits, k=2) if gate in single_qubit: p = random.sample(qubits, k=1) if "UCC2" in gate: p = random.sample(qubits, k=2) if "UCC4" in gate: p = random.sample(qubits, k=4) q_positions.append(p) return q_positions def delete(self, number=None): ''' Randomly drops some gates from a clifford instruction set if not specified, the number of gates to drop is sampled from a uniform distribution over all the gates ''' gates = copy.deepcopy(self.gates) positions = copy.deepcopy(self.positions) n_qubits = self.n_qubits if number is not None: num_to_drop = number else: num_to_drop = random.sample(range(1,len(gates)-1), k=1)[0] action_indices = random.sample(range(0,len(gates)-1), k=num_to_drop) for index in sorted(action_indices, reverse=True): if "UCC2_" in str(gates[index]) or "UCC4_" in str(gates[index]): self.num_non_cliffords -= 1 del gates[index] del positions[index] self.gates = gates self.positions = positions #print ('deleted {} gates'.format(num_to_drop)) def add(self, number=None): ''' adds a random selection of clifford gates to the end of a clifford instruction set if number is not specified, the number of gates to add will be drawn from a log normal distribution ''' gates = copy.deepcopy(self.gates) positions = copy.deepcopy(self.positions) n_qubits = self.n_qubits added_instructions = self.get_new_instructions(number=number) gates.extend(added_instructions['gates']) positions.extend(added_instructions['positions']) self.gates = gates self.positions = positions #print ('added {} gates'.format(len(added_instructions['gates']))) def change(self, number=None): ''' change a random number of gates and qubit positions in a clifford instruction set if not specified, the number of gates to change is sampled from a uniform distribution over all the gates ''' gates = copy.deepcopy(self.gates) positions = copy.deepcopy(self.positions) n_qubits = self.n_qubits if number is not None: num_to_change = number else: num_to_change = random.sample(range(1,len(gates)), k=1)[0] action_indices = random.sample(range(0,len(gates)-1), k=num_to_change) added_instructions = self.get_new_instructions(number=num_to_change) for i in range(num_to_change): gates[action_indices[i]] = added_instructions['gates'][i] positions[action_indices[i]] = added_instructions['positions'][i] self.gates = gates self.positions = positions #print ('changed {} gates'.format(len(added_instructions['gates']))) # TODO to be debugged! def prune(self): ''' Prune instructions to remove redundant operations: --> first gate should go beyond subsystems (this assumes expressible enough subsystem-ciruits #TODO later -> this needs subsystem information in here! --> 2 subsequent gates that are their respective inverse can be removed #TODO this might change the number of qubits acted on in theory? ''' pass #print ("DEBUG PRUNE FUNCTION!") # gates = copy.deepcopy(self.gates) # positions = copy.deepcopy(self.positions) # for g_index in range(len(gates)-1): # if (gates[g_index] == gates[g_index+1] and not 'S' in gates[g_index])\ # or (gates[g_index] == 'S' and gates[g_index+1] == 'S-dag')\ # or (gates[g_index] == 'S-dag' and gates[g_index+1] == 'S'): # print(len(gates)) # if positions[g_index] == positions[g_index+1]: # self.gates.pop(g_index) # self.positions.pop(g_index) def update_by_action(self, action: str): ''' Updates instruction dictionary -> Either adds, deletes or changes gates ''' if action == 'delete': try: self.delete() # In case there are too few gates to delete except: pass elif action == 'add': self.add() elif action == 'change': self.change() else: raise Exception("Unknown action type " + action + ".") self.prune() def update_best_previous_instructions(self): ''' Overwrites the best previous instructions with the current ones. ''' self.best_previous_instructions['gates'] = copy.deepcopy(self.gates) self.best_previous_instructions['positions'] = copy.deepcopy(self.positions) self.best_previous_instructions['T'] = copy.deepcopy(self.T) def reset_to_best(self): ''' Overwrites the current instructions with best previous ones. ''' #print ('Patience ran out... resetting to best previous instructions.') self.gates = copy.deepcopy(self.best_previous_instructions['gates']) self.positions = copy.deepcopy(self.best_previous_instructions['positions']) self.patience = copy.deepcopy(self.starting_patience) self.update_T(update_type='patience', best_temp=copy.deepcopy(self.best_previous_instructions['T'])) def get_new_instructions(self, number=None): ''' Returns a a clifford instruction set, a dictionary of gates and qubit positions for building a clifford circuit ''' mu = self.mu sigma = self.sigma n_qubits = self.n_qubits instruction = {} gates = self.get_random_gates(number=number) q_positions = self.get_random_positions(gates) assert(len(q_positions) == len(gates)) instruction['gates'] = gates instruction['positions'] = q_positions # instruction['n_qubits'] = n_qubits # instruction['patience'] = patience # instruction['best_previous_options'] = {} return instruction def replace_cg_w_ncg(self, gate_id): ''' replaces a set of Clifford gates with corresponding non-Cliffords ''' print("gates before", self.gates, flush=True) gate = self.gates[gate_id] if gate == 'X': gate = "Rx" elif gate == 'Y': gate = "Ry" elif gate == 'Z': gate = "Rz" elif gate == 'S': gate = "S_nc" #gate = "Rz" elif gate == 'H': gate = "H_nc" # this does not work??????? # gate = "Ry" elif gate == 'CX': gate = "CRx" elif gate == 'CY': gate = "CRy" elif gate == 'CZ': gate = "CRz" elif gate == 'SWAP':#find a way to change this as well pass # gate = "SWAP" elif "UCC2c" in str(gate): pre_gate = gate.split("_")[0] mid_gate = gate.split("_")[-1] gate = pre_gate + "_" + "UCC2" + "_" +mid_gate elif "UCC4c" in str(gate): pre_gate = gate.split("_")[0] mid_gate = gate.split("_")[-1] gate = pre_gate + "_" + "UCC4" + "_" + mid_gate self.gates[gate_id] = gate print("gates after", self.gates, flush=True) def build_circuit(instructions): ''' constructs a tequila circuit from a clifford instruction set ''' gates = instructions.gates q_positions = instructions.positions init_angles = {} clifford_circuit = tq.QCircuit() # for i in range(1, len(gates)): # TODO len(q_positions) not == len(gates) for i in range(len(gates)): if len(q_positions[i]) == 2: q1, q2 = q_positions[i] elif len(q_positions[i]) == 1: q1 = q_positions[i] q2 = None elif not len(q_positions[i]) == 4: raise Exception("q_positions[i] must have length 1, 2 or 4...") if gates[i] == 'X': clifford_circuit += tq.gates.X(q1) if gates[i] == 'Y': clifford_circuit += tq.gates.Y(q1) if gates[i] == 'Z': clifford_circuit += tq.gates.Z(q1) if gates[i] == 'S': clifford_circuit += tq.gates.S(q1) if gates[i] == 'H': clifford_circuit += tq.gates.H(q1) if gates[i] == 'CX': clifford_circuit += tq.gates.CX(q1, q2) if gates[i] == 'CY': #using generators clifford_circuit += tq.gates.S(q2) clifford_circuit += tq.gates.CX(q1, q2) clifford_circuit += tq.gates.S(q2).dagger() if gates[i] == 'CZ': #using generators clifford_circuit += tq.gates.H(q2) clifford_circuit += tq.gates.CX(q1, q2) clifford_circuit += tq.gates.H(q2) if gates[i] == 'SWAP': clifford_circuit += tq.gates.CX(q1, q2) clifford_circuit += tq.gates.CX(q2, q1) clifford_circuit += tq.gates.CX(q1, q2) if "UCC2c" in str(gates[i]) or "UCC4c" in str(gates[i]): clifford_circuit += get_clifford_UCC_circuit(gates[i], q_positions[i]) # NON-CLIFFORD STUFF FROM HERE ON global global_seed if gates[i] == "S_nc": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.S(q1) clifford_circuit += tq.gates.Rz(angle=var_name, target=q1) if gates[i] == "H_nc": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.H(q1) clifford_circuit += tq.gates.Ry(angle=var_name, target=q1) if gates[i] == "Rx": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.X(q1) clifford_circuit += tq.gates.Rx(angle=var_name, target=q1) if gates[i] == "Ry": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.Y(q1) clifford_circuit += tq.gates.Ry(angle=var_name, target=q1) if gates[i] == "Rz": global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0 clifford_circuit += tq.gates.Z(q1) clifford_circuit += tq.gates.Rz(angle=var_name, target=q1) if gates[i] == "CRx": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = np.pi clifford_circuit += tq.gates.Rx(angle=var_name, target=q2, control=q1) if gates[i] == "CRy": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = np.pi clifford_circuit += tq.gates.Ry(angle=var_name, target=q2, control=q1) if gates[i] == "CRz": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = np.pi clifford_circuit += tq.gates.Rz(angle=var_name, target=q2, control=q1) def get_ucc_init_angles(gate): angle = None pre_gate = gate.split("_")[0] mid_gate = gate.split("_")[-1] if mid_gate == 'Z': angle = 0. elif mid_gate == 'S': angle = 0. elif mid_gate == 'S-dag': angle = 0. else: raise Exception("This should not happen -- center/mid gate should be Z,S,S_dag.") return angle if "UCC2_" in str(gates[i]) or "UCC4_" in str(gates[i]): uccc_circuit = get_non_clifford_UCC_circuit(gates[i], q_positions[i]) clifford_circuit += uccc_circuit try: var_name = uccc_circuit.extract_variables()[0] init_angles[var_name]= get_ucc_init_angles(gates[i]) except: init_angles = {} return clifford_circuit, init_angles def get_non_clifford_UCC_circuit(gate, positions): """ """ pre_cir_dic = {"X":tq.gates.X, "Y":tq.gates.Y, "H":tq.gates.H, "I":None} pre_gate = gate.split("_")[0] pre_gates = pre_gate.split(*"#") pre_circuit = tq.QCircuit() for i, pos in enumerate(positions): try: pre_circuit += pre_cir_dic[pre_gates[i]](pos) except: pass for i, pos in enumerate(positions[:-1]): pre_circuit += tq.gates.CX(pos, positions[i+1]) global global_seed mid_gate = gate.split("_")[-1] mid_circuit = tq.QCircuit() if mid_gate == "S": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit += tq.gates.S(positions[-1]) mid_circuit += tq.gates.Rz(angle=tq.Variable(var_name), target=positions[-1]) elif mid_gate == "S-dag": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit += tq.gates.S(positions[-1]).dagger() mid_circuit += tq.gates.Rz(angle=tq.Variable(var_name), target=positions[-1]) elif mid_gate == "Z": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit += tq.gates.Z(positions[-1]) mid_circuit += tq.gates.Rz(angle=tq.Variable(var_name), target=positions[-1]) return pre_circuit + mid_circuit + pre_circuit.dagger() def get_string_Cliff_ucc(gate): """ this function randomly sample basis change and mid circuit elements for a ucc-type clifford circuit and adds it to the gate """ pre_circ_comp = ["X", "Y", "H", "I"] mid_circ_comp = ["S", "S-dag", "Z"] p = None if "UCC2c" in gate: p = random.sample(pre_circ_comp, k=2) elif "UCC4c" in gate: p = random.sample(pre_circ_comp, k=4) pre_gate = "#".join([str(item) for item in p]) mid_gate = random.sample(mid_circ_comp, k=1)[0] return str(pre_gate + "_" + gate + "_" + mid_gate) def get_string_ucc(gate): """ this function randomly sample basis change and mid circuit elements for a ucc-type clifford circuit and adds it to the gate """ pre_circ_comp = ["X", "Y", "H", "I"] p = None if "UCC2" in gate: p = random.sample(pre_circ_comp, k=2) elif "UCC4" in gate: p = random.sample(pre_circ_comp, k=4) pre_gate = "#".join([str(item) for item in p]) mid_gate = str(random.random() * 2 * np.pi) return str(pre_gate + "_" + gate + "_" + mid_gate) def get_clifford_UCC_circuit(gate, positions): """ This function creates an approximate UCC excitation circuit using only clifford Gates """ #pre_circ_comp = ["X", "Y", "H", "I"] pre_cir_dic = {"X":tq.gates.X, "Y":tq.gates.Y, "H":tq.gates.H, "I":None} pre_gate = gate.split("_")[0] pre_gates = pre_gate.split(*"#") #pre_gates = [] #if gate == "UCC2": # pre_gates = random.choices(pre_circ_comp, k=2) #if gate == "UCC4": # pre_gates = random.choices(pre_circ_comp, k=4) pre_circuit = tq.QCircuit() for i, pos in enumerate(positions): try: pre_circuit += pre_cir_dic[pre_gates[i]](pos) except: pass for i, pos in enumerate(positions[:-1]): pre_circuit += tq.gates.CX(pos, positions[i+1]) #mid_circ_comp = ["S", "S-dag", "Z"] #mid_gate = random.sample(mid_circ_comp, k=1)[0] mid_gate = gate.split("_")[-1] mid_circuit = tq.QCircuit() if mid_gate == "S": mid_circuit += tq.gates.S(positions[-1]) elif mid_gate == "S-dag": mid_circuit += tq.gates.S(positions[-1]).dagger() elif mid_gate == "Z": mid_circuit += tq.gates.Z(positions[-1]) return pre_circuit + mid_circuit + pre_circuit.dagger() def get_UCC_circuit(gate, positions): """ This function creates an UCC excitation circuit """ #pre_circ_comp = ["X", "Y", "H", "I"] pre_cir_dic = {"X":tq.gates.X, "Y":tq.gates.Y, "H":tq.gates.H, "I":None} pre_gate = gate.split("_")[0] pre_gates = pre_gate.split(*"#") pre_circuit = tq.QCircuit() for i, pos in enumerate(positions): try: pre_circuit += pre_cir_dic[pre_gates[i]](pos) except: pass for i, pos in enumerate(positions[:-1]): pre_circuit += tq.gates.CX(pos, positions[i+1]) mid_gate_val = gate.split("_")[-1] global global_seed np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit = tq.gates.Rz(target=positions[-1], angle=tq.Variable(var_name)) # mid_circ_comp = ["S", "S-dag", "Z"] # mid_gate = random.sample(mid_circ_comp, k=1)[0] # mid_circuit = tq.QCircuit() # if mid_gate == "S": # mid_circuit += tq.gates.S(positions[-1]) # elif mid_gate == "S-dag": # mid_circuit += tq.gates.S(positions[-1]).dagger() # elif mid_gate == "Z": # mid_circuit += tq.gates.Z(positions[-1]) return pre_circuit + mid_circuit + pre_circuit.dagger() def schedule_actions_ratio(epoch: int, action_options: list = ['delete', 'change', 'add'], decay: int = 30, steady_ratio: Union[tuple, list] = [0.2, 0.6, 0.2]) -> list: delete, change, add = tuple(steady_ratio) actions_ratio = [] for action in action_options: if action == 'delete': actions_ratio += [ delete*(1-np.exp(-1*epoch / decay)) ] elif action == 'change': actions_ratio += [ change*(1-np.exp(-1*epoch / decay)) ] elif action == 'add': actions_ratio += [ (1-add)*np.exp(-1*epoch / decay) + add ] else: print('Action type ', action, ' not defined!') # unnecessary for current schedule # if not np.isclose(np.sum(actions_ratio), 1.0): # actions_ratio /= np.sum(actions_ratio) return actions_ratio def get_action(ratio: list = [0.20,0.60,0.20]): ''' randomly chooses an action from delete, change, add ratio denotes the multinomial probabilities ''' choice = np.random.multinomial(n=1, pvals = ratio, size = 1) index = np.where(choice[0] == 1) action_options = ['delete', 'change', 'add'] action = action_options[index[0].item()] return action def get_prob_acceptance(E_curr, E_prev, T, reference_energy): ''' Computes acceptance probability of a certain action based on change in energy ''' delta_E = E_curr - E_prev prob = 0 if delta_E < 0 and E_curr < reference_energy: prob = 1 else: if E_curr < reference_energy: prob = np.exp(-delta_E/T) else: prob = 0 return prob def perform_folding(hamiltonian, circuit): # QubitHamiltonian -> ParamQubitHamiltonian param_hamiltonian = convert_tq_QH_to_PQH(hamiltonian) gates = circuit.gates # Go backwards gates.reverse() for gate in gates: # print("\t folding", gate) param_hamiltonian = (fold_unitary_into_hamiltonian(gate, param_hamiltonian)) # hamiltonian = convert_PQH_to_tq_QH(param_hamiltonian)() hamiltonian = param_hamiltonian return hamiltonian def evaluate_fitness(instructions, hamiltonian: tq.QubitHamiltonian, type_energy_eval: str, cluster_circuit: tq.QCircuit=None) -> tuple: ''' Evaluates fitness=objective=energy given a system for a set of instructions ''' #print ("evaluating fitness") n_qubits = instructions.n_qubits clifford_circuit, init_angles = build_circuit(instructions) # tq.draw(clifford_circuit, backend="cirq") ## TODO check if cluster_circuit is parametrized t0 = time() t1 = None folded_hamiltonian = perform_folding(hamiltonian, clifford_circuit) t1 = time() #print ("\tfolding took ", t1-t0) parametrized = len(clifford_circuit.extract_variables()) > 0 initial_guess = None if not parametrized: folded_hamiltonian = (convert_PQH_to_tq_QH(folded_hamiltonian))() elif parametrized: # TODO clifford_circuit is both ref + rest; so nomenclature is shit here variables = [gate.extract_variables() for gate in clifford_circuit.gates\ if gate.extract_variables()] variables = np.array(variables).flatten().tolist() # TODO this initial_guess is absolutely useless rn and is just causing problems if called initial_guess = { k: 0.1 for k in variables } if instructions.best_reference_wfn is not None: initial_guess = instructions.best_reference_wfn E_new, optimal_state = minimize_energy(hamiltonian=folded_hamiltonian, n_qubits=n_qubits, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit, initial_guess=initial_guess,\ initial_mixed_angles=init_angles) t2 = time() #print ("evaluated fitness; comp was ", t2-t1) #print ("current fitness: ", E_new) return E_new, optimal_state
26,497
34.096689
191
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.2/hacked_openfermion_qubit_operator.py
import tequila as tq import sympy import copy #from param_hamiltonian import get_geometry, generate_ucc_ansatz from hacked_openfermion_symbolic_operator import SymbolicOperator # Define products of all Pauli operators for symbolic multiplication. _PAULI_OPERATOR_PRODUCTS = { ('I', 'I'): (1., 'I'), ('I', 'X'): (1., 'X'), ('X', 'I'): (1., 'X'), ('I', 'Y'): (1., 'Y'), ('Y', 'I'): (1., 'Y'), ('I', 'Z'): (1., 'Z'), ('Z', 'I'): (1., 'Z'), ('X', 'X'): (1., 'I'), ('Y', 'Y'): (1., 'I'), ('Z', 'Z'): (1., 'I'), ('X', 'Y'): (1.j, 'Z'), ('X', 'Z'): (-1.j, 'Y'), ('Y', 'X'): (-1.j, 'Z'), ('Y', 'Z'): (1.j, 'X'), ('Z', 'X'): (1.j, 'Y'), ('Z', 'Y'): (-1.j, 'X') } _clifford_h_products = { ('I') : (1., 'I'), ('X') : (1., 'Z'), ('Y') : (-1., 'Y'), ('Z') : (1., 'X') } _clifford_s_products = { ('I') : (1., 'I'), ('X') : (-1., 'Y'), ('Y') : (1., 'X'), ('Z') : (1., 'Z') } _clifford_s_dag_products = { ('I') : (1., 'I'), ('X') : (1., 'Y'), ('Y') : (-1., 'X'), ('Z') : (1., 'Z') } _clifford_cx_products = { ('I', 'I'): (1., 'I', 'I'), ('I', 'X'): (1., 'I', 'X'), ('I', 'Y'): (1., 'Z', 'Y'), ('I', 'Z'): (1., 'Z', 'Z'), ('X', 'I'): (1., 'X', 'X'), ('X', 'X'): (1., 'X', 'I'), ('X', 'Y'): (1., 'Y', 'Z'), ('X', 'Z'): (-1., 'Y', 'Y'), ('Y', 'I'): (1., 'Y', 'X'), ('Y', 'X'): (1., 'Y', 'I'), ('Y', 'Y'): (-1., 'X', 'Z'), ('Y', 'Z'): (1., 'X', 'Y'), ('Z', 'I'): (1., 'Z', 'I'), ('Z', 'X'): (1., 'Z', 'X'), ('Z', 'Y'): (1., 'I', 'Y'), ('Z', 'Z'): (1., 'I', 'Z'), } _clifford_cy_products = { ('I', 'I'): (1., 'I', 'I'), ('I', 'X'): (1., 'Z', 'X'), ('I', 'Y'): (1., 'I', 'Y'), ('I', 'Z'): (1., 'Z', 'Z'), ('X', 'I'): (1., 'X', 'Y'), ('X', 'X'): (-1., 'Y', 'Z'), ('X', 'Y'): (1., 'X', 'I'), ('X', 'Z'): (-1., 'Y', 'X'), ('Y', 'I'): (1., 'Y', 'Y'), ('Y', 'X'): (1., 'X', 'Z'), ('Y', 'Y'): (1., 'Y', 'I'), ('Y', 'Z'): (-1., 'X', 'X'), ('Z', 'I'): (1., 'Z', 'I'), ('Z', 'X'): (1., 'I', 'X'), ('Z', 'Y'): (1., 'Z', 'Y'), ('Z', 'Z'): (1., 'I', 'Z'), } _clifford_cz_products = { ('I', 'I'): (1., 'I', 'I'), ('I', 'X'): (1., 'Z', 'X'), ('I', 'Y'): (1., 'Z', 'Y'), ('I', 'Z'): (1., 'I', 'Z'), ('X', 'I'): (1., 'X', 'Z'), ('X', 'X'): (-1., 'Y', 'Y'), ('X', 'Y'): (-1., 'Y', 'X'), ('X', 'Z'): (1., 'X', 'I'), ('Y', 'I'): (1., 'Y', 'Z'), ('Y', 'X'): (-1., 'X', 'Y'), ('Y', 'Y'): (1., 'X', 'X'), ('Y', 'Z'): (1., 'Y', 'I'), ('Z', 'I'): (1., 'Z', 'I'), ('Z', 'X'): (1., 'I', 'X'), ('Z', 'Y'): (1., 'I', 'Y'), ('Z', 'Z'): (1., 'Z', 'Z'), } COEFFICIENT_TYPES = (int, float, complex, sympy.Expr, tq.Variable) class ParamQubitHamiltonian(SymbolicOperator): @property def actions(self): """The allowed actions.""" return ('X', 'Y', 'Z') @property def action_strings(self): """The string representations of the allowed actions.""" return ('X', 'Y', 'Z') @property def action_before_index(self): """Whether action comes before index in string representations.""" return True @property def different_indices_commute(self): """Whether factors acting on different indices commute.""" return True def renormalize(self): """Fix the trace norm of an operator to 1""" norm = self.induced_norm(2) if numpy.isclose(norm, 0.0): raise ZeroDivisionError('Cannot renormalize empty or zero operator') else: self /= norm def _simplify(self, term, coefficient=1.0): """Simplify a term using commutator and anti-commutator relations.""" if not term: return coefficient, term term = sorted(term, key=lambda factor: factor[0]) new_term = [] left_factor = term[0] for right_factor in term[1:]: left_index, left_action = left_factor right_index, right_action = right_factor # Still on the same qubit, keep simplifying. if left_index == right_index: new_coefficient, new_action = _PAULI_OPERATOR_PRODUCTS[ left_action, right_action] left_factor = (left_index, new_action) coefficient *= new_coefficient # Reached different qubit, save result and re-initialize. else: if left_action != 'I': new_term.append(left_factor) left_factor = right_factor # Save result of final iteration. if left_factor[1] != 'I': new_term.append(left_factor) return coefficient, tuple(new_term) def _clifford_simplify_h(self, qubit): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 for left, right in term: if left == qubit: coeff, new_pauli = _clifford_h_products[right] new_term.append(tuple((left, new_pauli))) else: new_term.append(tuple((left,right))) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self def _clifford_simplify_s(self, qubit): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 for left, right in term: if left == qubit: coeff, new_pauli = _clifford_s_products[right] new_term.append(tuple((left, new_pauli))) else: new_term.append(tuple((left,right))) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self def _clifford_simplify_s_dag(self, qubit): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 for left, right in term: if left == qubit: coeff, new_pauli = _clifford_s_dag_products[right] new_term.append(tuple((left, new_pauli))) else: new_term.append(tuple((left,right))) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self def _clifford_simplify_control_g(self, axis, control_q, target_q): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 target = "I" control = "I" for left, right in term: if left == control_q: control = right elif left == target_q: target = right else: new_term.append(tuple((left,right))) new_c = "I" new_t = "I" if not (target == "I" and control == "I"): if axis == "X": coeff, new_c, new_t = _clifford_cx_products[control, target] if axis == "Y": coeff, new_c, new_t = _clifford_cy_products[control, target] if axis == "Z": coeff, new_c, new_t = _clifford_cz_products[control, target] if new_c != "I": new_term.append(tuple((control_q, new_c))) if new_t != "I": new_term.append(tuple((target_q, new_t))) new_term = sorted(new_term, key=lambda factor: factor[0]) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self if __name__ == "__main__": """geometry = get_geometry("H2", 0.714) print(geometry) basis_set = 'sto-3g' ref_anz, uccsd_anz, ham = generate_ucc_ansatz(geometry, basis_set) print(ham) b_ham = tq.grouping.binary_rep.BinaryHamiltonian.init_from_qubit_hamiltonian(ham) c_ham = tq.grouping.binary_rep.BinaryHamiltonian.init_from_qubit_hamiltonian(ham) print(b_ham) print(b_ham.get_binary()) print(b_ham.get_coeff()) param = uccsd_anz.extract_variables() print(param) for term in b_ham.binary_terms: print(term.coeff) term.set_coeff(param[0]) print(term.coeff) print(b_ham.get_coeff()) d_ham = c_ham.to_qubit_hamiltonian() + b_ham.to_qubit_hamiltonian() """ term = [(2,'X'), (0,'Y'), (3, 'Z')] coeff = tq.Variable("a") coeff = coeff *2.j print(coeff) print(type(coeff)) print(coeff({"a":1})) ham = ParamQubitHamiltonian(term= term, coefficient=coeff) print(ham.terms) print(str(ham)) for term in ham.terms: print(ham.terms[term]({"a":1,"b":2})) term = [(2,'X'), (0,'Z'), (3, 'Z')] coeff = tq.Variable("b") print(coeff({"b":1})) b_ham = ParamQubitHamiltonian(term= term, coefficient=coeff) print(b_ham.terms) print(str(b_ham)) for term in b_ham.terms: print(b_ham.terms[term]({"a":1,"b":2})) coeff = tq.Variable("a")*tq.Variable("b") print(coeff) print(coeff({"a":1,"b":2})) ham *= b_ham print(ham.terms) print(str(ham)) for term in ham.terms: coeff = (ham.terms[term]) print(coeff) print(coeff({"a":1,"b":2})) ham = ham*2. print(ham.terms) print(str(ham))
9,918
29.614198
85
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.2/HEA.py
import tequila as tq import numpy as np from tequila import gates as tq_g from tequila.objective.objective import Variable def generate_HEA(num_qubits, circuit_id=11, num_layers=1): """ This function generates different types of hardware efficient circuits as in this paper https://onlinelibrary.wiley.com/doi/full/10.1002/qute.201900070 param: num_qubits (int) -> the number of qubits in the circuit param: circuit_id (int) -> the type of hardware efficient circuit param: num_layers (int) -> the number of layers of the HEA input: num_qubits -> 4 circuit_id -> 11 num_layers -> 1 returns: ansatz (tq.QCircuit()) -> a circuit as shown below 0: ───Ry(0.318309886183791*pi*f((y0,))_0)───Rz(0.318309886183791*pi*f((z0,))_1)───@───────────────────────────────────────────────────────────────────────────────────── │ 1: ───Ry(0.318309886183791*pi*f((y1,))_2)───Rz(0.318309886183791*pi*f((z1,))_3)───X───Ry(0.318309886183791*pi*f((y4,))_8)────Rz(0.318309886183791*pi*f((z4,))_9)────@─── │ 2: ───Ry(0.318309886183791*pi*f((y2,))_4)───Rz(0.318309886183791*pi*f((z2,))_5)───@───Ry(0.318309886183791*pi*f((y5,))_10)───Rz(0.318309886183791*pi*f((z5,))_11)───X─── │ 3: ───Ry(0.318309886183791*pi*f((y3,))_6)───Rz(0.318309886183791*pi*f((z3,))_7)───X───────────────────────────────────────────────────────────────────────────────────── """ circuit = tq.QCircuit() qubits = [i for i in range(num_qubits)] if circuit_id == 1: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 2: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.CNOT(target=qubit, control=qubits[ind]) return circuit elif circuit_id == 3: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=qubit, control=qubits[ind]) count += 1 return circuit elif circuit_id == 4: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=qubit, control=qubits[ind]) count += 1 return circuit elif circuit_id == 5: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): for target in qubits: if control != target: variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=target, control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 6: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=qubits[ind+1], control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=qubits[ind+1], control=control) count += 1 return circuit elif circuit_id == 7: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): for target in qubits: if control != target: variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=target, control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 8: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=qubits[ind+1], control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=qubits[ind+1], control=control) count += 1 return circuit elif circuit_id == 9: count = 0 for _ in range(num_layers): for qubit in qubits: circuit += tq_g.H(qubit) for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.Z(target=qubit, control=qubits[ind]) for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 10: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.Z(target=qubit, control=qubits[ind]) circuit += tq_g.Z(target=qubits[0], control=qubits[-1]) for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 11: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: circuit += tq_g.X(target=qubits[ind+1], control=control) for ind, qubit in enumerate(qubits[1:-1]): variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: circuit += tq_g.X(target=qubits[ind+1], control=control) return circuit elif circuit_id == 12: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: circuit += tq_g.Z(target=qubits[ind+1], control=control) for ind, control in enumerate(qubits[1:-1]): variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = control) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = control) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: circuit += tq_g.Z(target=qubits[ind+1], control=control) return circuit elif circuit_id == 13: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubit, control=qubits[ind]) count += 1 variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubits[0], control=qubits[-1]) count += 1 for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=qubit, target=qubits[ind]) count += 1 variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=qubits[0], target=qubits[-1]) count += 1 return circuit elif circuit_id == 14: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubit, control=qubits[ind]) count += 1 variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubits[0], control=qubits[-1]) count += 1 for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=qubit, target=qubits[ind]) count += 1 variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=qubits[0], target=qubits[-1]) count += 1 return circuit elif circuit_id == 15: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.X(target=qubit, control=qubits[ind]) circuit += tq_g.X(control=qubits[-1], target=qubits[0]) for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.X(control=qubit, target=qubits[ind]) circuit += tq_g.X(target=qubits[-1], control=qubits[0]) return circuit elif circuit_id == 16: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=control, target=qubits[ind+1]) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=control, target=qubits[ind+1]) count += 1 return circuit elif circuit_id == 17: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=control, target=qubits[ind+1]) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=control, target=qubits[ind+1]) count += 1 return circuit elif circuit_id == 18: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[:-1]): variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubit, control=qubits[ind+1]) count += 1 variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubits[-1], control=qubits[0]) count += 1 return circuit elif circuit_id == 19: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[:-1]): variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubit, control=qubits[ind+1]) count += 1 variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubits[-1], control=qubits[0]) count += 1 return circuit
18,425
45.530303
172
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.2/grad_hacked.py
from tequila.circuit.compiler import CircuitCompiler from tequila.objective.objective import Objective, ExpectationValueImpl, Variable, \ assign_variable, identity, FixedVariable from tequila import TequilaException from tequila.objective import QTensor from tequila.simulators.simulator_api import compile import typing from numpy import vectorize from tequila.autograd_imports import jax, __AUTOGRAD__BACKEND__ def grad(objective: typing.Union[Objective, QTensor], variable: Variable = None, no_compile=False, *args, **kwargs): ''' wrapper function for getting the gradients of Objectives,ExpectationValues, Unitaries (including single gates), and Transforms. :param obj (QCircuit,ParametrizedGateImpl,Objective,ExpectationValue,Transform,Variable): structure to be differentiated :param variables (list of Variable): parameter with respect to which obj should be differentiated. default None: total gradient. return: dictionary of Objectives, if called on gate, circuit, exp.value, or objective; if Variable or Transform, returns number. ''' if variable is None: # None means that all components are created variables = objective.extract_variables() result = {} if len(variables) == 0: raise TequilaException("Error in gradient: Objective has no variables") for k in variables: assert (k is not None) result[k] = grad(objective, k, no_compile=no_compile) return result else: variable = assign_variable(variable) if isinstance(objective, QTensor): f = lambda x: grad(objective=x, variable=variable, *args, **kwargs) ff = vectorize(f) return ff(objective) if variable not in objective.extract_variables(): return Objective() if no_compile: compiled = objective else: compiler = CircuitCompiler(multitarget=True, trotterized=True, hadamard_power=True, power=True, controlled_phase=True, controlled_rotation=True, gradient_mode=True) compiled = compiler(objective, variables=[variable]) if variable not in compiled.extract_variables(): raise TequilaException("Error in taking gradient. Objective does not depend on variable {} ".format(variable)) if isinstance(objective, ExpectationValueImpl): return __grad_expectationvalue(E=objective, variable=variable) elif objective.is_expectationvalue(): return __grad_expectationvalue(E=compiled.args[-1], variable=variable) elif isinstance(compiled, Objective) or (hasattr(compiled, "args") and hasattr(compiled, "transformation")): return __grad_objective(objective=compiled, variable=variable) else: raise TequilaException("Gradient not implemented for other types than ExpectationValue and Objective.") def __grad_objective(objective: Objective, variable: Variable): args = objective.args transformation = objective.transformation dO = None processed_expectationvalues = {} for i, arg in enumerate(args): if __AUTOGRAD__BACKEND__ == "jax": df = jax.grad(transformation, argnums=i, holomorphic=True) elif __AUTOGRAD__BACKEND__ == "autograd": df = jax.grad(transformation, argnum=i) else: raise TequilaException("Can't differentiate without autograd or jax") # We can detect one simple case where the outer derivative is const=1 if transformation is None or transformation == identity: outer = 1.0 else: outer = Objective(args=args, transformation=df) if hasattr(arg, "U"): # save redundancies if arg in processed_expectationvalues: inner = processed_expectationvalues[arg] else: inner = __grad_inner(arg=arg, variable=variable) processed_expectationvalues[arg] = inner else: # this means this inner derivative is purely variable dependent inner = __grad_inner(arg=arg, variable=variable) if inner == 0.0: # don't pile up zero expectationvalues continue if dO is None: dO = outer * inner else: dO = dO + outer * inner if dO is None: raise TequilaException("caught None in __grad_objective") return dO # def __grad_vector_objective(objective: Objective, variable: Variable): # argsets = objective.argsets # transformations = objective._transformations # outputs = [] # for pos in range(len(objective)): # args = argsets[pos] # transformation = transformations[pos] # dO = None # # processed_expectationvalues = {} # for i, arg in enumerate(args): # if __AUTOGRAD__BACKEND__ == "jax": # df = jax.grad(transformation, argnums=i) # elif __AUTOGRAD__BACKEND__ == "autograd": # df = jax.grad(transformation, argnum=i) # else: # raise TequilaException("Can't differentiate without autograd or jax") # # # We can detect one simple case where the outer derivative is const=1 # if transformation is None or transformation == identity: # outer = 1.0 # else: # outer = Objective(args=args, transformation=df) # # if hasattr(arg, "U"): # # save redundancies # if arg in processed_expectationvalues: # inner = processed_expectationvalues[arg] # else: # inner = __grad_inner(arg=arg, variable=variable) # processed_expectationvalues[arg] = inner # else: # # this means this inner derivative is purely variable dependent # inner = __grad_inner(arg=arg, variable=variable) # # if inner == 0.0: # # don't pile up zero expectationvalues # continue # # if dO is None: # dO = outer * inner # else: # dO = dO + outer * inner # # if dO is None: # dO = Objective() # outputs.append(dO) # if len(outputs) == 1: # return outputs[0] # return outputs def __grad_inner(arg, variable): ''' a modified loop over __grad_objective, which gets derivatives all the way down to variables, return 1 or 0 when a variable is (isnt) identical to var. :param arg: a transform or variable object, to be differentiated :param variable: the Variable with respect to which par should be differentiated. :ivar var: the string representation of variable ''' assert (isinstance(variable, Variable)) if isinstance(arg, Variable): if arg == variable: return 1.0 else: return 0.0 elif isinstance(arg, FixedVariable): return 0.0 elif isinstance(arg, ExpectationValueImpl): return __grad_expectationvalue(arg, variable=variable) elif hasattr(arg, "abstract_expectationvalue"): E = arg.abstract_expectationvalue dE = __grad_expectationvalue(E, variable=variable) return compile(dE, **arg._input_args) else: return __grad_objective(objective=arg, variable=variable) def __grad_expectationvalue(E: ExpectationValueImpl, variable: Variable): ''' implements the analytic partial derivative of a unitary as it would appear in an expectation value. See the paper. :param unitary: the unitary whose gradient should be obtained :param variables (list, dict, str): the variables with respect to which differentiation should be performed. :return: vector (as dict) of dU/dpi as Objective (without hamiltonian) ''' hamiltonian = E.H unitary = E.U if not (unitary.verify()): raise TequilaException("error in grad_expectationvalue unitary is {}".format(unitary)) # fast return if possible if variable not in unitary.extract_variables(): return 0.0 param_gates = unitary._parameter_map[variable] dO = Objective() for idx_g in param_gates: idx, g = idx_g dOinc = __grad_shift_rule(unitary, g, idx, variable, hamiltonian) dO += dOinc assert dO is not None return dO def __grad_shift_rule(unitary, g, i, variable, hamiltonian): ''' function for getting the gradients of directly differentiable gates. Expects precompiled circuits. :param unitary: QCircuit: the QCircuit object containing the gate to be differentiated :param g: a parametrized: the gate being differentiated :param i: Int: the position in unitary at which g appears :param variable: Variable or String: the variable with respect to which gate g is being differentiated :param hamiltonian: the hamiltonian with respect to which unitary is to be measured, in the case that unitary is contained within an ExpectationValue :return: an Objective, whose calculation yields the gradient of g w.r.t variable ''' # possibility for overwride in custom gate construction if hasattr(g, "shifted_gates"): inner_grad = __grad_inner(g.parameter, variable) shifted = g.shifted_gates() dOinc = Objective() for x in shifted: w, g = x Ux = unitary.replace_gates(positions=[i], circuits=[g]) wx = w * inner_grad Ex = Objective.ExpectationValue(U=Ux, H=hamiltonian) dOinc += wx * Ex return dOinc else: raise TequilaException('No shift found for gate {}\nWas the compiler called?'.format(g))
9,886
38.548
132
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.2/vqe_utils.py
import tequila as tq import numpy as np from hacked_openfermion_qubit_operator import ParamQubitHamiltonian from openfermion import QubitOperator from HEA import * def get_ansatz_circuit(ansatz_type, geometry, basis_set=None, trotter_steps = 1, name=None, circuit_id=None,num_layers=1): """ This function generates the ansatz for the molecule and the Hamiltonian param: ansatz_type (str) -> the type of the ansatz ('UCCSD, UpCCGSD, SPA, HEA') param: geometry (str) -> the geometry of the molecule param: basis_set (str) -> the basis set for wchich the ansatz has to generated param: trotter_steps (int) -> the number of trotter step to be used in the trotter decomposition param: name (str) -> the name for the madness molecule param: circuit_id (int) -> the type of hardware efficient ansatz param: num_layers (int) -> the number of layers of the HEA e.g.: input: ansatz_type -> "UCCSD" geometry -> "H 0.0 0.0 0.0\nH 0.0 0.0 0.714" basis_set -> 'sto-3g' trotter_steps -> 1 name -> None circuit_id -> None num_layers -> 1 returns: ucc_ansatz (tq.QCircuit()) -> a circuit printed below: circuit: FermionicExcitation(target=(0, 1, 2, 3), control=(), parameter=Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = []) FermionicExcitation(target=(0, 1, 2, 3), control=(), parameter=Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = []) Hamiltonian (tq.QubitHamiltonian()) -> -0.0621+0.1755Z(0)+0.1755Z(1)-0.2358Z(2)-0.2358Z(3)+0.1699Z(0)Z(1) +0.0449Y(0)X(1)X(2)Y(3)-0.0449Y(0)Y(1)X(2)X(3)-0.0449X(0)X(1)Y(2)Y(3) +0.0449X(0)Y(1)Y(2)X(3)+0.1221Z(0)Z(2)+0.1671Z(0)Z(3)+0.1671Z(1)Z(2) +0.1221Z(1)Z(3)+0.1756Z(2)Z(3) fci_ener (float) -> """ ham = tq.QubitHamiltonian() fci_ener = 0.0 ansatz = tq.QCircuit() if ansatz_type == "UCCSD": molecule = tq.Molecule(geometry=geometry, basis_set=basis_set) ansatz = molecule.make_uccsd_ansatz(trotter_steps) ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy(method="fci") elif ansatz_type == "UCCS": molecule = tq.Molecule(geometry=geometry, basis_set=basis_set, backend='psi4') ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy("fci") indices = molecule.make_upccgsd_indices(key='UCCS') print("indices are:", indices) ansatz = molecule.make_upccgsd_layer(indices=indices, include_singles=True, include_doubles=False) elif ansatz_type == "UpCCGSD": molecule = tq.Molecule(name=name, geometry=geometry, n_pno=None) ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy("fci") ansatz = molecule.make_upccgsd_ansatz() elif ansatz_type == "SPA": molecule = tq.Molecule(name=name, geometry=geometry, n_pno=None) ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy("fci") ansatz = molecule.make_upccgsd_ansatz(name="SPA") elif ansatz_type == "HEA": molecule = tq.Molecule(geometry=geometry, basis_set=basis_set) ham = molecule.make_hamiltonian() fci_ener = molecule.compute_energy(method="fci") ansatz = generate_HEA(molecule.n_orbitals * 2, circuit_id) else: raise Exception("not implemented any other ansatz, please choose from 'UCCSD, UpCCGSD, SPA, HEA'") return ansatz, ham, fci_ener def get_generator_for_gates(unitary): """ This function takes a unitary gate and returns the generator of the the gate so that it can be padded to the Hamiltonian param: unitary (tq.QGateImpl()) -> the unitary circuit element that has to be converted to a paulistring e.g.: input: unitary -> a FermionicGateImpl object as the one printed below FermionicExcitation(target=(0, 1, 2, 3), control=(), parameter=Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = []) returns: parameter (tq.Variable()) -> (1, 0, 1, 0) generator (tq.QubitHamiltonian()) -> -0.1250Y(0)Y(1)Y(2)X(3)+0.1250Y(0)X(1)Y(2)Y(3) +0.1250X(0)X(1)Y(2)X(3)+0.1250X(0)Y(1)Y(2)Y(3) -0.1250Y(0)X(1)X(2)X(3)-0.1250Y(0)Y(1)X(2)Y(3) -0.1250X(0)Y(1)X(2)X(3)+0.1250X(0)X(1)X(2)Y(3) null_proj (tq.QubitHamiltonian()) -> -0.1250Z(0)Z(1)+0.1250Z(1)Z(3)+0.1250Z(0)Z(3) +0.1250Z(1)Z(2)+0.1250Z(0)Z(2)-0.1250Z(2)Z(3) -0.1250Z(0)Z(1)Z(2)Z(3) """ try: parameter = None generator = None null_proj = None if isinstance(unitary, tq.quantumchemistry.qc_base.FermionicGateImpl): parameter = unitary.extract_variables() generator = unitary.generator null_proj = unitary.p0 else: #getting parameter if unitary.is_parametrized(): parameter = unitary.extract_variables() else: parameter = [None] try: generator = unitary.make_generator(include_controls=True) except: generator = unitary.generator() """if len(parameter) == 0: parameter = [tq.objective.objective.assign_variable(unitary.parameter)]""" return parameter[0], generator, null_proj except Exception as e: print("An Exception happened, details :",e) pass def fold_unitary_into_hamiltonian(unitary, Hamiltonian): """ This function return a list of the resulting Hamiltonian terms after folding the paulistring correspondig to the unitary into the Hamiltonian param: unitary (tq.QGateImpl()) -> the unitary to be folded into the Hamiltonian param: Hamiltonian (ParamQubitHamiltonian()) -> the Hamiltonian of the system e.g.: input: unitary -> a FermionicGateImpl object as the one printed below FermionicExcitation(target=(0, 1, 2, 3), control=(), parameter=Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = []) Hamiltonian -> -0.06214952615456104 [] + -0.044941923860490916 [X0 X1 Y2 Y3] + 0.044941923860490916 [X0 Y1 Y2 X3] + 0.044941923860490916 [Y0 X1 X2 Y3] + -0.044941923860490916 [Y0 Y1 X2 X3] + 0.17547360045040505 [Z0] + 0.16992958569230643 [Z0 Z1] + 0.12212314332112947 [Z0 Z2] + 0.1670650671816204 [Z0 Z3] + 0.17547360045040508 [Z1] + 0.1670650671816204 [Z1 Z2] + 0.12212314332112947 [Z1 Z3] + -0.23578915712819945 [Z2] + 0.17561918557144712 [Z2 Z3] + -0.23578915712819945 [Z3] returns: folded_hamiltonian (ParamQubitHamiltonian()) -> Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [X0 X1 X2 X3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [X0 X1 Y2 Y3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [X0 Y1 X2 Y3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [X0 Y1 Y2 X3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Y0 X1 X2 Y3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Y0 X1 Y2 X3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Y0 Y1 X2 X3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Y0 Y1 Y2 Y3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z1] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z1 Z2] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z1 Z2 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z1 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z2] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z2 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z0 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z1] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z1 Z2] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z1 Z2 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z1 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z2] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z2 Z3] + Objective with 0 unique expectation values total measurements = 0 variables = [(1, 0, 1, 0)] types = [] [Z3] """ folded_hamiltonian = ParamQubitHamiltonian() if isinstance(unitary, tq.circuit._gates_impl.DifferentiableGateImpl) and not isinstance(unitary, tq.circuit._gates_impl.PhaseGateImpl): variable, generator, null_proj = get_generator_for_gates(unitary) # print(generator) # print(null_proj) #converting into ParamQubitHamiltonian() c_generator = convert_tq_QH_to_PQH(generator) """c_null_proj = convert_tq_QH_to_PQH(null_proj) print(variable) prod1 = (null_proj*ham*generator - generator*ham*null_proj) print(prod1) #print((Hamiltonian*c_generator)) prod2 = convert_PQH_to_tq_QH(c_null_proj*Hamiltonian*c_generator - c_generator*Hamiltonian*c_null_proj)({var:0.1 for var in variable.extract_variables()}) print(prod2) assert prod1 ==prod2 raise Exception("testing")""" #print("starting", flush=True) #handling the parameterize gates if variable is not None: #print("folding generator") # adding the term: cos^2(\theta)*H temp_ham = ParamQubitHamiltonian().identity() temp_ham *= Hamiltonian temp_ham *= (variable.apply(tq.numpy.cos)**2) #print(convert_PQH_to_tq_QH(temp_ham)({var:1. for var in variable.extract_variables()})) folded_hamiltonian += temp_ham #print("step1 done", flush=True) # adding the term: sin^2(\theta)*G*H*G temp_ham = ParamQubitHamiltonian().identity() temp_ham *= c_generator temp_ham *= Hamiltonian temp_ham *= c_generator temp_ham *= (variable.apply(tq.numpy.sin)**2) #print(convert_PQH_to_tq_QH(temp_ham)({var:1. for var in variable.extract_variables()})) folded_hamiltonian += temp_ham #print("step2 done", flush=True) # adding the term: i*cos^2(\theta)8sin^2(\theta)*(G*H -H*G) temp_ham1 = ParamQubitHamiltonian().identity() temp_ham1 *= c_generator temp_ham1 *= Hamiltonian temp_ham2 = ParamQubitHamiltonian().identity() temp_ham2 *= Hamiltonian temp_ham2 *= c_generator temp_ham = temp_ham1 - temp_ham2 temp_ham *= 1.0j temp_ham *= variable.apply(tq.numpy.sin) * variable.apply(tq.numpy.cos) #print(convert_PQH_to_tq_QH(temp_ham)({var:1. for var in variable.extract_variables()})) folded_hamiltonian += temp_ham #print("step3 done", flush=True) #handling the non-paramterized gates else: raise Exception("This function is not implemented yet") # adding the term: G*H*G folded_hamiltonian += c_generator*Hamiltonian*c_generator #print("Halfway there", flush=True) #handle the FermionicGateImpl gates if null_proj is not None: print("folding null projector") c_null_proj = convert_tq_QH_to_PQH(null_proj) #print("step4 done", flush=True) # adding the term: (1-cos(\theta))^2*P0*H*P0 temp_ham = ParamQubitHamiltonian().identity() temp_ham *= c_null_proj temp_ham *= Hamiltonian temp_ham *= c_null_proj temp_ham *= ((1-variable.apply(tq.numpy.cos))**2) folded_hamiltonian += temp_ham #print("step5 done", flush=True) # adding the term: 2*cos(\theta)*(1-cos(\theta))*(P0*H +H*P0) temp_ham1 = ParamQubitHamiltonian().identity() temp_ham1 *= c_null_proj temp_ham1 *= Hamiltonian temp_ham2 = ParamQubitHamiltonian().identity() temp_ham2 *= Hamiltonian temp_ham2 *= c_null_proj temp_ham = temp_ham1 + temp_ham2 temp_ham *= (variable.apply(tq.numpy.cos)*(1-variable.apply(tq.numpy.cos))) folded_hamiltonian += temp_ham #print("step6 done", flush=True) # adding the term: i*sin(\theta)*(1-cos(\theta))*(G*H*P0 - P0*H*G) temp_ham1 = ParamQubitHamiltonian().identity() temp_ham1 *= c_generator temp_ham1 *= Hamiltonian temp_ham1 *= c_null_proj temp_ham2 = ParamQubitHamiltonian().identity() temp_ham2 *= c_null_proj temp_ham2 *= Hamiltonian temp_ham2 *= c_generator temp_ham = temp_ham1 - temp_ham2 temp_ham *= 1.0j temp_ham *= (variable.apply(tq.numpy.sin)*(1-variable.apply(tq.numpy.cos))) folded_hamiltonian += temp_ham #print("step7 done", flush=True) elif isinstance(unitary, tq.circuit._gates_impl.PhaseGateImpl): if np.isclose(unitary.parameter, np.pi/2.0): return Hamiltonian._clifford_simplify_s(unitary.qubits[0]) elif np.isclose(unitary.parameter, -1.*np.pi/2.0): return Hamiltonian._clifford_simplify_s_dag(unitary.qubits[0]) else: raise Exception("Only DifferentiableGateImpl, PhaseGateImpl(S), Pauligate(X,Y,Z), Controlled(X,Y,Z) and Hadamrd(H) implemented yet") elif isinstance(unitary, tq.circuit._gates_impl.QGateImpl): if unitary.is_controlled(): if unitary.name == "X": return Hamiltonian._clifford_simplify_control_g("X", unitary.control[0], unitary.target[0]) elif unitary.name == "Y": return Hamiltonian._clifford_simplify_control_g("Y", unitary.control[0], unitary.target[0]) elif unitary.name == "Z": return Hamiltonian._clifford_simplify_control_g("Z", unitary.control[0], unitary.target[0]) else: raise Exception("Only DifferentiableGateImpl, PhaseGateImpl(S), Pauligate(X,Y,Z), Controlled(X,Y,Z) and Hadamrd(H) implemented yet") else: if unitary.name == "X": gate = convert_tq_QH_to_PQH(tq.paulis.X(unitary.qubits[0])) return gate*Hamiltonian*gate elif unitary.name == "Y": gate = convert_tq_QH_to_PQH(tq.paulis.Y(unitary.qubits[0])) return gate*Hamiltonian*gate elif unitary.name == "Z": gate = convert_tq_QH_to_PQH(tq.paulis.Z(unitary.qubits[0])) return gate*Hamiltonian*gate elif unitary.name == "H": return Hamiltonian._clifford_simplify_h(unitary.qubits[0]) else: raise Exception("Only DifferentiableGateImpl, PhaseGateImpl(S), Pauligate(X,Y,Z), Controlled(X,Y,Z) and Hadamrd(H) implemented yet") else: raise Exception("Only DifferentiableGateImpl, PhaseGateImpl(S), Pauligate(X,Y,Z), Controlled(X,Y,Z) and Hadamrd(H) implemented yet") return folded_hamiltonian def convert_tq_QH_to_PQH(Hamiltonian): """ This function takes the tequila QubitHamiltonian object and converts into a ParamQubitHamiltonian object. param: Hamiltonian (tq.QubitHamiltonian()) -> the Hamiltonian to be converted e.g: input: Hamiltonian -> -0.0621+0.1755Z(0)+0.1755Z(1)-0.2358Z(2)-0.2358Z(3)+0.1699Z(0)Z(1) +0.0449Y(0)X(1)X(2)Y(3)-0.0449Y(0)Y(1)X(2)X(3)-0.0449X(0)X(1)Y(2)Y(3) +0.0449X(0)Y(1)Y(2)X(3)+0.1221Z(0)Z(2)+0.1671Z(0)Z(3)+0.1671Z(1)Z(2) +0.1221Z(1)Z(3)+0.1756Z(2)Z(3) returns: param_hamiltonian (ParamQubitHamiltonian()) -> -0.06214952615456104 [] + -0.044941923860490916 [X0 X1 Y2 Y3] + 0.044941923860490916 [X0 Y1 Y2 X3] + 0.044941923860490916 [Y0 X1 X2 Y3] + -0.044941923860490916 [Y0 Y1 X2 X3] + 0.17547360045040505 [Z0] + 0.16992958569230643 [Z0 Z1] + 0.12212314332112947 [Z0 Z2] + 0.1670650671816204 [Z0 Z3] + 0.17547360045040508 [Z1] + 0.1670650671816204 [Z1 Z2] + 0.12212314332112947 [Z1 Z3] + -0.23578915712819945 [Z2] + 0.17561918557144712 [Z2 Z3] + -0.23578915712819945 [Z3] """ param_hamiltonian = ParamQubitHamiltonian() Hamiltonian = Hamiltonian.to_openfermion() for term in Hamiltonian.terms: param_hamiltonian += ParamQubitHamiltonian(term = term, coefficient = Hamiltonian.terms[term]) return param_hamiltonian class convert_PQH_to_tq_QH: def __init__(self, Hamiltonian): self.param_hamiltonian = Hamiltonian def __call__(self,variables=None): """ This function takes the ParamQubitHamiltonian object and converts into a tequila QubitHamiltonian object. param: param_hamiltonian (ParamQubitHamiltonian()) -> the Hamiltonian to be converted param: variables (dict) -> a dictionary with the values of the variables in the Hamiltonian coefficient e.g: input: param_hamiltonian -> a [Y0 X2 Z3] + b [Z0 X2 Z3] variables -> {"a":1,"b":2} returns: Hamiltonian (tq.QubitHamiltonian()) -> +1.0000Y(0)X(2)Z(3)+2.0000Z(0)X(2)Z(3) """ Hamiltonian = tq.QubitHamiltonian() for term in self.param_hamiltonian.terms: val = self.param_hamiltonian.terms[term]# + self.param_hamiltonian.imag_terms[term]*1.0j if isinstance(val, tq.Variable) or isinstance(val, tq.objective.objective.Objective): try: for key in variables.keys(): variables[key] = variables[key] #print(variables) val = val(variables) #print(val) except Exception as e: print(e) raise Exception("You forgot to pass the dictionary with the values of the variables") Hamiltonian += tq.QubitHamiltonian(QubitOperator(term=term, coefficient=val)) return Hamiltonian def _construct_derivatives(self, variables=None): """ """ derivatives = {} variable_names = [] for term in self.param_hamiltonian.terms: val = self.param_hamiltonian.terms[term]# + self.param_hamiltonian.imag_terms[term]*1.0j #print(val) if isinstance(val, tq.Variable) or isinstance(val, tq.objective.objective.Objective): variable = val.extract_variables() for var in list(variable): from grad_hacked import grad derivative = ParamQubitHamiltonian(term = term, coefficient = grad(val, var)) if var not in variable_names: variable_names.append(var) if var not in list(derivatives.keys()): derivatives[var] = derivative else: derivatives[var] += derivative return variable_names, derivatives def get_geometry(name, b_l): """ This is utility fucntion that generates tehe geometry string of a Molecule param: name (str) -> name of the molecule param: b_l (float) -> the bond length of the molecule e.g.: input: name -> "H2" b_l -> 0.714 returns: geo_str (str) -> "H 0.0 0.0 0.0\nH 0.0 0.0 0.714" """ geo_str = None if name == "LiH": geo_str = "H 0.0 0.0 0.0\nLi 0.0 0.0 {0}".format(b_l) elif name == "H2": geo_str = "H 0.0 0.0 0.0\nH 0.0 0.0 {0}".format(b_l) elif name == "BeH2": geo_str = "H 0.0 0.0 {0}\nH 0.0 0.0 {1}\nBe 0.0 0.0 0.0".format(b_l,-1*b_l) elif name == "N2": geo_str = "N 0.0 0.0 0.0\nN 0.0 0.0 {0}".format(b_l) elif name == "H4": geo_str = "H 0.0 0.0 0.0\nH 0.0 0.0 {0}\nH 0.0 0.0 {1}\nH 0.0 0.0 {2}".format(b_l,-1*b_l,2*b_l) return geo_str
27,934
51.807183
162
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.2/hacked_openfermion_symbolic_operator.py
import abc import copy import itertools import re import warnings import sympy import tequila as tq from tequila.objective.objective import Objective, Variable from openfermion.config import EQ_TOLERANCE COEFFICIENT_TYPES = (int, float, complex, sympy.Expr, Variable, Objective) class SymbolicOperator(metaclass=abc.ABCMeta): """Base class for FermionOperator and QubitOperator. A SymbolicOperator stores an object which represents a weighted sum of terms; each term is a product of individual factors of the form (`index`, `action`), where `index` is a nonnegative integer and the possible values for `action` are determined by the subclass. For instance, for the subclass FermionOperator, `action` can be 1 or 0, indicating raising or lowering, and for QubitOperator, `action` is from the set {'X', 'Y', 'Z'}. The coefficients of the terms are stored in a dictionary whose keys are the terms. SymbolicOperators of the same type can be added or multiplied together. Note: Adding SymbolicOperators is faster using += (as this is done by in-place addition). Specifying the coefficient during initialization is faster than multiplying a SymbolicOperator with a scalar. Attributes: actions (tuple): A tuple of objects representing the possible actions. e.g. for FermionOperator, this is (1, 0). action_strings (tuple): A tuple of string representations of actions. These should be in one-to-one correspondence with actions and listed in the same order. e.g. for FermionOperator, this is ('^', ''). action_before_index (bool): A boolean indicating whether in string representations, the action should come before the index. different_indices_commute (bool): A boolean indicating whether factors acting on different indices commute. terms (dict): **key** (tuple of tuples): A dictionary storing the coefficients of the terms in the operator. The keys are the terms. A term is a product of individual factors; each factor is represented by a tuple of the form (`index`, `action`), and these tuples are collected into a larger tuple which represents the term as the product of its factors. """ @staticmethod def _issmall(val, tol=EQ_TOLERANCE): '''Checks whether a value is near-zero Parses the allowed coefficients above for near-zero tests. Args: val (COEFFICIENT_TYPES) -- the value to be tested tol (float) -- tolerance for inequality ''' if isinstance(val, sympy.Expr): if sympy.simplify(abs(val) < tol) == True: return True return False if isinstance(val, tq.Variable) or isinstance(val, tq.objective.objective.Objective): return False if abs(val) < tol: return True return False @abc.abstractproperty def actions(self): """The allowed actions. Returns a tuple of objects representing the possible actions. """ pass @abc.abstractproperty def action_strings(self): """The string representations of the allowed actions. Returns a tuple containing string representations of the possible actions, in the same order as the `actions` property. """ pass @abc.abstractproperty def action_before_index(self): """Whether action comes before index in string representations. Example: For QubitOperator, the actions are ('X', 'Y', 'Z') and the string representations look something like 'X0 Z2 Y3'. So the action comes before the index, and this function should return True. For FermionOperator, the string representations look like '0^ 1 2^ 3'. The action comes after the index, so this function should return False. """ pass @abc.abstractproperty def different_indices_commute(self): """Whether factors acting on different indices commute.""" pass __hash__ = None def __init__(self, term=None, coefficient=1.): if not isinstance(coefficient, COEFFICIENT_TYPES): raise ValueError('Coefficient must be a numeric type.') # Initialize the terms dictionary self.terms = {} # Detect if the input is the string representation of a sum of terms; # if so, initialization needs to be handled differently if isinstance(term, str) and '[' in term: self._long_string_init(term, coefficient) return # Zero operator: leave the terms dictionary empty if term is None: return # Parse the term # Sequence input if isinstance(term, (list, tuple)): term = self._parse_sequence(term) # String input elif isinstance(term, str): term = self._parse_string(term) # Invalid input type else: raise ValueError('term specified incorrectly.') # Simplify the term coefficient, term = self._simplify(term, coefficient=coefficient) # Add the term to the dictionary self.terms[term] = coefficient def _long_string_init(self, long_string, coefficient): r""" Initialization from a long string representation. e.g. For FermionOperator: '1.5 [2^ 3] + 1.4 [3^ 0]' """ pattern = r'(.*?)\[(.*?)\]' # regex for a term for match in re.findall(pattern, long_string, flags=re.DOTALL): # Determine the coefficient for this term coef_string = re.sub(r"\s+", "", match[0]) if coef_string and coef_string[0] == '+': coef_string = coef_string[1:].strip() if coef_string == '': coef = 1.0 elif coef_string == '-': coef = -1.0 else: try: if 'j' in coef_string: if coef_string[0] == '-': coef = -complex(coef_string[1:]) else: coef = complex(coef_string) else: coef = float(coef_string) except ValueError: raise ValueError( 'Invalid coefficient {}.'.format(coef_string)) coef *= coefficient # Parse the term, simpify it and add to the dict term = self._parse_string(match[1]) coef, term = self._simplify(term, coefficient=coef) if term not in self.terms: self.terms[term] = coef else: self.terms[term] += coef def _validate_factor(self, factor): """Check that a factor of a term is valid.""" if len(factor) != 2: raise ValueError('Invalid factor {}.'.format(factor)) index, action = factor if action not in self.actions: raise ValueError('Invalid action in factor {}. ' 'Valid actions are: {}'.format( factor, self.actions)) if not isinstance(index, int) or index < 0: raise ValueError('Invalid index in factor {}. ' 'The index should be a non-negative ' 'integer.'.format(factor)) def _simplify(self, term, coefficient=1.0): """Simplifies a term.""" if self.different_indices_commute: term = sorted(term, key=lambda factor: factor[0]) return coefficient, tuple(term) def _parse_sequence(self, term): """Parse a term given as a sequence type (i.e., list, tuple, etc.). e.g. For QubitOperator: [('X', 2), ('Y', 0), ('Z', 3)] -> (('Y', 0), ('X', 2), ('Z', 3)) """ if not term: # Empty sequence return () elif isinstance(term[0], int): # Single factor self._validate_factor(term) return (tuple(term),) else: # Check that all factors in the term are valid for factor in term: self._validate_factor(factor) # Return a tuple return tuple(term) def _parse_string(self, term): """Parse a term given as a string. e.g. For FermionOperator: "2^ 3" -> ((2, 1), (3, 0)) """ factors = term.split() # Convert the string representations of the factors to tuples processed_term = [] for factor in factors: # Get the index and action string if self.action_before_index: # The index is at the end of the string; find where it starts. if not factor[-1].isdigit(): raise ValueError('Invalid factor {}.'.format(factor)) index_start = len(factor) - 1 while index_start > 0 and factor[index_start - 1].isdigit(): index_start -= 1 if factor[index_start - 1] == '-': raise ValueError('Invalid index in factor {}. ' 'The index should be a non-negative ' 'integer.'.format(factor)) index = int(factor[index_start:]) action_string = factor[:index_start] else: # The index is at the beginning of the string; find where # it ends if factor[0] == '-': raise ValueError('Invalid index in factor {}. ' 'The index should be a non-negative ' 'integer.'.format(factor)) if not factor[0].isdigit(): raise ValueError('Invalid factor {}.'.format(factor)) index_end = 1 while (index_end <= len(factor) - 1 and factor[index_end].isdigit()): index_end += 1 index = int(factor[:index_end]) action_string = factor[index_end:] # Convert the action string to an action if action_string in self.action_strings: action = self.actions[self.action_strings.index(action_string)] else: raise ValueError('Invalid action in factor {}. ' 'Valid actions are: {}'.format( factor, self.action_strings)) # Add the factor to the list as a tuple processed_term.append((index, action)) # Return a tuple return tuple(processed_term) @property def constant(self): """The value of the constant term.""" return self.terms.get((), 0.0) @constant.setter def constant(self, value): self.terms[()] = value @classmethod def zero(cls): """ Returns: additive_identity (SymbolicOperator): A symbolic operator o with the property that o+x = x+o = x for all operators x of the same class. """ return cls(term=None) @classmethod def identity(cls): """ Returns: multiplicative_identity (SymbolicOperator): A symbolic operator u with the property that u*x = x*u = x for all operators x of the same class. """ return cls(term=()) def __str__(self): """Return an easy-to-read string representation.""" if not self.terms: return '0' string_rep = '' for term, coeff in sorted(self.terms.items()): if self._issmall(coeff): continue tmp_string = '{} ['.format(coeff) for factor in term: index, action = factor action_string = self.action_strings[self.actions.index(action)] if self.action_before_index: tmp_string += '{}{} '.format(action_string, index) else: tmp_string += '{}{} '.format(index, action_string) string_rep += '{}] +\n'.format(tmp_string.strip()) return string_rep[:-3] def __repr__(self): return str(self) def __imul__(self, multiplier): """In-place multiply (*=) with scalar or operator of the same type. Default implementation is to multiply coefficients and concatenate terms. Args: multiplier(complex float, or SymbolicOperator): multiplier Returns: product (SymbolicOperator): Mutated self. """ # Handle scalars. if isinstance(multiplier, COEFFICIENT_TYPES): for term in self.terms: self.terms[term] *= multiplier return self # Handle operator of the same type elif isinstance(multiplier, self.__class__): result_terms = dict() for left_term in self.terms: for right_term in multiplier.terms: left_coefficient = self.terms[left_term] right_coefficient = multiplier.terms[right_term] new_coefficient = left_coefficient * right_coefficient new_term = left_term + right_term new_coefficient, new_term = self._simplify( new_term, coefficient=new_coefficient) # Update result dict. if new_term in result_terms: result_terms[new_term] += new_coefficient else: result_terms[new_term] = new_coefficient self.terms = result_terms return self # Invalid multiplier type else: raise TypeError('Cannot multiply {} with {}'.format( self.__class__.__name__, multiplier.__class__.__name__)) def __mul__(self, multiplier): """Return self * multiplier for a scalar, or a SymbolicOperator. Args: multiplier: A scalar, or a SymbolicOperator. Returns: product (SymbolicOperator) Raises: TypeError: Invalid type cannot be multiply with SymbolicOperator. """ if isinstance(multiplier, COEFFICIENT_TYPES + (type(self),)): product = copy.deepcopy(self) product *= multiplier return product else: raise TypeError('Object of invalid type cannot multiply with ' + type(self) + '.') def __iadd__(self, addend): """In-place method for += addition of SymbolicOperator. Args: addend (SymbolicOperator, or scalar): The operator to add. If scalar, adds to the constant term Returns: sum (SymbolicOperator): Mutated self. Raises: TypeError: Cannot add invalid type. """ if isinstance(addend, type(self)): for term in addend.terms: self.terms[term] = (self.terms.get(term, 0.0) + addend.terms[term]) if self._issmall(self.terms[term]): del self.terms[term] elif isinstance(addend, COEFFICIENT_TYPES): self.constant += addend else: raise TypeError('Cannot add invalid type to {}.'.format(type(self))) return self def __add__(self, addend): """ Args: addend (SymbolicOperator): The operator to add. Returns: sum (SymbolicOperator) """ summand = copy.deepcopy(self) summand += addend return summand def __radd__(self, addend): """ Args: addend (SymbolicOperator): The operator to add. Returns: sum (SymbolicOperator) """ return self + addend def __isub__(self, subtrahend): """In-place method for -= subtraction of SymbolicOperator. Args: subtrahend (A SymbolicOperator, or scalar): The operator to subtract if scalar, subtracts from the constant term. Returns: difference (SymbolicOperator): Mutated self. Raises: TypeError: Cannot subtract invalid type. """ if isinstance(subtrahend, type(self)): for term in subtrahend.terms: self.terms[term] = (self.terms.get(term, 0.0) - subtrahend.terms[term]) if self._issmall(self.terms[term]): del self.terms[term] elif isinstance(subtrahend, COEFFICIENT_TYPES): self.constant -= subtrahend else: raise TypeError('Cannot subtract invalid type from {}.'.format( type(self))) return self def __sub__(self, subtrahend): """ Args: subtrahend (SymbolicOperator): The operator to subtract. Returns: difference (SymbolicOperator) """ minuend = copy.deepcopy(self) minuend -= subtrahend return minuend def __rsub__(self, subtrahend): """ Args: subtrahend (SymbolicOperator): The operator to subtract. Returns: difference (SymbolicOperator) """ return -1 * self + subtrahend def __rmul__(self, multiplier): """ Return multiplier * self for a scalar. We only define __rmul__ for scalars because the left multiply exist for SymbolicOperator and left multiply is also queried as the default behavior. Args: multiplier: A scalar to multiply by. Returns: product: A new instance of SymbolicOperator. Raises: TypeError: Object of invalid type cannot multiply SymbolicOperator. """ if not isinstance(multiplier, COEFFICIENT_TYPES): raise TypeError('Object of invalid type cannot multiply with ' + type(self) + '.') return self * multiplier def __truediv__(self, divisor): """ Return self / divisor for a scalar. Note: This is always floating point division. Args: divisor: A scalar to divide by. Returns: A new instance of SymbolicOperator. Raises: TypeError: Cannot divide local operator by non-scalar type. """ if not isinstance(divisor, COEFFICIENT_TYPES): raise TypeError('Cannot divide ' + type(self) + ' by non-scalar type.') return self * (1.0 / divisor) def __div__(self, divisor): """ For compatibility with Python 2. """ return self.__truediv__(divisor) def __itruediv__(self, divisor): if not isinstance(divisor, COEFFICIENT_TYPES): raise TypeError('Cannot divide ' + type(self) + ' by non-scalar type.') self *= (1.0 / divisor) return self def __idiv__(self, divisor): """ For compatibility with Python 2. """ return self.__itruediv__(divisor) def __neg__(self): """ Returns: negation (SymbolicOperator) """ return -1 * self def __pow__(self, exponent): """Exponentiate the SymbolicOperator. Args: exponent (int): The exponent with which to raise the operator. Returns: exponentiated (SymbolicOperator) Raises: ValueError: Can only raise SymbolicOperator to non-negative integer powers. """ # Handle invalid exponents. if not isinstance(exponent, int) or exponent < 0: raise ValueError( 'exponent must be a non-negative int, but was {} {}'.format( type(exponent), repr(exponent))) # Initialized identity. exponentiated = self.__class__(()) # Handle non-zero exponents. for _ in range(exponent): exponentiated *= self return exponentiated def __eq__(self, other): """Approximate numerical equality (not true equality).""" return self.isclose(other) def __ne__(self, other): return not (self == other) def __iter__(self): self._iter = iter(self.terms.items()) return self def __next__(self): term, coefficient = next(self._iter) return self.__class__(term=term, coefficient=coefficient) def isclose(self, other, tol=EQ_TOLERANCE): """Check if other (SymbolicOperator) is close to self. Comparison is done for each term individually. Return True if the difference between each term in self and other is less than EQ_TOLERANCE Args: other(SymbolicOperator): SymbolicOperator to compare against. """ if not isinstance(self, type(other)): return NotImplemented # terms which are in both: for term in set(self.terms).intersection(set(other.terms)): a = self.terms[term] b = other.terms[term] if not (isinstance(a, sympy.Expr) or isinstance(b, sympy.Expr)): tol *= max(1, abs(a), abs(b)) if self._issmall(a - b, tol) is False: return False # terms only in one (compare to 0.0 so only abs_tol) for term in set(self.terms).symmetric_difference(set(other.terms)): if term in self.terms: if self._issmall(self.terms[term], tol) is False: return False else: if self._issmall(other.terms[term], tol) is False: return False return True def compress(self, abs_tol=EQ_TOLERANCE): """ Eliminates all terms with coefficients close to zero and removes small imaginary and real parts. Args: abs_tol(float): Absolute tolerance, must be at least 0.0 """ new_terms = {} for term in self.terms: coeff = self.terms[term] if isinstance(coeff, sympy.Expr): if sympy.simplify(sympy.im(coeff) <= abs_tol) == True: coeff = sympy.re(coeff) if sympy.simplify(sympy.re(coeff) <= abs_tol) == True: coeff = 1j * sympy.im(coeff) if (sympy.simplify(abs(coeff) <= abs_tol) != True): new_terms[term] = coeff continue if isinstance(val, tq.Variable) or isinstance(val, tq.objective.objective.Objective): continue # Remove small imaginary and real parts if abs(coeff.imag) <= abs_tol: coeff = coeff.real if abs(coeff.real) <= abs_tol: coeff = 1.j * coeff.imag # Add the term if the coefficient is large enough if abs(coeff) > abs_tol: new_terms[term] = coeff self.terms = new_terms def induced_norm(self, order=1): r""" Compute the induced p-norm of the operator. If we represent an operator as :math: `\sum_{j} w_j H_j` where :math: `w_j` are scalar coefficients then this norm is :math: `\left(\sum_{j} \| w_j \|^p \right)^{\frac{1}{p}} where :math: `p` is the order of the induced norm Args: order(int): the order of the induced norm. """ norm = 0. for coefficient in self.terms.values(): norm += abs(coefficient)**order return norm**(1. / order) def many_body_order(self): """Compute the many-body order of a SymbolicOperator. The many-body order of a SymbolicOperator is the maximum length of a term with nonzero coefficient. Returns: int """ if not self.terms: # Zero operator return 0 else: return max( len(term) for term, coeff in self.terms.items() if (self._issmall(coeff) is False)) @classmethod def accumulate(cls, operators, start=None): """Sums over SymbolicOperators.""" total = copy.deepcopy(start or cls.zero()) for operator in operators: total += operator return total def get_operators(self): """Gets a list of operators with a single term. Returns: operators([self.__class__]): A generator of the operators in self. """ for term, coefficient in self.terms.items(): yield self.__class__(term, coefficient) def get_operator_groups(self, num_groups): """Gets a list of operators with a few terms. Args: num_groups(int): How many operators to get in the end. Returns: operators([self.__class__]): A list of operators summing up to self. """ if num_groups < 1: warnings.warn('Invalid num_groups {} < 1.'.format(num_groups), RuntimeWarning) num_groups = 1 operators = self.get_operators() num_groups = min(num_groups, len(self.terms)) for i in range(num_groups): yield self.accumulate( itertools.islice(operators, len(range(i, len(self.terms), num_groups))))
25,797
35.697013
97
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.7/main.py
import tequila as tq import numpy as np from tequila.objective.objective import Variable import openfermion from typing import Union from vqe_utils import convert_PQH_to_tq_QH, convert_tq_QH_to_PQH,\ fold_unitary_into_hamiltonian from energy_optimization import * from do_annealing import * import random # guess we could substitute that with numpy.random #TODO import argparse import pickle as pk import matplotlib.pyplot as plt # Main hyperparameters mu = 2.0 # lognormal dist mean sigma = 0.4 # lognormal dist std T_0 = 1.0 # T_0, initial starting temperature # max_epochs = 25 # num_epochs, max number of iterations max_epochs = 20 # num_epochs, max number of iterations min_epochs = 2 # num_epochs, max number of iterations5 # min_epochs = 20 # num_epochs, max number of iterations tol = 1e-6 # minimum change in energy required, otherwise terminate optimization actions_ratio = [.15, .6, .25] patience = 100 beta = 0.5 max_non_cliffords = 0 type_energy_eval='wfn' num_population = 24 num_offsprings = 20 num_processors = 8 #tuning, input as lists. # parser.add_argument('--alphas', type = float, nargs = '+', help='alpha, temperature decay', required=True) alphas = [0.9] # alpha, temperature decay' #Required be = False h2 = True n2 = False name_prefix = '../../data/' # Construct qubit-Hamiltonian #num_active = 3 #active_orbitals = list(range(num_active)) if be: R1 = rrrr R2 = 1.7 geometry = "be 0.0 0.0 0.0\nh 0.0 0.0 {R1}\nh 0.0 0.0 -{R2}" name = "/h/292/philipps/software/moldata/beh2/beh2_{R1:2.2f}_{R2:2.2f}_180" # adapt of you move data mol = tq.Molecule(name=name.format(R1=R1, R2=R2), geometry=geometry.format(R1=R1,R2=R2), n_pno=None) lqm = mol.local_qubit_map(hcb=False) H = mol.make_hamiltonian().map_qubits(lqm).simplify() #print("FCI ENERGY: ", mol.compute_energy(method="fci")) U_spa = mol.make_upccgsd_ansatz(name="SPA").map_qubits(lqm) U = U_spa elif n2: R1 = rrrr geometry = "N 0.0 0.0 0.0\nN 0.0 0.0 {R1}" # name = "/home/abhinav/matter_lab/moldata/n2/n2_{R1:2.2f}" # adapt of you move data name = "/h/292/philipps/software/moldata/n2/n2_{R1:2.2f}" # adapt of you move data mol = tq.Molecule(name=name.format(R1=R1), geometry=geometry.format(R1=R1), n_pno=None) lqm = mol.local_qubit_map(hcb=False) H = mol.make_hamiltonian().map_qubits(lqm).simplify() # print("FCI ENERGY: ", mol.compute_energy(method="fci")) print("Skip FCI calculation, take old data...") U_spa = mol.make_upccgsd_ansatz(name="SPA").map_qubits(lqm) U = U_spa elif h2: active_orbitals = list(range(3)) mol = tq.Molecule(geometry='H 0.0 0.0 0.0\n H 0.0 0.0 1.7', basis_set='6-31g', active_orbitals=active_orbitals, backend='psi4') H = mol.make_hamiltonian().simplify() print("FCI ENERGY: ", mol.compute_energy(method="fci")) U = mol.make_uccsd_ansatz(trotter_steps=1) # Alternatively, get qubit-Hamiltonian from openfermion/externally # with open("ham_6qubits.txt") as hamstring_file: """if be: with open("ham_beh2_3_3.txt") as hamstring_file: hamstring = hamstring_file.read() #print(hamstring) H = tq.QubitHamiltonian().from_string(string=hamstring, openfermion_format=True) elif h2: with open("ham_6qubits.txt") as hamstring_file: hamstring = hamstring_file.read() #print(hamstring) H = tq.QubitHamiltonian().from_string(string=hamstring, openfermion_format=True)""" n_qubits = len(H.qubits) ''' Option 'wfn': "Shortcut" via wavefunction-optimization using MPO-rep of Hamiltonian Option 'qc': Need to input a proper quantum circuit ''' # Clifford optimization in the context of reduced-size quantum circuits starting_E = 123.456 reference = True if reference: if type_energy_eval.lower() == 'wfn': starting_E, _ = minimize_energy(hamiltonian=H, n_qubits=n_qubits, type_energy_eval='wfn') print('starting energy wfn: {:.5f}'.format(starting_E), flush=True) elif type_energy_eval.lower() == 'qc': starting_E, _ = minimize_energy(hamiltonian=H, n_qubits=n_qubits, type_energy_eval='qc', cluster_circuit=U) print('starting energy spa: {:.5f}'.format(starting_E)) else: raise Exception("type_energy_eval must be either 'wfn' or 'qc', but is", type_energy_eval) starting_E, _ = minimize_energy(hamiltonian=H, n_qubits=n_qubits, type_energy_eval='wfn') """for alpha in alphas: print('Starting optimization, alpha = {:3f}'.format(alpha)) # print('Energy to beat', minimize_energy(H, n_qubits, 'wfn')[0]) simulated_annealing(hamiltonian=H, num_population=num_population, num_offsprings=num_offsprings, num_processors=num_processors, tol=tol, max_epochs=max_epochs, min_epochs=min_epochs, T_0=T_0, alpha=alpha, actions_ratio=actions_ratio, max_non_cliffords=max_non_cliffords, verbose=True, patience=patience, beta=beta, type_energy_eval=type_energy_eval.lower(), cluster_circuit=U, starting_energy=starting_E)""" alter_cliffords = True if alter_cliffords: print("starting to replace cliffords with non-clifford gates to see if that improves the current fitness") replace_cliff_with_non_cliff(hamiltonian=H, num_population=num_population, num_offsprings=num_offsprings, num_processors=num_processors, tol=tol, max_epochs=max_epochs, min_epochs=min_epochs, T_0=T_0, alpha=alphas[0], actions_ratio=actions_ratio, max_non_cliffords=max_non_cliffords, verbose=True, patience=patience, beta=beta, type_energy_eval=type_energy_eval.lower(), cluster_circuit=U, starting_energy=starting_E) # accepted_E, tested_E, decisions, instructions_list, best_instructions, temp, best_E = simulated_annealing(hamiltonian=H, # population=4, # num_mutations=2, # num_processors=1, # tol=opt.tol, max_epochs=opt.max_epochs, # min_epochs=opt.min_epochs, T_0=opt.T_0, alpha=alpha, # mu=opt.mu, sigma=opt.sigma, verbose=True, prev_E = starting_E, patience = 10, beta = 0.5, # energy_eval='qc', # eval_circuit=U # print(best_E) # print(best_instructions) # print(len(accepted_E)) # plt.plot(accepted_E) # plt.show() # #pickling data # data = {'accepted_energies': accepted_E, 'tested_energies': tested_E, # 'decisions': decisions, 'instructions': instructions_list, # 'best_instructions': best_instructions, 'temperature': temp, # 'best_energy': best_E} # f_name = '{}{}_alpha_{:.2f}.pk'.format(opt.name_prefix, r, alpha) # pk.dump(data, open(f_name, 'wb')) # print('Finished optimization, data saved in {}'.format(f_name))
7,368
40.869318
129
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.7/my_mpo.py
import numpy as np import tensornetwork as tn from tensornetwork.backends.abstract_backend import AbstractBackend tn.set_default_backend("pytorch") #tn.set_default_backend("numpy") from typing import List, Union, Text, Optional, Any, Type Tensor = Any import tequila as tq import torch EPS = 1e-12 class SubOperator: """ This is just a helper class to store coefficient, operators and positions in an intermediate format """ def __init__(self, coefficient: float, operators: List, positions: List ): self._coefficient = coefficient self._operators = operators self._positions = positions @property def coefficient(self): return self._coefficient @property def operators(self): return self._operators @property def positions(self): return self._positions class MPOContainer: """ Class that handles the MPO. Is able to set values at certain positions, update containers (wannabe-equivalent to dynamic arrays) and compress the MPO """ def __init__(self, n_qubits: int, ): self.n_qubits = n_qubits self.container = [ np.zeros((1,1,2,2), dtype=np.complex) for q in range(self.n_qubits) ] def get_dim(self): """ Returns max dimension of container """ d = 1 for q in range(len(self.container)): d = max(d, self.container[q].shape[0]) return d def set_tensor(self, qubit: int, set_at: list, add_operator: Union[np.ndarray, float]): """ set_at: where to put data """ # Set a matrix if len(set_at) == 2: self.container[qubit][set_at[0],set_at[1],:,:] = add_operator[:,:] # Set specific values elif len(set_at) == 4: self.container[qubit][set_at[0],set_at[1],set_at[2],set_at[3]] =\ add_operator else: raise Exception("set_at needs to be either of length 2 or 4") def update_container(self, qubit: int, update_dir: list, add_operator: np.ndarray): """ This should mimick a dynamic array update_dir: e.g. [1,1,0,0] -> extend dimension along where there's a 1 the last two dimensions are always 2x2 only """ old_shape = self.container[qubit].shape # print(old_shape) if not len(update_dir) == 4: if len(update_dir) == 2: update_dir += [0, 0] else: raise Exception("update_dir needs to be either of length 2 or 4") if update_dir[2] or update_dir[3]: raise Exception("Last two dims must be zero.") new_shape = tuple(update_dir[i]+old_shape[i] for i in range(len(update_dir))) new_tensor = np.zeros(new_shape, dtype=np.complex) # Copy old values new_tensor[:old_shape[0],:old_shape[1],:,:] = self.container[qubit][:,:,:,:] # Add new values new_tensor[new_shape[0]-1,new_shape[1]-1,:,:] = add_operator[:,:] # Overwrite container self.container[qubit] = new_tensor def compress_mpo(self): """ Compression of MPO via SVD """ n_qubits = len(self.container) for q in range(n_qubits): my_shape = self.container[q].shape self.container[q] =\ self.container[q].reshape((my_shape[0], my_shape[1], -1)) # Go forwards for q in range(n_qubits-1): # Apply permutation [0 1 2] -> [0 2 1] my_tensor = np.swapaxes(self.container[q], 1, 2) my_tensor = my_tensor.reshape((-1, my_tensor.shape[2])) # full_matrices flag corresponds to 'econ' -> no zero-singular values u, s, vh = np.linalg.svd(my_tensor, full_matrices=False) # Count the non-zero singular values num_nonzeros = len(np.argwhere(s>EPS)) # Construct matrix from square root of singular values s = np.diag(np.sqrt(s[:num_nonzeros])) u = u[:,:num_nonzeros] vh = vh[:num_nonzeros,:] # Distribute weights to left- and right singular vectors (@ = np.matmul) u = u @ s vh = s @ vh # Apply permutation [0 1 2] -> [0 2 1] u = u.reshape((self.container[q].shape[0],\ self.container[q].shape[2], -1)) self.container[q] = np.swapaxes(u, 1, 2) self.container[q+1] = tn.ncon([vh, self.container[q+1]], [(-1, 1),(1, -2, -3)]) # Go backwards for q in range(n_qubits-1, 0, -1): my_tensor = self.container[q] my_tensor = my_tensor.reshape((self.container[q].shape[0], -1)) # full_matrices flag corresponds to 'econ' -> no zero-singular values u, s, vh = np.linalg.svd(my_tensor, full_matrices=False) # Count the non-zero singular values num_nonzeros = len(np.argwhere(s>EPS)) # Construct matrix from square root of singular values s = np.diag(np.sqrt(s[:num_nonzeros])) u = u[:,:num_nonzeros] vh = vh[:num_nonzeros,:] # Distribute weights to left- and right singular vectors u = u @ s vh = s @ vh self.container[q] = np.reshape(vh, (num_nonzeros, self.container[q].shape[1], self.container[q].shape[2])) self.container[q-1] = tn.ncon([self.container[q-1], u], [(-1, 1, -3),(1, -2)]) for q in range(n_qubits): my_shape = self.container[q].shape self.container[q] = self.container[q].reshape((my_shape[0],\ my_shape[1],2,2)) # TODO maybe make subclass of tn.FiniteMPO if it makes sense #class my_MPO(tn.FiniteMPO): class MyMPO: """ Class building up on tensornetwork FiniteMPO to handle MPO-Hamiltonians """ def __init__(self, hamiltonian: Union[tq.QubitHamiltonian, Text], # tensors: List[Tensor], backend: Optional[Union[AbstractBackend, Text]] = None, n_qubits: Optional[int] = None, name: Optional[Text] = None, maxdim: Optional[int] = 10000) -> None: # TODO: modifiy docstring """ Initialize a finite MPO object Args: tensors: The mpo tensors. backend: An optional backend. Defaults to the defaulf backend of TensorNetwork. name: An optional name for the MPO. """ self.hamiltonian = hamiltonian self.maxdim = maxdim if n_qubits: self._n_qubits = n_qubits else: self._n_qubits = self.get_n_qubits() @property def n_qubits(self): return self._n_qubits def make_mpo_from_hamiltonian(self): intermediate = self.openfermion_to_intermediate() # for i in range(len(intermediate)): # print(intermediate[i].coefficient) # print(intermediate[i].operators) # print(intermediate[i].positions) self.mpo = self.intermediate_to_mpo(intermediate) def openfermion_to_intermediate(self): # Here, have either a QubitHamiltonian or a file with a of-operator # Start with Qubithamiltonian def get_pauli_matrix(string): pauli_matrices = { 'I': np.array([[1, 0], [0, 1]], dtype=np.complex), 'Z': np.array([[1, 0], [0, -1]], dtype=np.complex), 'X': np.array([[0, 1], [1, 0]], dtype=np.complex), 'Y': np.array([[0, -1j], [1j, 0]], dtype=np.complex) } return pauli_matrices[string.upper()] intermediate = [] first = True # Store all paulistrings in intermediate format for paulistring in self.hamiltonian.paulistrings: coefficient = paulistring.coeff # print(coefficient) operators = [] positions = [] # Only first one should be identity -> distribute over all if first and not paulistring.items(): positions += [] operators += [] first = False elif not first and not paulistring.items(): raise Exception("Only first Pauli should be identity.") # Get operators and where they act for k,v in paulistring.items(): positions += [k] operators += [get_pauli_matrix(v)] tmp_op = SubOperator(coefficient=coefficient, operators=operators, positions=positions) intermediate += [tmp_op] # print("len intermediate = num Pauli strings", len(intermediate)) return intermediate def build_single_mpo(self, intermediate, j): # Set MPO Container n_qubits = self._n_qubits mpo = MPOContainer(n_qubits=n_qubits) # *********************************************************************** # Set first entries (of which we know that they are 2x2-matrices) # Typically, this is an identity my_coefficient = intermediate[j].coefficient my_positions = intermediate[j].positions my_operators = intermediate[j].operators for q in range(n_qubits): if not q in my_positions: mpo.set_tensor(qubit=q, set_at=[0,0], add_operator=np.complex(my_coefficient)**(1/n_qubits)* np.eye(2)) elif q in my_positions: my_pos_index = my_positions.index(q) mpo.set_tensor(qubit=q, set_at=[0,0], add_operator=np.complex(my_coefficient)**(1/n_qubits)* my_operators[my_pos_index]) # *********************************************************************** # All other entries # while (j smaller than number of intermediates left) and mpo.dim() <= self.maxdim # Re-write this based on positions keyword! j += 1 while j < len(intermediate) and mpo.get_dim() < self.maxdim: # """ my_coefficient = intermediate[j].coefficient my_positions = intermediate[j].positions my_operators = intermediate[j].operators for q in range(n_qubits): # It is guaranteed that every index appears only once in positions if q == 0: update_dir = [0,1] elif q == n_qubits-1: update_dir = [1,0] else: update_dir = [1,1] # If there's an operator on my position, add that if q in my_positions: my_pos_index = my_positions.index(q) mpo.update_container(qubit=q, update_dir=update_dir, add_operator= np.complex(my_coefficient)**(1/n_qubits)* my_operators[my_pos_index]) # Else add an identity else: mpo.update_container(qubit=q, update_dir=update_dir, add_operator= np.complex(my_coefficient)**(1/n_qubits)* np.eye(2)) if not j % 100: mpo.compress_mpo() #print("\t\tAt iteration ", j, " MPO has dimension ", mpo.get_dim()) j += 1 mpo.compress_mpo() #print("\tAt final iteration ", j-1, " MPO has dimension ", mpo.get_dim()) return mpo, j def intermediate_to_mpo(self, intermediate): n_qubits = self._n_qubits # TODO Change to multiple MPOs mpo_list = [] j_global = 0 num_mpos = 0 # Start with 0, then final one is correct while j_global < len(intermediate): current_mpo, j_global = self.build_single_mpo(intermediate, j_global) mpo_list += [current_mpo] num_mpos += 1 return mpo_list def construct_matrix(self): # TODO extend to lists of MPOs ''' Recover matrix, e.g. to compare with Hamiltonian that we get from tq ''' mpo = self.mpo # Contract over all bond indices # mpo.container has indices [bond, bond, physical, physical] n_qubits = self._n_qubits d = int(2**(n_qubits/2)) first = True H = None #H = np.zeros((d,d,d,d), dtype='complex') # Define network nodes # | | | | # -O--O--...--O--O- # | | | | for m in mpo: assert(n_qubits == len(m.container)) nodes = [tn.Node(m.container[q], name=str(q)) for q in range(n_qubits)] # Connect network (along double -- above) for q in range(n_qubits-1): nodes[q][1] ^ nodes[q+1][0] # Collect dangling edges (free indices) edges = [] # Left dangling edge edges += [nodes[0].get_edge(0)] # Right dangling edge edges += [nodes[-1].get_edge(1)] # Upper dangling edges for q in range(n_qubits): edges += [nodes[q].get_edge(2)] # Lower dangling edges for q in range(n_qubits): edges += [nodes[q].get_edge(3)] # Contract between all nodes along non-dangling edges res = tn.contractors.auto(nodes, output_edge_order=edges) # Reshape to get tensor of order 4 (get rid of left- and right open indices # and combine top&bottom into one) if isinstance(res.tensor, torch.Tensor): H_m = res.tensor.numpy() if not first: H += H_m else: H = H_m first = False return H.reshape((d,d,d,d))
14,354
36.480418
99
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.7/do_annealing.py
import tequila as tq import numpy as np import pickle from pathos.multiprocessing import ProcessingPool as Pool from parallel_annealing import * #from dummy_par import * from mutation_options import * from single_thread_annealing import * def find_best_instructions(instructions_dict): """ This function finds the instruction with the best fitness args: instructions_dict: A dictionary with the "Instructions" objects the corresponding fitness values as values """ best_instructions = None best_fitness = 10000000 for key in instructions_dict: if instructions_dict[key][1] <= best_fitness: best_instructions = instructions_dict[key][0] best_fitness = instructions_dict[key][1] return best_instructions, best_fitness def simulated_annealing(num_population, num_offsprings, actions_ratio, hamiltonian, max_epochs=100, min_epochs=1, tol=1e-6, type_energy_eval="wfn", cluster_circuit=None, patience = 20, num_processors=4, T_0=1.0, alpha=0.9, max_non_cliffords=0, verbose=False, beta=0.5, starting_energy=None): """ this function tries to find the clifford circuit that best lowers the energy of the hamiltonian using simulated annealing. params: - num_population = number of members in a generation - num_offsprings = number of mutations carried on every member - num_processors = number of processors to use for parallelization - T_0 = initial temperature - alpha = temperature decay - beta = parameter to adjust temperature on resetting after running out of patience - max_epochs = max iterations for optimizing - min_epochs = min iterations for optimizing - tol = minimum change in energy required, otherwise terminate optimization - verbose = display energies/decisions at iterations of not - hamiltonian = original hamiltonian - actions_ratio = The ratio of the different actions for mutations - type_energy_eval = keyword specifying the type of optimization method to use for energy minimization - cluster_circuit = the reference circuit to which clifford gates are added - patience = the number of epochs before resetting the optimization """ if verbose: print("Starting to Optimize Cluster circuit", flush=True) num_qubits = len(hamiltonian.qubits) if verbose: print("Initializing Generation", flush=True) # restart = False if previous_instructions is None\ # else True restart = False instructions_dict = {} instructions_list = [] current_fitness_list = [] fitness, wfn = None, None # pre-initialize with None for instruction_id in range(num_population): instructions = None if restart: try: instructions = Instructions(n_qubits=num_qubits, alpha=alpha, T_0=T_0, beta=beta, patience=patience, max_non_cliffords=max_non_cliffords, reference_energy=starting_energy) instructions.gates = pickle.load(open("instruct_gates.pickle", "rb")) instructions.positions = pickle.load(open("instruct_positions.pickle", "rb")) instructions.best_reference_wfn = pickle.load(open("best_reference_wfn.pickle", "rb")) print("Added a guess from previous runs", flush=True) fitness, wfn = evaluate_fitness(instructions=instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) except Exception as e: print(e) raise Exception("Did not find a guess from previous runs") # pass restart = False #print(instructions._str()) else: failed = True while failed: instructions = Instructions(n_qubits=num_qubits, alpha=alpha, T_0=T_0, beta=beta, patience=patience, max_non_cliffords=max_non_cliffords, reference_energy=starting_energy) instructions.prune() fitness, wfn = evaluate_fitness(instructions=instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) # if fitness <= starting_energy: failed = False instructions.set_reference_wfn(wfn) current_fitness_list.append(fitness) instructions_list.append(instructions) instructions_dict[instruction_id] = (instructions, fitness) if verbose: print("First Generation details: \n", flush=True) for key in instructions_dict: print("Initial Instructions number: ", key, flush=True) instructions_dict[key][0]._str() print("Initial fitness values: ", instructions_dict[key][1], flush=True) best_instructions, best_energy = find_best_instructions(instructions_dict) if verbose: print("Best member of the Generation: \n", flush=True) print("Instructions: ", flush=True) best_instructions._str() print("fitness value: ", best_energy, flush=True) pickle.dump(best_instructions.gates, open("instruct_gates.pickle", "wb")) pickle.dump(best_instructions.positions, open("instruct_positions.pickle", "wb")) pickle.dump(best_instructions.best_reference_wfn, open("best_reference_wfn.pickle", "wb")) epoch = 0 previous_best_energy = best_energy converged = False has_improved_before = False dts = [] #pool = multiprocessing.Pool(processes=num_processors) while (epoch < max_epochs): print("Epoch: ", epoch, flush=True) import time t0 = time.time() if num_processors == 1: st_evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, type_energy_eval, cluster_circuit) else: evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, num_processors, type_energy_eval, cluster_circuit) t1 = time.time() dts += [t1-t0] best_instructions, best_energy = find_best_instructions(instructions_dict) if verbose: print("Best member of the Generation: \n", flush=True) print("Instructions: ", flush=True) best_instructions._str() print("fitness value: ", best_energy, flush=True) # A bit confusing, but: # Want that current best energy has improved something previous, is better than # some starting energy and achieves some convergence criterion has_improved_before = True if np.abs(best_energy - previous_best_energy) < 0\ else False if np.abs(best_energy - previous_best_energy) < tol and has_improved_before: if starting_energy is not None: converged = True if best_energy < starting_energy else False else: converged = True else: converged = False if best_energy < previous_best_energy: previous_best_energy = best_energy epoch += 1 pickle.dump(best_instructions.gates, open("instruct_gates.pickle", "wb")) pickle.dump(best_instructions.positions, open("instruct_positions.pickle", "wb")) pickle.dump(best_instructions.best_reference_wfn, open("best_reference_wfn.pickle", "wb")) #pool.close() if converged: print("Converged after ", epoch, " iterations.", flush=True) print("Best energy:", best_energy, flush=True) print("\t with instructions", best_instructions.gates, best_instructions.positions, flush=True) print("\t optimal parameters", best_instructions.best_reference_wfn, flush=True) print("average time: ", np.average(dts), flush=True) print("overall time: ", np.sum(dts), flush=True) # best_instructions.replace_UCCXc_with_UCC(number=max_non_cliffords) pickle.dump(best_instructions.gates, open("instruct_gates.pickle", "wb")) pickle.dump(best_instructions.positions, open("instruct_positions.pickle", "wb")) pickle.dump(best_instructions.best_reference_wfn, open("best_reference_wfn.pickle", "wb")) def replace_cliff_with_non_cliff(num_population, num_offsprings, actions_ratio, hamiltonian, max_epochs=100, min_epochs=1, tol=1e-6, type_energy_eval="wfn", cluster_circuit=None, patience = 20, num_processors=4, T_0=1.0, alpha=0.9, max_non_cliffords=0, verbose=False, beta=0.5, starting_energy=None): """ this function tries to find the clifford circuit that best lowers the energy of the hamiltonian using simulated annealing. params: - num_population = number of members in a generation - num_offsprings = number of mutations carried on every member - num_processors = number of processors to use for parallelization - T_0 = initial temperature - alpha = temperature decay - beta = parameter to adjust temperature on resetting after running out of patience - max_epochs = max iterations for optimizing - min_epochs = min iterations for optimizing - tol = minimum change in energy required, otherwise terminate optimization - verbose = display energies/decisions at iterations of not - hamiltonian = original hamiltonian - actions_ratio = The ratio of the different actions for mutations - type_energy_eval = keyword specifying the type of optimization method to use for energy minimization - cluster_circuit = the reference circuit to which clifford gates are added - patience = the number of epochs before resetting the optimization """ if verbose: print("Starting to replace clifford gates Cluster circuit with non-clifford gates one at a time", flush=True) num_qubits = len(hamiltonian.qubits) #get the best clifford object instructions = Instructions(n_qubits=num_qubits, alpha=alpha, T_0=T_0, beta=beta, patience=patience, max_non_cliffords=max_non_cliffords, reference_energy=starting_energy) instructions.gates = pickle.load(open("instruct_gates.pickle", "rb")) instructions.positions = pickle.load(open("instruct_positions.pickle", "rb")) instructions.best_reference_wfn = pickle.load(open("best_reference_wfn.pickle", "rb")) fitness, wfn = evaluate_fitness(instructions=instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) if verbose: print("Initial energy after previous Clifford optimization is",\ fitness, flush=True) print("Starting with instructions", instructions.gates, instructions.positions, flush=True) instructions_dict = {} instructions_dict[0] = (instructions, fitness) for gate_id, (gate, position) in enumerate(zip(instructions.gates, instructions.positions)): print(gate) altered_instructions = copy.deepcopy(instructions) # skip if controlled rotation if gate[0]=='C': continue altered_instructions.replace_cg_w_ncg(gate_id) # altered_instructions.max_non_cliffords = 1 # TODO why is this set to 1?? altered_instructions.max_non_cliffords = max_non_cliffords #clifford_circuit, init_angles = build_circuit(instructions) #print(clifford_circuit, init_angles) #folded_hamiltonian = perform_folding(hamiltonian, clifford_circuit) #folded_hamiltonian2 = (convert_PQH_to_tq_QH(folded_hamiltonian))() #print(folded_hamiltonian) #clifford_circuit, init_angles = build_circuit(altered_instructions) #print(clifford_circuit, init_angles) #folded_hamiltonian = perform_folding(hamiltonian, clifford_circuit) #folded_hamiltonian1 = (convert_PQH_to_tq_QH(folded_hamiltonian))(init_angles) #print(folded_hamiltonian1 - folded_hamiltonian2) #print(folded_hamiltonian) #raise Exception("teste") counter = 0 success = False while not success: counter += 1 try: fitness, wfn = evaluate_fitness(instructions=altered_instructions, hamiltonian=hamiltonian, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit) success = True except Exception as e: print(e) if counter > 5: print("This replacement failed more than 5 times") success = True instructions_dict[gate_id+1] = (altered_instructions, fitness) #circuit = build_circuit(altered_instructions) #tq.draw(circuit,backend="cirq") best_instructions, best_energy = find_best_instructions(instructions_dict) print("best instrucitons after the non-clifford opimizaton") print("Best energy:", best_energy, flush=True) print("\t with instructions", best_instructions.gates, best_instructions.positions, flush=True)
13,155
46.154122
187
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.7/scipy_optimizer.py
import numpy, copy, scipy, typing, numbers from tequila import BitString, BitNumbering, BitStringLSB from tequila.utils.keymap import KeyMapRegisterToSubregister from tequila.circuit.compiler import change_basis from tequila.utils import to_float import tequila as tq from tequila.objective import Objective from tequila.optimizers.optimizer_scipy import OptimizerSciPy, SciPyResults from tequila.objective.objective import assign_variable, Variable, format_variable_dictionary, format_variable_list from tequila.circuit.noise import NoiseModel #from tequila.optimizers._containers import _EvalContainer, _GradContainer, _HessContainer, _QngContainer from vqe_utils import * class _EvalContainer: """ Overwrite the call function Container Class to access scipy and keep the optimization history. This class is used by the SciPy optimizer and should not be used elsewhere. Attributes --------- objective: the objective to evaluate. param_keys: the dictionary mapping parameter keys to positions in a numpy array. samples: the number of samples to evaluate objective with. save_history: whether or not to save, in a history, information about each time __call__ occurs. print_level dictates the verbosity of printing during call. N: the length of param_keys. history: if save_history, a list of energies received from every __call__ history_angles: if save_history, a list of angles sent to __call__. """ def __init__(self, Hamiltonian, unitary, param_keys, Ham_derivatives= None, Eval=None, passive_angles=None, samples=1024, save_history=True, print_level: int = 3): self.Hamiltonian = Hamiltonian self.unitary = unitary self.samples = samples self.param_keys = param_keys self.N = len(param_keys) self.save_history = save_history self.print_level = print_level self.passive_angles = passive_angles self.Eval = Eval self.infostring = None self.Ham_derivatives = Ham_derivatives if save_history: self.history = [] self.history_angles = [] def __call__(self, p, *args, **kwargs): """ call a wrapped objective. Parameters ---------- p: numpy array: Parameters with which to call the objective. args kwargs Returns ------- numpy.array: value of self.objective with p translated into variables, as a numpy array. """ angles = {}#dict((self.param_keys[i], p[i]) for i in range(self.N)) for i in range(self.N): if self.param_keys[i] in self.unitary.extract_variables(): angles[self.param_keys[i]] = p[i] else: angles[self.param_keys[i]] = complex(p[i]) if self.passive_angles is not None: angles = {**angles, **self.passive_angles} vars = format_variable_dictionary(angles) Hamiltonian = self.Hamiltonian(vars) #print(Hamiltonian) #print(self.unitary) #print(vars) Expval = tq.ExpectationValue(H=Hamiltonian, U=self.unitary) #print(Expval) E = tq.simulate(Expval, vars, backend='qulacs', samples=self.samples) self.infostring = "{:15} : {} expectationvalues\n".format("Objective", Expval.count_expectationvalues()) if self.print_level > 2: print("E={:+2.8f}".format(E), " angles=", angles, " samples=", self.samples) elif self.print_level > 1: print("E={:+2.8f}".format(E)) if self.save_history: self.history.append(E) self.history_angles.append(angles) return complex(E) # jax types confuses optimizers class _GradContainer(_EvalContainer): """ Overwrite the call function Container Class to access scipy and keep the optimization history. This class is used by the SciPy optimizer and should not be used elsewhere. see _EvalContainer for details. """ def __call__(self, p, *args, **kwargs): """ call the wrapped qng. Parameters ---------- p: numpy array: Parameters with which to call gradient args kwargs Returns ------- numpy.array: value of self.objective with p translated into variables, as a numpy array. """ Ham_derivatives = self.Ham_derivatives Hamiltonian = self.Hamiltonian unitary = self.unitary dE_vec = numpy.zeros(self.N) memory = dict() #variables = dict((self.param_keys[i], p[i]) for i in range(len(self.param_keys))) variables = {}#dict((self.param_keys[i], p[i]) for i in range(self.N)) for i in range(len(self.param_keys)): if self.param_keys[i] in self.unitary.extract_variables(): variables[self.param_keys[i]] = p[i] else: variables[self.param_keys[i]] = complex(p[i]) if self.passive_angles is not None: variables = {**variables, **self.passive_angles} vars = format_variable_dictionary(variables) expvals = 0 for i in range(self.N): derivative = 0.0 if self.param_keys[i] in list(unitary.extract_variables()): Ham = Hamiltonian(vars) Expval = tq.ExpectationValue(H=Ham, U=unitary) temp_derivative = tq.compile(objective = tq.grad(objective = Expval, variable = self.param_keys[i]),backend='qulacs') expvals += temp_derivative.count_expectationvalues() derivative += temp_derivative if self.param_keys[i] in list(Ham_derivatives.keys()): #print(self.param_keys[i]) Ham = Ham_derivatives[self.param_keys[i]] Ham = convert_PQH_to_tq_QH(Ham) H = Ham(vars) #print(H) #raise Exception("testing") Expval = tq.ExpectationValue(H=H, U=unitary) expvals += Expval.count_expectationvalues() derivative += tq.simulate(Expval, vars, backend='qulacs', samples=self.samples) #print(derivative) #print(type(H)) if isinstance(derivative, float) or isinstance(derivative, numpy.complex64) : dE_vec[i] = derivative else: dE_vec[i] = derivative(variables=variables, samples=self.samples) memory[self.param_keys[i]] = dE_vec[i] self.infostring = "{:15} : {} expectationvalues\n".format("gradient", expvals) self.history.append(memory) return numpy.asarray(dE_vec, dtype=numpy.complex64) class optimize_scipy(OptimizerSciPy): """ overwrite the expectation and gradient container objects """ def initialize_variables(self, all_variables, initial_values, variables): """ Convenience function to format the variables of some objective recieved in calls to optimzers. Parameters ---------- objective: Objective: the objective being optimized. initial_values: dict or string: initial values for the variables of objective, as a dictionary. if string: can be `zero` or `random` if callable: custom function that initializes when keys are passed if None: random initialization between 0 and 2pi (not recommended) variables: list: the variables being optimized over. Returns ------- tuple: active_angles, a dict of those variables being optimized. passive_angles, a dict of those variables NOT being optimized. variables: formatted list of the variables being optimized. """ # bring into right format variables = format_variable_list(variables) initial_values = format_variable_dictionary(initial_values) all_variables = all_variables if variables is None: variables = all_variables if initial_values is None: initial_values = {k: numpy.random.uniform(0, 2 * numpy.pi) for k in all_variables} elif hasattr(initial_values, "lower"): if initial_values.lower() == "zero": initial_values = {k:0.0 for k in all_variables} elif initial_values.lower() == "random": initial_values = {k: numpy.random.uniform(0, 2 * numpy.pi) for k in all_variables} else: raise TequilaOptimizerException("unknown initialization instruction: {}".format(initial_values)) elif callable(initial_values): initial_values = {k: initial_values(k) for k in all_variables} elif isinstance(initial_values, numbers.Number): initial_values = {k: initial_values for k in all_variables} else: # autocomplete initial values, warn if you did detected = False for k in all_variables: if k not in initial_values: initial_values[k] = 0.0 detected = True if detected and not self.silent: warnings.warn("initial_variables given but not complete: Autocompleted with zeroes", TequilaWarning) active_angles = {} for v in variables: active_angles[v] = initial_values[v] passive_angles = {} for k, v in initial_values.items(): if k not in active_angles.keys(): passive_angles[k] = v return active_angles, passive_angles, variables def __call__(self, Hamiltonian, unitary, variables: typing.List[Variable] = None, initial_values: typing.Dict[Variable, numbers.Real] = None, gradient: typing.Dict[Variable, Objective] = None, hessian: typing.Dict[typing.Tuple[Variable, Variable], Objective] = None, reset_history: bool = True, *args, **kwargs) -> SciPyResults: """ Perform optimization using scipy optimizers. Parameters ---------- objective: Objective: the objective to optimize. variables: list, optional: the variables of objective to optimize. If None: optimize all. initial_values: dict, optional: a starting point from which to begin optimization. Will be generated if None. gradient: optional: Information or object used to calculate the gradient of objective. Defaults to None: get analytically. hessian: optional: Information or object used to calculate the hessian of objective. Defaults to None: get analytically. reset_history: bool: Default = True: whether or not to reset all history before optimizing. args kwargs Returns ------- ScipyReturnType: the results of optimization. """ H = convert_PQH_to_tq_QH(Hamiltonian) Ham_variables, Ham_derivatives = H._construct_derivatives() #print("hamvars",Ham_variables) all_variables = copy.deepcopy(Ham_variables) #print(all_variables) for var in unitary.extract_variables(): all_variables.append(var) #print(all_variables) infostring = "{:15} : {}\n".format("Method", self.method) #infostring += "{:15} : {} expectationvalues\n".format("Objective", objective.count_expectationvalues()) if self.save_history and reset_history: self.reset_history() active_angles, passive_angles, variables = self.initialize_variables(all_variables, initial_values, variables) #print(active_angles, passive_angles, variables) # Transform the initial value directory into (ordered) arrays param_keys, param_values = zip(*active_angles.items()) param_values = numpy.array(param_values) # process and initialize scipy bounds bounds = None if self.method_bounds is not None: bounds = {k: None for k in active_angles} for k, v in self.method_bounds.items(): if k in bounds: bounds[k] = v infostring += "{:15} : {}\n".format("bounds", self.method_bounds) names, bounds = zip(*bounds.items()) assert (names == param_keys) # make sure the bounds are not shuffled #print(param_keys, param_values) # do the compilation here to avoid costly recompilation during the optimization #compiled_objective = self.compile_objective(objective=objective, *args, **kwargs) E = _EvalContainer(Hamiltonian = H, unitary = unitary, Eval=None, param_keys=param_keys, samples=self.samples, passive_angles=passive_angles, save_history=self.save_history, print_level=self.print_level) E.print_level = 0 (E(param_values)) E.print_level = self.print_level infostring += E.infostring if gradient is not None: infostring += "{:15} : {}\n".format("grad instr", gradient) if hessian is not None: infostring += "{:15} : {}\n".format("hess_instr", hessian) compile_gradient = self.method in (self.gradient_based_methods + self.hessian_based_methods) compile_hessian = self.method in self.hessian_based_methods dE = None ddE = None # detect if numerical gradients shall be used # switch off compiling if so if isinstance(gradient, str): if gradient.lower() == 'qng': compile_gradient = False if compile_hessian: raise TequilaException('Sorry, QNG and hessian not yet tested together.') combos = get_qng_combos(objective, initial_values=initial_values, backend=self.backend, samples=self.samples, noise=self.noise) dE = _QngContainer(combos=combos, param_keys=param_keys, passive_angles=passive_angles) infostring += "{:15} : QNG {}\n".format("gradient", dE) else: dE = gradient compile_gradient = False if compile_hessian: compile_hessian = False if hessian is None: hessian = gradient infostring += "{:15} : scipy numerical {}\n".format("gradient", dE) infostring += "{:15} : scipy numerical {}\n".format("hessian", ddE) if isinstance(gradient,dict): if gradient['method'] == 'qng': func = gradient['function'] compile_gradient = False if compile_hessian: raise TequilaException('Sorry, QNG and hessian not yet tested together.') combos = get_qng_combos(objective,func=func, initial_values=initial_values, backend=self.backend, samples=self.samples, noise=self.noise) dE = _QngContainer(combos=combos, param_keys=param_keys, passive_angles=passive_angles) infostring += "{:15} : QNG {}\n".format("gradient", dE) if isinstance(hessian, str): ddE = hessian compile_hessian = False if compile_gradient: dE =_GradContainer(Ham_derivatives = Ham_derivatives, unitary = unitary, Hamiltonian = H, Eval= E, param_keys=param_keys, samples=self.samples, passive_angles=passive_angles, save_history=self.save_history, print_level=self.print_level) dE.print_level = 0 (dE(param_values)) dE.print_level = self.print_level infostring += dE.infostring if self.print_level > 0: print(self) print(infostring) print("{:15} : {}\n".format("active variables", len(active_angles))) Es = [] optimizer_instance = self class SciPyCallback: energies = [] gradients = [] hessians = [] angles = [] real_iterations = 0 def __call__(self, *args, **kwargs): self.energies.append(E.history[-1]) self.angles.append(E.history_angles[-1]) if dE is not None and not isinstance(dE, str): self.gradients.append(dE.history[-1]) if ddE is not None and not isinstance(ddE, str): self.hessians.append(ddE.history[-1]) self.real_iterations += 1 if 'callback' in optimizer_instance.kwargs: optimizer_instance.kwargs['callback'](E.history_angles[-1]) callback = SciPyCallback() res = scipy.optimize.minimize(E, x0=param_values, jac=dE, hess=ddE, args=(Es,), method=self.method, tol=self.tol, bounds=bounds, constraints=self.method_constraints, options=self.method_options, callback=callback) # failsafe since callback is not implemented everywhere if callback.real_iterations == 0: real_iterations = range(len(E.history)) if self.save_history: self.history.energies = callback.energies self.history.energy_evaluations = E.history self.history.angles = callback.angles self.history.angles_evaluations = E.history_angles self.history.gradients = callback.gradients self.history.hessians = callback.hessians if dE is not None and not isinstance(dE, str): self.history.gradients_evaluations = dE.history if ddE is not None and not isinstance(ddE, str): self.history.hessians_evaluations = ddE.history # some methods like "cobyla" do not support callback functions if len(self.history.energies) == 0: self.history.energies = E.history self.history.angles = E.history_angles # some scipy methods always give back the last value and not the minimum (e.g. cobyla) ea = sorted(zip(E.history, E.history_angles), key=lambda x: x[0]) E_final = ea[0][0] angles_final = ea[0][1] #dict((param_keys[i], res.x[i]) for i in range(len(param_keys))) angles_final = {**angles_final, **passive_angles} return SciPyResults(energy=E_final, history=self.history, variables=format_variable_dictionary(angles_final), scipy_result=res) def minimize(Hamiltonian, unitary, gradient: typing.Union[str, typing.Dict[Variable, Objective]] = None, hessian: typing.Union[str, typing.Dict[typing.Tuple[Variable, Variable], Objective]] = None, initial_values: typing.Dict[typing.Hashable, numbers.Real] = None, variables: typing.List[typing.Hashable] = None, samples: int = None, maxiter: int = 100, backend: str = None, backend_options: dict = None, noise: NoiseModel = None, device: str = None, method: str = "BFGS", tol: float = 1.e-3, method_options: dict = None, method_bounds: typing.Dict[typing.Hashable, numbers.Real] = None, method_constraints=None, silent: bool = False, save_history: bool = True, *args, **kwargs) -> SciPyResults: """ calls the local optimize_scipy scipy funtion instead and pass down the objective construction down Parameters ---------- objective: Objective : The tequila objective to optimize gradient: typing.Union[str, typing.Dict[Variable, Objective], None] : Default value = None): '2-point', 'cs' or '3-point' for numerical gradient evaluation (does not work in combination with all optimizers), dictionary of variables and tequila objective to define own gradient, None for automatic construction (default) Other options include 'qng' to use the quantum natural gradient. hessian: typing.Union[str, typing.Dict[Variable, Objective], None], optional: '2-point', 'cs' or '3-point' for numerical gradient evaluation (does not work in combination with all optimizers), dictionary (keys:tuple of variables, values:tequila objective) to define own gradient, None for automatic construction (default) initial_values: typing.Dict[typing.Hashable, numbers.Real], optional: Initial values as dictionary of Hashable types (variable keys) and floating point numbers. If given None they will all be set to zero variables: typing.List[typing.Hashable], optional: List of Variables to optimize samples: int, optional: samples/shots to take in every run of the quantum circuits (None activates full wavefunction simulation) maxiter: int : (Default value = 100): max iters to use. backend: str, optional: Simulator backend, will be automatically chosen if set to None backend_options: dict, optional: Additional options for the backend Will be unpacked and passed to the compiled objective in every call noise: NoiseModel, optional: a NoiseModel to apply to all expectation values in the objective. method: str : (Default = "BFGS"): Optimization method (see scipy documentation, or 'available methods') tol: float : (Default = 1.e-3): Convergence tolerance for optimization (see scipy documentation) method_options: dict, optional: Dictionary of options (see scipy documentation) method_bounds: typing.Dict[typing.Hashable, typing.Tuple[float, float]], optional: bounds for the variables (see scipy documentation) method_constraints: optional: (see scipy documentation silent: bool : No printout if True save_history: bool: Save the history throughout the optimization Returns ------- SciPyReturnType: the results of optimization """ if isinstance(gradient, dict) or hasattr(gradient, "items"): if all([isinstance(x, Objective) for x in gradient.values()]): gradient = format_variable_dictionary(gradient) if isinstance(hessian, dict) or hasattr(hessian, "items"): if all([isinstance(x, Objective) for x in hessian.values()]): hessian = {(assign_variable(k[0]), assign_variable([k[1]])): v for k, v in hessian.items()} method_bounds = format_variable_dictionary(method_bounds) # set defaults optimizer = optimize_scipy(save_history=save_history, maxiter=maxiter, method=method, method_options=method_options, method_bounds=method_bounds, method_constraints=method_constraints, silent=silent, backend=backend, backend_options=backend_options, device=device, samples=samples, noise_model=noise, tol=tol, *args, **kwargs) if initial_values is not None: initial_values = {assign_variable(k): v for k, v in initial_values.items()} return optimizer(Hamiltonian, unitary, gradient=gradient, hessian=hessian, initial_values=initial_values, variables=variables, *args, **kwargs)
24,489
42.732143
144
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.7/energy_optimization.py
import tequila as tq import numpy as np from tequila.objective.objective import Variable import openfermion from hacked_openfermion_qubit_operator import ParamQubitHamiltonian from typing import Union from vqe_utils import convert_PQH_to_tq_QH, convert_tq_QH_to_PQH,\ fold_unitary_into_hamiltonian from grad_hacked import grad from scipy_optimizer import minimize import scipy import random # guess we could substitute that with numpy.random #TODO import argparse import pickle as pk import sys sys.path.insert(0, '../../../') #sys.path.insert(0, '../') # This needs to be properly integrated somewhere else at some point # from tn_update.qq import contract_energy, optimize_wavefunctions from tn_update.my_mpo import * from tn_update.wfn_optimization import contract_energy_mpo, optimize_wavefunctions_mpo, initialize_wfns_randomly def energy_from_wfn_opti(hamiltonian: tq.QubitHamiltonian, n_qubits: int, guess_wfns=None, TOL=1e-4) -> tuple: ''' Get energy using a tensornetwork based method ~ power method (here as blackbox) ''' d = int(2**(n_qubits/2)) # Build MPO h_mpo = MyMPO(hamiltonian=hamiltonian, n_qubits=n_qubits, maxdim=500) h_mpo.make_mpo_from_hamiltonian() # Optimize wavefunctions based on random guess out = None it = 0 while out is None: # Set up random initial guesses for subsystems it += 1 if guess_wfns is None: psiL_rand = initialize_wfns_randomly(d, n_qubits//2) psiR_rand = initialize_wfns_randomly(d, n_qubits//2) else: psiL_rand = guess_wfns[0] psiR_rand = guess_wfns[1] out = optimize_wavefunctions_mpo(h_mpo, psiL_rand, psiR_rand, TOL=TOL, silent=True) energy_rand = out[0] optimal_wfns = [out[1], out[2]] return energy_rand, optimal_wfns def combine_two_clusters(H: tq.QubitHamiltonian, subsystems: list, circ_list: list) -> float: ''' E = nuc_rep + \sum_j c_j <0_A | U_A+ sigma_j|A U_A | 0_A><0_B | U_B+ sigma_j|B U_B | 0_B> i ) Split up Hamiltonian into vector c = [c_j], all sigmas of system A and system B ii ) Two vectors of ExpectationValues E_A=[E(U_A, sigma_j|A)], E_B=[E(U_B, sigma_j|B)] iii) Minimize vectors from ii) iv ) Perform weighted sum \sum_j c_[j] E_A[j] E_B[j] result = nuc_rep + iv) Finishing touch inspired by private tequila-repo / pair-separated objective This is still rather inefficient/unoptimized Can still prune out near-zero coefficients c_j ''' objective = 0.0 n_subsystems = len(subsystems) # Over all Paulistrings in the Hamiltonian for p_index, pauli in enumerate(H.paulistrings): # Gather coefficient coeff = pauli.coeff.real # Empty dictionary for operations: # to be filled with another dictionary per subsystem, where then # e.g. X(0)Z(1)Y(2)X(4) and subsystems=[[0,1,2],[3,4,5]] # -> ops={ 0: {0: 'X', 1: 'Z', 2: 'Y'}, 1: {4: 'X'} } ops = {} for s_index, sys in enumerate(subsystems): for k, v in pauli.items(): if k in sys: if s_index in ops: ops[s_index][k] = v else: ops[s_index] = {k: v} # If no ops gathered -> identity -> nuclear repulsion if len(ops) == 0: #print ("this should only happen ONCE") objective += coeff # If not just identity: # add objective += c_j * prod_subsys( < Paulistring_j_subsys >_{U_subsys} ) elif len(ops) > 0: obj_tmp = coeff for s_index, sys_pauli in ops.items(): #print (s_index, sys_pauli) H_tmp = QubitHamiltonian.from_paulistrings(PauliString(data=sys_pauli)) E_tmp = ExpectationValue(U=circ_list[s_index], H=H_tmp) obj_tmp *= E_tmp objective += obj_tmp initial_values = {k: 0.0 for k in objective.extract_variables()} random_initial_values = {k: 1e-2*np.random.uniform(-1, 1) for k in objective.extract_variables()} method = 'bfgs' # 'bfgs' # 'l-bfgs-b' # 'cobyla' # 'slsqp' curr_res = tq.minimize(method=method, objective=objective, initial_values=initial_values, gradient='two-point', backend='qulacs', method_options={"finite_diff_rel_step": 1e-3}) return curr_res.energy def energy_from_tq_qcircuit(hamiltonian: Union[tq.QubitHamiltonian, ParamQubitHamiltonian], n_qubits: int, circuit = Union[list, tq.QCircuit], subsystems: list = [[0,1,2,3,4,5]], initial_guess = None)-> tuple: ''' Get minimal energy using tequila ''' result = None # If only one circuit handed over, just run simple VQE if isinstance(circuit, list) and len(circuit) == 1: circuit = circuit[0] if isinstance(circuit, tq.QCircuit): if isinstance(hamiltonian, tq.QubitHamiltonian): E = tq.ExpectationValue(H=hamiltonian, U=circuit) if initial_guess is None: initial_angles = {k: 0.0 for k in E.extract_variables()} else: initial_angles = initial_guess #print ("optimizing non-param...") result = tq.minimize(objective=E, method='l-bfgs-b', silent=True, backend='qulacs', initial_values=initial_angles) #gradient='two-point', backend='qulacs', #method_options={"finite_diff_rel_step": 1e-4}) elif isinstance(hamiltonian, ParamQubitHamiltonian): if initial_guess is None: raise Exception("Need to provide initial guess for this to work.") initial_angles = None else: initial_angles = initial_guess #print ("optimizing param...") result = minimize(hamiltonian, circuit, method='bfgs', initial_values=initial_angles, backend="qulacs", silent=True) # If more circuits handed over, assume subsystems else: # TODO!! implement initial guess for the combine_two_clusters thing #print ("Should not happen for now...") result = combine_two_clusters(hamiltonian, subsystems, circuit) return result.energy, result.angles def mixed_optimization(hamiltonian: ParamQubitHamiltonian, n_qubits: int, initial_guess: Union[dict, list]=None, init_angles: list=None): ''' Minimizes energy using wfn opti and a parametrized Hamiltonian min_{psi, theta fixed} <psi | H(theta) | psi> --> min_{t, p fixed} <p | H(t) | p> ^---------------------------------------------------^ until convergence ''' energy, optimal_state = None, None H_qh = convert_PQH_to_tq_QH(hamiltonian) var_keys, H_derivs = H_qh._construct_derivatives() print("var keys", var_keys, flush=True) print('var dict', init_angles, flush=True) # if not init_angles: # var_vals = [0. for i in range(len(var_keys))] # initialize with 0 # else: # var_vals = init_angles def build_variable_dict(keys, values): assert(len(keys)==len(values)) out = dict() for idx, key in enumerate(keys): out[key] = complex(values[idx]) return out var_dict = init_angles var_vals = [*init_angles.values()] assert(build_variable_dict(var_keys, var_vals) == var_dict) def wrap_energy_eval(psi): ''' like energy_from_wfn_opti but instead of optimize get inner product ''' def energy_eval_fn(x): var_dict = build_variable_dict(var_keys, x) H_qh_fix = H_qh(var_dict) H_mpo = MyMPO(hamiltonian=H_qh_fix, n_qubits=n_qubits, maxdim=500) H_mpo.make_mpo_from_hamiltonian() return contract_energy_mpo(H_mpo, psi[0], psi[1]) return energy_eval_fn def wrap_gradient_eval(psi): ''' call derivatives with updated variable list ''' def gradient_eval_fn(x): variables = build_variable_dict(var_keys, x) deriv_expectations = H_derivs.values() # list of ParamQubitHamiltonian's deriv_qhs = [convert_PQH_to_tq_QH(d) for d in deriv_expectations] deriv_qhs = [d(variables) for d in deriv_qhs] # list of tq.QubitHamiltonian's # print(deriv_qhs) deriv_mpos = [MyMPO(hamiltonian=d, n_qubits=n_qubits, maxdim=500)\ for d in deriv_qhs] # print(deriv_mpos[0].n_qubits) for d in deriv_mpos: d.make_mpo_from_hamiltonian() # deriv_mpos = [d.make_mpo_from_hamiltonian() for d in deriv_mpos] return np.asarray([contract_energy_mpo(d, psi[0], psi[1]) for d in deriv_mpos]) return gradient_eval_fn def do_wfn_opti(values, guess_wfns, TOL): # H_qh = H_qh(H_vars) var_dict = build_variable_dict(var_keys, values) en, psi = energy_from_wfn_opti(H_qh(var_dict), n_qubits=n_qubits, guess_wfns=guess_wfns, TOL=TOL) return en, psi def do_param_opti(psi, x0): result = scipy.optimize.minimize(fun=wrap_energy_eval(psi), jac=wrap_gradient_eval(psi), method='bfgs', x0=x0, options={'maxiter': 4}) # print(result) return result e_prev, psi_prev = 123., None # print("iguess", initial_guess) e_curr, psi_curr = do_wfn_opti(var_vals, initial_guess, 1e-5) print('first eval', e_curr, flush=True) def converged(e_prev, e_curr, TOL=1e-4): return True if np.abs(e_prev-e_curr) < TOL else False it = 0 var_prev = var_vals print("vars before comp", var_prev, flush=True) while not converged(e_prev, e_curr) and it < 50: e_prev, psi_prev = e_curr, psi_curr # print('before param opti') res = do_param_opti(psi_curr, var_prev) var_curr = res['x'] print('curr vars', var_curr, flush=True) e_curr = res['fun'] print('en before wfn opti', e_curr, flush=True) # print("iiiiiguess", psi_prev) e_curr, psi_curr = do_wfn_opti(var_curr, psi_prev, 1e-3) print('en after wfn opti', e_curr, flush=True) it += 1 print('at iteration', it, flush=True) return e_curr, psi_curr # optimize parameters with fixed wavefunction # define/wrap energy function - given |p>, evaluate <p|H(t)|p> ''' def wrap_gradient(objective: typing.Union[Objective, QTensor], no_compile=False, *args, **kwargs): def gradient_fn(variable: Variable = None): return grad(objective: typing.Union[Objective, QTensor], variable: Variable = None, no_compile=False, *args, **kwargs) return grad_fn ''' def minimize_energy(hamiltonian: Union[ParamQubitHamiltonian, tq.QubitHamiltonian], n_qubits: int, type_energy_eval: str='wfn', cluster_circuit: tq.QCircuit=None, initial_guess=None, initial_mixed_angles: dict=None) -> float: ''' Minimizes energy functional either according a power-method inspired shortcut ('wfn') or using a unitary circuit ('qc') ''' if type_energy_eval == 'wfn': if isinstance(hamiltonian, tq.QubitHamiltonian): energy, optimal_state = energy_from_wfn_opti(hamiltonian, n_qubits, initial_guess) elif isinstance(hamiltonian, ParamQubitHamiltonian): init_angles = initial_mixed_angles energy, optimal_state = mixed_optimization(hamiltonian=hamiltonian, n_qubits=n_qubits, initial_guess=initial_guess, init_angles=init_angles) elif type_energy_eval == 'qc': if cluster_circuit is None: raise Exception("Need to hand over circuit!") energy, optimal_state = energy_from_tq_qcircuit(hamiltonian, n_qubits, cluster_circuit, [[0,1,2,3],[4,5,6,7]], initial_guess) else: raise Exception("Option not implemented!") return energy, optimal_state
12,457
43.021201
225
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.7/parallel_annealing.py
import tequila as tq import multiprocessing import copy from time import sleep from mutation_options import * from pathos.multiprocessing import ProcessingPool as Pool def evolve_population(hamiltonian, type_energy_eval, cluster_circuit, process_id, num_offsprings, actions_ratio, tasks, results): """ This function carries a single step of the simulated annealing on a single member of the generation args: process_id: A unique identifier for each process num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for mutations tasks: multiprocessing queue to pass family_id, instructions and current_fitness family_id: A unique identifier for each family instructions: An object consisting of the instructions in the quantum circuit current_fitness: Current fitness value of the circuit results: multiprocessing queue to pass results back """ #print('[%s] evaluation routine starts' % process_id) while True: try: #getting parameters for mutation and carrying it family_id, instructions, current_fitness = tasks.get() #check if patience has been exhausted if instructions.patience == 0: instructions.reset_to_best() best_child = 0 best_energy = current_fitness new_generations = {} for off_id in range(1, num_offsprings+1): scheduled_ratio = schedule_actions_ratio(epoch=0, steady_ratio=actions_ratio) action = get_action(scheduled_ratio) updated_instructions = copy.deepcopy(instructions) updated_instructions.update_by_action(action) new_fitness, wfn = evaluate_fitness(updated_instructions, hamiltonian, type_energy_eval, cluster_circuit) updated_instructions.set_reference_wfn(wfn) prob_acceptance = get_prob_acceptance(current_fitness, new_fitness, updated_instructions.T, updated_instructions.reference_energy) # need to figure out in case we have two equals new_generations[str(off_id)] = updated_instructions if best_energy > new_fitness: # now two equals -> "first one" is picked best_child = off_id best_energy = new_fitness # decision = np.random.binomial(1, prob_acceptance) # if decision == 0: if best_child == 0: # Add result to the queue instructions.patience -= 1 #print('Reduced patience -- now ' + str(updated_instructions.patience)) if instructions.patience == 0: if instructions.best_previous_instructions: instructions.reset_to_best() else: instructions.update_T() results.put((family_id, instructions, current_fitness)) else: # Add result to the queue if (best_energy < current_fitness): new_generations[str(best_child)].update_best_previous_instructions() new_generations[str(best_child)].update_T() results.put((family_id, new_generations[str(best_child)], best_energy)) except Exception as eeee: #print('[%s] evaluation routine quits' % process_id) #print(eeee) # Indicate finished results.put(-1) break return def evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, num_processors=4, type_energy_eval='wfn', cluster_circuit=None): """ This function does parallel mutation on all the members of the generation and updates the generation args: num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for sampling instructions_dict: A dictionary with the "Instructions" objects the corresponding fitness values as values num_processors: Number of processors to use for parallel run """ # Define IPC manager manager = multiprocessing.Manager() # Define a list (queue) for tasks and computation results tasks = manager.Queue() results = manager.Queue() processes = [] pool = Pool(processes=num_processors) for i in range(num_processors): process_id = 'P%i' % i # Create the process, and connect it to the worker function new_process = multiprocessing.Process(target=evolve_population, args=(hamiltonian, type_energy_eval, cluster_circuit, process_id, num_offsprings, actions_ratio, tasks, results)) # Add new process to the list of processes processes.append(new_process) # Start the process new_process.start() #print("putting tasks") for family_id in instructions_dict: single_task = (family_id, instructions_dict[family_id][0], instructions_dict[family_id][1]) tasks.put(single_task) # Wait while the workers process - change it to something for our case later # sleep(5) multiprocessing.Barrier(num_processors) #print("after barrier") # Quit the worker processes by sending them -1 for i in range(num_processors): tasks.put(-1) # Read calculation results num_finished_processes = 0 while True: # Read result #print("num fin", num_finished_processes) try: family_id, updated_instructions, new_fitness = results.get() instructions_dict[family_id] = (updated_instructions, new_fitness) except: # Process has finished num_finished_processes += 1 if num_finished_processes == num_processors: break for process in processes: process.join() pool.close()
6,456
38.371951
146
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.7/single_thread_annealing.py
import tequila as tq import copy from mutation_options import * def st_evolve_population(hamiltonian, type_energy_eval, cluster_circuit, num_offsprings, actions_ratio, tasks): """ This function carries a single step of the simulated annealing on a single member of the generation args: num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for mutations tasks: a tuple of (family_id, instructions and current_fitness) family_id: A unique identifier for each family instructions: An object consisting of the instructions in the quantum circuit current_fitness: Current fitness value of the circuit """ family_id, instructions, current_fitness = tasks #check if patience has been exhausted if instructions.patience == 0: if instructions.best_previous_instructions: instructions.reset_to_best() best_child = 0 best_energy = current_fitness new_generations = {} for off_id in range(1, num_offsprings+1): scheduled_ratio = schedule_actions_ratio(epoch=0, steady_ratio=actions_ratio) action = get_action(scheduled_ratio) updated_instructions = copy.deepcopy(instructions) updated_instructions.update_by_action(action) new_fitness, wfn = evaluate_fitness(updated_instructions, hamiltonian, type_energy_eval, cluster_circuit) updated_instructions.set_reference_wfn(wfn) prob_acceptance = get_prob_acceptance(current_fitness, new_fitness, updated_instructions.T, updated_instructions.reference_energy) # need to figure out in case we have two equals new_generations[str(off_id)] = updated_instructions if best_energy > new_fitness: # now two equals -> "first one" is picked best_child = off_id best_energy = new_fitness # decision = np.random.binomial(1, prob_acceptance) # if decision == 0: if best_child == 0: # Add result to the queue instructions.patience -= 1 #print('Reduced patience -- now ' + str(updated_instructions.patience)) if instructions.patience == 0: if instructions.best_previous_instructions: instructions.reset_to_best() else: instructions.update_T() results = ((family_id, instructions, current_fitness)) else: # Add result to the queue if (best_energy < current_fitness): new_generations[str(best_child)].update_best_previous_instructions() new_generations[str(best_child)].update_T() results = ((family_id, new_generations[str(best_child)], best_energy)) return results def st_evolve_generation(num_offsprings, actions_ratio, instructions_dict, hamiltonian, type_energy_eval='wfn', cluster_circuit=None): """ This function does a single threas mutation on all the members of the generation and updates the generation args: num_offsprings: Number of offsprings every member has actions_ratio: The ratio of the different actions for sampling instructions_dict: A dictionary with the "Instructions" objects the corresponding fitness values as values """ for family_id in instructions_dict: task = (family_id, instructions_dict[family_id][0], instructions_dict[family_id][1]) results = st_evolve_population(hamiltonian, type_energy_eval, cluster_circuit, num_offsprings, actions_ratio, task) family_id, updated_instructions, new_fitness = results instructions_dict[family_id] = (updated_instructions, new_fitness)
4,005
40.298969
138
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.7/mutation_options.py
import argparse import numpy as np import random import copy import tequila as tq from typing import Union from collections import Counter from time import time from vqe_utils import convert_PQH_to_tq_QH, convert_tq_QH_to_PQH,\ fold_unitary_into_hamiltonian from energy_optimization import minimize_energy global_seed = 1 class Instructions: ''' TODO need to put some documentation here ''' def __init__(self, n_qubits, mu=2.0, sigma=0.4, alpha=0.9, T_0=1.0, beta=0.5, patience=10, max_non_cliffords=0, reference_energy=0., number=None): # hardcoded values for now self.num_non_cliffords = 0 self.max_non_cliffords = max_non_cliffords # ------------------------ self.starting_patience = patience self.patience = patience self.mu = mu self.sigma = sigma self.alpha = alpha self.beta = beta self.T_0 = T_0 self.T = T_0 self.gates = self.get_random_gates(number=number) self.n_qubits = n_qubits self.positions = self.get_random_positions() self.best_previous_instructions = {} self.reference_energy = reference_energy self.best_reference_wfn = None self.noncliff_replacements = {} def _str(self): print(self.gates) print(self.positions) def set_reference_wfn(self, reference_wfn): self.best_reference_wfn = reference_wfn def update_T(self, update_type: str = 'regular', best_temp=None): # Regular update if update_type.lower() == 'regular': self.T = self.alpha * self.T # Temperature update if patience ran out elif update_type.lower() == 'patience': self.T = self.beta*best_temp + (1-self.beta)*self.T_0 def get_random_gates(self, number=None): ''' Randomly generates a list of gates. number indicates the number of gates to generate otherwise, number will be drawn from a log normal distribution ''' mu, sigma = self.mu, self.sigma full_options = ['X','Y','Z','S','H','CX', 'CY', 'CZ','SWAP', 'UCC2c', 'UCC4c', 'UCC2', 'UCC4'] clifford_options = ['X','Y','Z','S','H','CX', 'CY', 'CZ','SWAP', 'UCC2c', 'UCC4c'] #non_clifford_options = ['UCC2', 'UCC4'] # Gate distribution, selecting number of gates to add k = np.random.lognormal(mu, sigma) k = np.int(k) if number is not None: k = number # Selecting gate types gates = None if self.num_non_cliffords < self.max_non_cliffords: gates = random.choices(full_options, k=k) # with replacement else: gates = random.choices(clifford_options, k=k) new_num_non_cliffords = 0 if "UCC2" in gates: new_num_non_cliffords += Counter(gates)["UCC2"] if "UCC4" in gates: new_num_non_cliffords += Counter(gates)["UCC4"] if (new_num_non_cliffords+self.num_non_cliffords) <= self.max_non_cliffords: self.num_non_cliffords += new_num_non_cliffords else: extra_cliffords = (new_num_non_cliffords+self.num_non_cliffords) - self.max_non_cliffords assert(extra_cliffords >= 0) new_gates = random.choices(clifford_options, k=extra_cliffords) for g in new_gates: try: gates[gates.index("UCC4")] = g except: gates[gates.index("UCC2")] = g self.num_non_cliffords = self.max_non_cliffords if k == 1: if gates == "UCC2c" or gates == "UCC4c": gates = get_string_Cliff_ucc(gates) if gates == "UCC2" or gates == "UCC4": gates = get_string_ucc(gates) else: for ind, gate in enumerate(gates): if gate == "UCC2c" or gate == "UCC4c": gates[ind] = get_string_Cliff_ucc(gate) if gate == "UCC2" or gate == "UCC4": gates[ind] = get_string_ucc(gate) return gates def get_random_positions(self, gates=None): ''' Randomly assign gates to qubits. ''' if gates is None: gates = self.gates n_qubits = self.n_qubits single_qubit = ['X','Y','Z','S','H'] # two_qubit = ['CX','CY','CZ', 'SWAP'] two_qubit = ['CX', 'CY', 'CZ', 'SWAP', 'UCC2c', 'UCC2'] four_qubit = ['UCC4c', 'UCC4'] qubits = list(range(0, n_qubits)) q_positions = [] for gate in gates: if gate in four_qubit: p = random.sample(qubits, k=4) if gate in two_qubit: p = random.sample(qubits, k=2) if gate in single_qubit: p = random.sample(qubits, k=1) if "UCC2" in gate: p = random.sample(qubits, k=2) if "UCC4" in gate: p = random.sample(qubits, k=4) q_positions.append(p) return q_positions def delete(self, number=None): ''' Randomly drops some gates from a clifford instruction set if not specified, the number of gates to drop is sampled from a uniform distribution over all the gates ''' gates = copy.deepcopy(self.gates) positions = copy.deepcopy(self.positions) n_qubits = self.n_qubits if number is not None: num_to_drop = number else: num_to_drop = random.sample(range(1,len(gates)-1), k=1)[0] action_indices = random.sample(range(0,len(gates)-1), k=num_to_drop) for index in sorted(action_indices, reverse=True): if "UCC2_" in str(gates[index]) or "UCC4_" in str(gates[index]): self.num_non_cliffords -= 1 del gates[index] del positions[index] self.gates = gates self.positions = positions #print ('deleted {} gates'.format(num_to_drop)) def add(self, number=None): ''' adds a random selection of clifford gates to the end of a clifford instruction set if number is not specified, the number of gates to add will be drawn from a log normal distribution ''' gates = copy.deepcopy(self.gates) positions = copy.deepcopy(self.positions) n_qubits = self.n_qubits added_instructions = self.get_new_instructions(number=number) gates.extend(added_instructions['gates']) positions.extend(added_instructions['positions']) self.gates = gates self.positions = positions #print ('added {} gates'.format(len(added_instructions['gates']))) def change(self, number=None): ''' change a random number of gates and qubit positions in a clifford instruction set if not specified, the number of gates to change is sampled from a uniform distribution over all the gates ''' gates = copy.deepcopy(self.gates) positions = copy.deepcopy(self.positions) n_qubits = self.n_qubits if number is not None: num_to_change = number else: num_to_change = random.sample(range(1,len(gates)), k=1)[0] action_indices = random.sample(range(0,len(gates)-1), k=num_to_change) added_instructions = self.get_new_instructions(number=num_to_change) for i in range(num_to_change): gates[action_indices[i]] = added_instructions['gates'][i] positions[action_indices[i]] = added_instructions['positions'][i] self.gates = gates self.positions = positions #print ('changed {} gates'.format(len(added_instructions['gates']))) # TODO to be debugged! def prune(self): ''' Prune instructions to remove redundant operations: --> first gate should go beyond subsystems (this assumes expressible enough subsystem-ciruits #TODO later -> this needs subsystem information in here! --> 2 subsequent gates that are their respective inverse can be removed #TODO this might change the number of qubits acted on in theory? ''' pass #print ("DEBUG PRUNE FUNCTION!") # gates = copy.deepcopy(self.gates) # positions = copy.deepcopy(self.positions) # for g_index in range(len(gates)-1): # if (gates[g_index] == gates[g_index+1] and not 'S' in gates[g_index])\ # or (gates[g_index] == 'S' and gates[g_index+1] == 'S-dag')\ # or (gates[g_index] == 'S-dag' and gates[g_index+1] == 'S'): # print(len(gates)) # if positions[g_index] == positions[g_index+1]: # self.gates.pop(g_index) # self.positions.pop(g_index) def update_by_action(self, action: str): ''' Updates instruction dictionary -> Either adds, deletes or changes gates ''' if action == 'delete': try: self.delete() # In case there are too few gates to delete except: pass elif action == 'add': self.add() elif action == 'change': self.change() else: raise Exception("Unknown action type " + action + ".") self.prune() def update_best_previous_instructions(self): ''' Overwrites the best previous instructions with the current ones. ''' self.best_previous_instructions['gates'] = copy.deepcopy(self.gates) self.best_previous_instructions['positions'] = copy.deepcopy(self.positions) self.best_previous_instructions['T'] = copy.deepcopy(self.T) def reset_to_best(self): ''' Overwrites the current instructions with best previous ones. ''' #print ('Patience ran out... resetting to best previous instructions.') self.gates = copy.deepcopy(self.best_previous_instructions['gates']) self.positions = copy.deepcopy(self.best_previous_instructions['positions']) self.patience = copy.deepcopy(self.starting_patience) self.update_T(update_type='patience', best_temp=copy.deepcopy(self.best_previous_instructions['T'])) def get_new_instructions(self, number=None): ''' Returns a a clifford instruction set, a dictionary of gates and qubit positions for building a clifford circuit ''' mu = self.mu sigma = self.sigma n_qubits = self.n_qubits instruction = {} gates = self.get_random_gates(number=number) q_positions = self.get_random_positions(gates) assert(len(q_positions) == len(gates)) instruction['gates'] = gates instruction['positions'] = q_positions # instruction['n_qubits'] = n_qubits # instruction['patience'] = patience # instruction['best_previous_options'] = {} return instruction def replace_cg_w_ncg(self, gate_id): ''' replaces a set of Clifford gates with corresponding non-Cliffords ''' print("gates before", self.gates, flush=True) gate = self.gates[gate_id] if gate == 'X': gate = "Rx" elif gate == 'Y': gate = "Ry" elif gate == 'Z': gate = "Rz" elif gate == 'S': gate = "S_nc" #gate = "Rz" elif gate == 'H': gate = "H_nc" # this does not work??????? # gate = "Ry" elif gate == 'CX': gate = "CRx" elif gate == 'CY': gate = "CRy" elif gate == 'CZ': gate = "CRz" elif gate == 'SWAP':#find a way to change this as well pass # gate = "SWAP" elif "UCC2c" in str(gate): pre_gate = gate.split("_")[0] mid_gate = gate.split("_")[-1] gate = pre_gate + "_" + "UCC2" + "_" +mid_gate elif "UCC4c" in str(gate): pre_gate = gate.split("_")[0] mid_gate = gate.split("_")[-1] gate = pre_gate + "_" + "UCC4" + "_" + mid_gate self.gates[gate_id] = gate print("gates after", self.gates, flush=True) def build_circuit(instructions): ''' constructs a tequila circuit from a clifford instruction set ''' gates = instructions.gates q_positions = instructions.positions init_angles = {} clifford_circuit = tq.QCircuit() # for i in range(1, len(gates)): # TODO len(q_positions) not == len(gates) for i in range(len(gates)): if len(q_positions[i]) == 2: q1, q2 = q_positions[i] elif len(q_positions[i]) == 1: q1 = q_positions[i] q2 = None elif not len(q_positions[i]) == 4: raise Exception("q_positions[i] must have length 1, 2 or 4...") if gates[i] == 'X': clifford_circuit += tq.gates.X(q1) if gates[i] == 'Y': clifford_circuit += tq.gates.Y(q1) if gates[i] == 'Z': clifford_circuit += tq.gates.Z(q1) if gates[i] == 'S': clifford_circuit += tq.gates.S(q1) if gates[i] == 'H': clifford_circuit += tq.gates.H(q1) if gates[i] == 'CX': clifford_circuit += tq.gates.CX(q1, q2) if gates[i] == 'CY': #using generators clifford_circuit += tq.gates.S(q2) clifford_circuit += tq.gates.CX(q1, q2) clifford_circuit += tq.gates.S(q2).dagger() if gates[i] == 'CZ': #using generators clifford_circuit += tq.gates.H(q2) clifford_circuit += tq.gates.CX(q1, q2) clifford_circuit += tq.gates.H(q2) if gates[i] == 'SWAP': clifford_circuit += tq.gates.CX(q1, q2) clifford_circuit += tq.gates.CX(q2, q1) clifford_circuit += tq.gates.CX(q1, q2) if "UCC2c" in str(gates[i]) or "UCC4c" in str(gates[i]): clifford_circuit += get_clifford_UCC_circuit(gates[i], q_positions[i]) # NON-CLIFFORD STUFF FROM HERE ON global global_seed if gates[i] == "S_nc": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.S(q1) clifford_circuit += tq.gates.Rz(angle=var_name, target=q1) if gates[i] == "H_nc": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.H(q1) clifford_circuit += tq.gates.Ry(angle=var_name, target=q1) if gates[i] == "Rx": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.X(q1) clifford_circuit += tq.gates.Rx(angle=var_name, target=q1) if gates[i] == "Ry": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0.0 clifford_circuit += tq.gates.Y(q1) clifford_circuit += tq.gates.Ry(angle=var_name, target=q1) if gates[i] == "Rz": global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = 0 clifford_circuit += tq.gates.Z(q1) clifford_circuit += tq.gates.Rz(angle=var_name, target=q1) if gates[i] == "CRx": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = np.pi clifford_circuit += tq.gates.Rx(angle=var_name, target=q2, control=q1) if gates[i] == "CRy": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = np.pi clifford_circuit += tq.gates.Ry(angle=var_name, target=q2, control=q1) if gates[i] == "CRz": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) init_angles[var_name] = np.pi clifford_circuit += tq.gates.Rz(angle=var_name, target=q2, control=q1) def get_ucc_init_angles(gate): angle = None pre_gate = gate.split("_")[0] mid_gate = gate.split("_")[-1] if mid_gate == 'Z': angle = 0. elif mid_gate == 'S': angle = 0. elif mid_gate == 'S-dag': angle = 0. else: raise Exception("This should not happen -- center/mid gate should be Z,S,S_dag.") return angle if "UCC2_" in str(gates[i]) or "UCC4_" in str(gates[i]): uccc_circuit = get_non_clifford_UCC_circuit(gates[i], q_positions[i]) clifford_circuit += uccc_circuit try: var_name = uccc_circuit.extract_variables()[0] init_angles[var_name]= get_ucc_init_angles(gates[i]) except: init_angles = {} return clifford_circuit, init_angles def get_non_clifford_UCC_circuit(gate, positions): """ """ pre_cir_dic = {"X":tq.gates.X, "Y":tq.gates.Y, "H":tq.gates.H, "I":None} pre_gate = gate.split("_")[0] pre_gates = pre_gate.split(*"#") pre_circuit = tq.QCircuit() for i, pos in enumerate(positions): try: pre_circuit += pre_cir_dic[pre_gates[i]](pos) except: pass for i, pos in enumerate(positions[:-1]): pre_circuit += tq.gates.CX(pos, positions[i+1]) global global_seed mid_gate = gate.split("_")[-1] mid_circuit = tq.QCircuit() if mid_gate == "S": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit += tq.gates.S(positions[-1]) mid_circuit += tq.gates.Rz(angle=tq.Variable(var_name), target=positions[-1]) elif mid_gate == "S-dag": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit += tq.gates.S(positions[-1]).dagger() mid_circuit += tq.gates.Rz(angle=tq.Variable(var_name), target=positions[-1]) elif mid_gate == "Z": np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit += tq.gates.Z(positions[-1]) mid_circuit += tq.gates.Rz(angle=tq.Variable(var_name), target=positions[-1]) return pre_circuit + mid_circuit + pre_circuit.dagger() def get_string_Cliff_ucc(gate): """ this function randomly sample basis change and mid circuit elements for a ucc-type clifford circuit and adds it to the gate """ pre_circ_comp = ["X", "Y", "H", "I"] mid_circ_comp = ["S", "S-dag", "Z"] p = None if "UCC2c" in gate: p = random.sample(pre_circ_comp, k=2) elif "UCC4c" in gate: p = random.sample(pre_circ_comp, k=4) pre_gate = "#".join([str(item) for item in p]) mid_gate = random.sample(mid_circ_comp, k=1)[0] return str(pre_gate + "_" + gate + "_" + mid_gate) def get_string_ucc(gate): """ this function randomly sample basis change and mid circuit elements for a ucc-type clifford circuit and adds it to the gate """ pre_circ_comp = ["X", "Y", "H", "I"] p = None if "UCC2" in gate: p = random.sample(pre_circ_comp, k=2) elif "UCC4" in gate: p = random.sample(pre_circ_comp, k=4) pre_gate = "#".join([str(item) for item in p]) mid_gate = str(random.random() * 2 * np.pi) return str(pre_gate + "_" + gate + "_" + mid_gate) def get_clifford_UCC_circuit(gate, positions): """ This function creates an approximate UCC excitation circuit using only clifford Gates """ #pre_circ_comp = ["X", "Y", "H", "I"] pre_cir_dic = {"X":tq.gates.X, "Y":tq.gates.Y, "H":tq.gates.H, "I":None} pre_gate = gate.split("_")[0] pre_gates = pre_gate.split(*"#") #pre_gates = [] #if gate == "UCC2": # pre_gates = random.choices(pre_circ_comp, k=2) #if gate == "UCC4": # pre_gates = random.choices(pre_circ_comp, k=4) pre_circuit = tq.QCircuit() for i, pos in enumerate(positions): try: pre_circuit += pre_cir_dic[pre_gates[i]](pos) except: pass for i, pos in enumerate(positions[:-1]): pre_circuit += tq.gates.CX(pos, positions[i+1]) #mid_circ_comp = ["S", "S-dag", "Z"] #mid_gate = random.sample(mid_circ_comp, k=1)[0] mid_gate = gate.split("_")[-1] mid_circuit = tq.QCircuit() if mid_gate == "S": mid_circuit += tq.gates.S(positions[-1]) elif mid_gate == "S-dag": mid_circuit += tq.gates.S(positions[-1]).dagger() elif mid_gate == "Z": mid_circuit += tq.gates.Z(positions[-1]) return pre_circuit + mid_circuit + pre_circuit.dagger() def get_UCC_circuit(gate, positions): """ This function creates an UCC excitation circuit """ #pre_circ_comp = ["X", "Y", "H", "I"] pre_cir_dic = {"X":tq.gates.X, "Y":tq.gates.Y, "H":tq.gates.H, "I":None} pre_gate = gate.split("_")[0] pre_gates = pre_gate.split(*"#") pre_circuit = tq.QCircuit() for i, pos in enumerate(positions): try: pre_circuit += pre_cir_dic[pre_gates[i]](pos) except: pass for i, pos in enumerate(positions[:-1]): pre_circuit += tq.gates.CX(pos, positions[i+1]) mid_gate_val = gate.split("_")[-1] global global_seed np.random.seed(global_seed) global_seed += 1 var_name = "var"+str(np.random.rand()) mid_circuit = tq.gates.Rz(target=positions[-1], angle=tq.Variable(var_name)) # mid_circ_comp = ["S", "S-dag", "Z"] # mid_gate = random.sample(mid_circ_comp, k=1)[0] # mid_circuit = tq.QCircuit() # if mid_gate == "S": # mid_circuit += tq.gates.S(positions[-1]) # elif mid_gate == "S-dag": # mid_circuit += tq.gates.S(positions[-1]).dagger() # elif mid_gate == "Z": # mid_circuit += tq.gates.Z(positions[-1]) return pre_circuit + mid_circuit + pre_circuit.dagger() def schedule_actions_ratio(epoch: int, action_options: list = ['delete', 'change', 'add'], decay: int = 30, steady_ratio: Union[tuple, list] = [0.2, 0.6, 0.2]) -> list: delete, change, add = tuple(steady_ratio) actions_ratio = [] for action in action_options: if action == 'delete': actions_ratio += [ delete*(1-np.exp(-1*epoch / decay)) ] elif action == 'change': actions_ratio += [ change*(1-np.exp(-1*epoch / decay)) ] elif action == 'add': actions_ratio += [ (1-add)*np.exp(-1*epoch / decay) + add ] else: print('Action type ', action, ' not defined!') # unnecessary for current schedule # if not np.isclose(np.sum(actions_ratio), 1.0): # actions_ratio /= np.sum(actions_ratio) return actions_ratio def get_action(ratio: list = [0.20,0.60,0.20]): ''' randomly chooses an action from delete, change, add ratio denotes the multinomial probabilities ''' choice = np.random.multinomial(n=1, pvals = ratio, size = 1) index = np.where(choice[0] == 1) action_options = ['delete', 'change', 'add'] action = action_options[index[0].item()] return action def get_prob_acceptance(E_curr, E_prev, T, reference_energy): ''' Computes acceptance probability of a certain action based on change in energy ''' delta_E = E_curr - E_prev prob = 0 if delta_E < 0 and E_curr < reference_energy: prob = 1 else: if E_curr < reference_energy: prob = np.exp(-delta_E/T) else: prob = 0 return prob def perform_folding(hamiltonian, circuit): # QubitHamiltonian -> ParamQubitHamiltonian param_hamiltonian = convert_tq_QH_to_PQH(hamiltonian) gates = circuit.gates # Go backwards gates.reverse() for gate in gates: # print("\t folding", gate) param_hamiltonian = (fold_unitary_into_hamiltonian(gate, param_hamiltonian)) # hamiltonian = convert_PQH_to_tq_QH(param_hamiltonian)() hamiltonian = param_hamiltonian return hamiltonian def evaluate_fitness(instructions, hamiltonian: tq.QubitHamiltonian, type_energy_eval: str, cluster_circuit: tq.QCircuit=None) -> tuple: ''' Evaluates fitness=objective=energy given a system for a set of instructions ''' #print ("evaluating fitness") n_qubits = instructions.n_qubits clifford_circuit, init_angles = build_circuit(instructions) # tq.draw(clifford_circuit, backend="cirq") ## TODO check if cluster_circuit is parametrized t0 = time() t1 = None folded_hamiltonian = perform_folding(hamiltonian, clifford_circuit) t1 = time() #print ("\tfolding took ", t1-t0) parametrized = len(clifford_circuit.extract_variables()) > 0 initial_guess = None if not parametrized: folded_hamiltonian = (convert_PQH_to_tq_QH(folded_hamiltonian))() elif parametrized: # TODO clifford_circuit is both ref + rest; so nomenclature is shit here variables = [gate.extract_variables() for gate in clifford_circuit.gates\ if gate.extract_variables()] variables = np.array(variables).flatten().tolist() # TODO this initial_guess is absolutely useless rn and is just causing problems if called initial_guess = { k: 0.1 for k in variables } if instructions.best_reference_wfn is not None: initial_guess = instructions.best_reference_wfn E_new, optimal_state = minimize_energy(hamiltonian=folded_hamiltonian, n_qubits=n_qubits, type_energy_eval=type_energy_eval, cluster_circuit=cluster_circuit, initial_guess=initial_guess,\ initial_mixed_angles=init_angles) t2 = time() #print ("evaluated fitness; comp was ", t2-t1) #print ("current fitness: ", E_new) return E_new, optimal_state
26,497
34.096689
191
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.7/hacked_openfermion_qubit_operator.py
import tequila as tq import sympy import copy #from param_hamiltonian import get_geometry, generate_ucc_ansatz from hacked_openfermion_symbolic_operator import SymbolicOperator # Define products of all Pauli operators for symbolic multiplication. _PAULI_OPERATOR_PRODUCTS = { ('I', 'I'): (1., 'I'), ('I', 'X'): (1., 'X'), ('X', 'I'): (1., 'X'), ('I', 'Y'): (1., 'Y'), ('Y', 'I'): (1., 'Y'), ('I', 'Z'): (1., 'Z'), ('Z', 'I'): (1., 'Z'), ('X', 'X'): (1., 'I'), ('Y', 'Y'): (1., 'I'), ('Z', 'Z'): (1., 'I'), ('X', 'Y'): (1.j, 'Z'), ('X', 'Z'): (-1.j, 'Y'), ('Y', 'X'): (-1.j, 'Z'), ('Y', 'Z'): (1.j, 'X'), ('Z', 'X'): (1.j, 'Y'), ('Z', 'Y'): (-1.j, 'X') } _clifford_h_products = { ('I') : (1., 'I'), ('X') : (1., 'Z'), ('Y') : (-1., 'Y'), ('Z') : (1., 'X') } _clifford_s_products = { ('I') : (1., 'I'), ('X') : (-1., 'Y'), ('Y') : (1., 'X'), ('Z') : (1., 'Z') } _clifford_s_dag_products = { ('I') : (1., 'I'), ('X') : (1., 'Y'), ('Y') : (-1., 'X'), ('Z') : (1., 'Z') } _clifford_cx_products = { ('I', 'I'): (1., 'I', 'I'), ('I', 'X'): (1., 'I', 'X'), ('I', 'Y'): (1., 'Z', 'Y'), ('I', 'Z'): (1., 'Z', 'Z'), ('X', 'I'): (1., 'X', 'X'), ('X', 'X'): (1., 'X', 'I'), ('X', 'Y'): (1., 'Y', 'Z'), ('X', 'Z'): (-1., 'Y', 'Y'), ('Y', 'I'): (1., 'Y', 'X'), ('Y', 'X'): (1., 'Y', 'I'), ('Y', 'Y'): (-1., 'X', 'Z'), ('Y', 'Z'): (1., 'X', 'Y'), ('Z', 'I'): (1., 'Z', 'I'), ('Z', 'X'): (1., 'Z', 'X'), ('Z', 'Y'): (1., 'I', 'Y'), ('Z', 'Z'): (1., 'I', 'Z'), } _clifford_cy_products = { ('I', 'I'): (1., 'I', 'I'), ('I', 'X'): (1., 'Z', 'X'), ('I', 'Y'): (1., 'I', 'Y'), ('I', 'Z'): (1., 'Z', 'Z'), ('X', 'I'): (1., 'X', 'Y'), ('X', 'X'): (-1., 'Y', 'Z'), ('X', 'Y'): (1., 'X', 'I'), ('X', 'Z'): (-1., 'Y', 'X'), ('Y', 'I'): (1., 'Y', 'Y'), ('Y', 'X'): (1., 'X', 'Z'), ('Y', 'Y'): (1., 'Y', 'I'), ('Y', 'Z'): (-1., 'X', 'X'), ('Z', 'I'): (1., 'Z', 'I'), ('Z', 'X'): (1., 'I', 'X'), ('Z', 'Y'): (1., 'Z', 'Y'), ('Z', 'Z'): (1., 'I', 'Z'), } _clifford_cz_products = { ('I', 'I'): (1., 'I', 'I'), ('I', 'X'): (1., 'Z', 'X'), ('I', 'Y'): (1., 'Z', 'Y'), ('I', 'Z'): (1., 'I', 'Z'), ('X', 'I'): (1., 'X', 'Z'), ('X', 'X'): (-1., 'Y', 'Y'), ('X', 'Y'): (-1., 'Y', 'X'), ('X', 'Z'): (1., 'X', 'I'), ('Y', 'I'): (1., 'Y', 'Z'), ('Y', 'X'): (-1., 'X', 'Y'), ('Y', 'Y'): (1., 'X', 'X'), ('Y', 'Z'): (1., 'Y', 'I'), ('Z', 'I'): (1., 'Z', 'I'), ('Z', 'X'): (1., 'I', 'X'), ('Z', 'Y'): (1., 'I', 'Y'), ('Z', 'Z'): (1., 'Z', 'Z'), } COEFFICIENT_TYPES = (int, float, complex, sympy.Expr, tq.Variable) class ParamQubitHamiltonian(SymbolicOperator): @property def actions(self): """The allowed actions.""" return ('X', 'Y', 'Z') @property def action_strings(self): """The string representations of the allowed actions.""" return ('X', 'Y', 'Z') @property def action_before_index(self): """Whether action comes before index in string representations.""" return True @property def different_indices_commute(self): """Whether factors acting on different indices commute.""" return True def renormalize(self): """Fix the trace norm of an operator to 1""" norm = self.induced_norm(2) if numpy.isclose(norm, 0.0): raise ZeroDivisionError('Cannot renormalize empty or zero operator') else: self /= norm def _simplify(self, term, coefficient=1.0): """Simplify a term using commutator and anti-commutator relations.""" if not term: return coefficient, term term = sorted(term, key=lambda factor: factor[0]) new_term = [] left_factor = term[0] for right_factor in term[1:]: left_index, left_action = left_factor right_index, right_action = right_factor # Still on the same qubit, keep simplifying. if left_index == right_index: new_coefficient, new_action = _PAULI_OPERATOR_PRODUCTS[ left_action, right_action] left_factor = (left_index, new_action) coefficient *= new_coefficient # Reached different qubit, save result and re-initialize. else: if left_action != 'I': new_term.append(left_factor) left_factor = right_factor # Save result of final iteration. if left_factor[1] != 'I': new_term.append(left_factor) return coefficient, tuple(new_term) def _clifford_simplify_h(self, qubit): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 for left, right in term: if left == qubit: coeff, new_pauli = _clifford_h_products[right] new_term.append(tuple((left, new_pauli))) else: new_term.append(tuple((left,right))) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self def _clifford_simplify_s(self, qubit): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 for left, right in term: if left == qubit: coeff, new_pauli = _clifford_s_products[right] new_term.append(tuple((left, new_pauli))) else: new_term.append(tuple((left,right))) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self def _clifford_simplify_s_dag(self, qubit): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 for left, right in term: if left == qubit: coeff, new_pauli = _clifford_s_dag_products[right] new_term.append(tuple((left, new_pauli))) else: new_term.append(tuple((left,right))) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self def _clifford_simplify_control_g(self, axis, control_q, target_q): """simplifying the Hamiltonian using the clifford group property""" fold_ham = {} for term in self.terms: #there should be a better way to do this new_term = [] coeff = 1.0 target = "I" control = "I" for left, right in term: if left == control_q: control = right elif left == target_q: target = right else: new_term.append(tuple((left,right))) new_c = "I" new_t = "I" if not (target == "I" and control == "I"): if axis == "X": coeff, new_c, new_t = _clifford_cx_products[control, target] if axis == "Y": coeff, new_c, new_t = _clifford_cy_products[control, target] if axis == "Z": coeff, new_c, new_t = _clifford_cz_products[control, target] if new_c != "I": new_term.append(tuple((control_q, new_c))) if new_t != "I": new_term.append(tuple((target_q, new_t))) new_term = sorted(new_term, key=lambda factor: factor[0]) fold_ham[tuple(new_term)] = coeff*self.terms[term] self.terms = fold_ham return self if __name__ == "__main__": """geometry = get_geometry("H2", 0.714) print(geometry) basis_set = 'sto-3g' ref_anz, uccsd_anz, ham = generate_ucc_ansatz(geometry, basis_set) print(ham) b_ham = tq.grouping.binary_rep.BinaryHamiltonian.init_from_qubit_hamiltonian(ham) c_ham = tq.grouping.binary_rep.BinaryHamiltonian.init_from_qubit_hamiltonian(ham) print(b_ham) print(b_ham.get_binary()) print(b_ham.get_coeff()) param = uccsd_anz.extract_variables() print(param) for term in b_ham.binary_terms: print(term.coeff) term.set_coeff(param[0]) print(term.coeff) print(b_ham.get_coeff()) d_ham = c_ham.to_qubit_hamiltonian() + b_ham.to_qubit_hamiltonian() """ term = [(2,'X'), (0,'Y'), (3, 'Z')] coeff = tq.Variable("a") coeff = coeff *2.j print(coeff) print(type(coeff)) print(coeff({"a":1})) ham = ParamQubitHamiltonian(term= term, coefficient=coeff) print(ham.terms) print(str(ham)) for term in ham.terms: print(ham.terms[term]({"a":1,"b":2})) term = [(2,'X'), (0,'Z'), (3, 'Z')] coeff = tq.Variable("b") print(coeff({"b":1})) b_ham = ParamQubitHamiltonian(term= term, coefficient=coeff) print(b_ham.terms) print(str(b_ham)) for term in b_ham.terms: print(b_ham.terms[term]({"a":1,"b":2})) coeff = tq.Variable("a")*tq.Variable("b") print(coeff) print(coeff({"a":1,"b":2})) ham *= b_ham print(ham.terms) print(str(ham)) for term in ham.terms: coeff = (ham.terms[term]) print(coeff) print(coeff({"a":1,"b":2})) ham = ham*2. print(ham.terms) print(str(ham))
9,918
29.614198
85
py
partitioning-with-cliffords
partitioning-with-cliffords-main/data/h2/h2_bl_1.7/HEA.py
import tequila as tq import numpy as np from tequila import gates as tq_g from tequila.objective.objective import Variable def generate_HEA(num_qubits, circuit_id=11, num_layers=1): """ This function generates different types of hardware efficient circuits as in this paper https://onlinelibrary.wiley.com/doi/full/10.1002/qute.201900070 param: num_qubits (int) -> the number of qubits in the circuit param: circuit_id (int) -> the type of hardware efficient circuit param: num_layers (int) -> the number of layers of the HEA input: num_qubits -> 4 circuit_id -> 11 num_layers -> 1 returns: ansatz (tq.QCircuit()) -> a circuit as shown below 0: ───Ry(0.318309886183791*pi*f((y0,))_0)───Rz(0.318309886183791*pi*f((z0,))_1)───@───────────────────────────────────────────────────────────────────────────────────── │ 1: ───Ry(0.318309886183791*pi*f((y1,))_2)───Rz(0.318309886183791*pi*f((z1,))_3)───X───Ry(0.318309886183791*pi*f((y4,))_8)────Rz(0.318309886183791*pi*f((z4,))_9)────@─── │ 2: ───Ry(0.318309886183791*pi*f((y2,))_4)───Rz(0.318309886183791*pi*f((z2,))_5)───@───Ry(0.318309886183791*pi*f((y5,))_10)───Rz(0.318309886183791*pi*f((z5,))_11)───X─── │ 3: ───Ry(0.318309886183791*pi*f((y3,))_6)───Rz(0.318309886183791*pi*f((z3,))_7)───X───────────────────────────────────────────────────────────────────────────────────── """ circuit = tq.QCircuit() qubits = [i for i in range(num_qubits)] if circuit_id == 1: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 2: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.CNOT(target=qubit, control=qubits[ind]) return circuit elif circuit_id == 3: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=qubit, control=qubits[ind]) count += 1 return circuit elif circuit_id == 4: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=qubit, control=qubits[ind]) count += 1 return circuit elif circuit_id == 5: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): for target in qubits: if control != target: variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=target, control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 6: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=qubits[ind+1], control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("cz"+str(count)) circuit += tq_g.Rz(angle = variable,target=qubits[ind+1], control=control) count += 1 return circuit elif circuit_id == 7: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): for target in qubits: if control != target: variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=target, control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 8: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=qubits[ind+1], control=control) count += 1 for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("cx"+str(count)) circuit += tq_g.Rx(angle = variable,target=qubits[ind+1], control=control) count += 1 return circuit elif circuit_id == 9: count = 0 for _ in range(num_layers): for qubit in qubits: circuit += tq_g.H(qubit) for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.Z(target=qubit, control=qubits[ind]) for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 10: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.Z(target=qubit, control=qubits[ind]) circuit += tq_g.Z(target=qubits[0], control=qubits[-1]) for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 return circuit elif circuit_id == 11: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: circuit += tq_g.X(target=qubits[ind+1], control=control) for ind, qubit in enumerate(qubits[1:-1]): variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: circuit += tq_g.X(target=qubits[ind+1], control=control) return circuit elif circuit_id == 12: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: circuit += tq_g.Z(target=qubits[ind+1], control=control) for ind, control in enumerate(qubits[1:-1]): variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = control) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = control) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: circuit += tq_g.Z(target=qubits[ind+1], control=control) return circuit elif circuit_id == 13: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubit, control=qubits[ind]) count += 1 variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubits[0], control=qubits[-1]) count += 1 for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=qubit, target=qubits[ind]) count += 1 variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=qubits[0], target=qubits[-1]) count += 1 return circuit elif circuit_id == 14: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubit, control=qubits[ind]) count += 1 variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubits[0], control=qubits[-1]) count += 1 for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=qubit, target=qubits[ind]) count += 1 variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=qubits[0], target=qubits[-1]) count += 1 return circuit elif circuit_id == 15: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.X(target=qubit, control=qubits[ind]) circuit += tq_g.X(control=qubits[-1], target=qubits[0]) for qubit in qubits: variable = Variable("y"+str(count)) circuit += tq_g.Ry(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[1:]): circuit += tq_g.X(control=qubit, target=qubits[ind]) circuit += tq_g.X(target=qubits[-1], control=qubits[0]) return circuit elif circuit_id == 16: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=control, target=qubits[ind+1]) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, control=control, target=qubits[ind+1]) count += 1 return circuit elif circuit_id == 17: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, control in enumerate(qubits): if ind % 2 == 0: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=control, target=qubits[ind+1]) count += 1 for ind, control in enumerate(qubits[:-1]): if ind % 2 != 0: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, control=control, target=qubits[ind+1]) count += 1 return circuit elif circuit_id == 18: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[:-1]): variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubit, control=qubits[ind+1]) count += 1 variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target=qubits[-1], control=qubits[0]) count += 1 return circuit elif circuit_id == 19: count = 0 for _ in range(num_layers): for qubit in qubits: variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target = qubit) variable = Variable("z"+str(count)) circuit += tq_g.Rz(angle=variable, target = qubit) count += 1 for ind, qubit in enumerate(qubits[:-1]): variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubit, control=qubits[ind+1]) count += 1 variable = Variable("x"+str(count)) circuit += tq_g.Rx(angle=variable, target=qubits[-1], control=qubits[0]) count += 1 return circuit
18,425
45.530303
172
py