code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def _check_and_send(self): """Check whether a qubit pipeline must be sent on and, if so, optimize the pipeline and then send it on.""" # NB: self.optimize(i) modifies self._l for i in self._l: # pylint: disable=consider-using-dict-items if ( len(self._l[i]) >= self._cache_size or len(self._l[i]) > 0 and isinstance(self._l[i][-1].gate, FastForwardingGate) ): self._optimize(i) if len(self._l[i]) >= self._cache_size and not isinstance(self._l[i][-1].gate, FastForwardingGate): self._send_qubit_pipeline(i, len(self._l[i]) - self._cache_size + 1) elif len(self._l[i]) > 0 and isinstance(self._l[i][-1].gate, FastForwardingGate): self._send_qubit_pipeline(i, len(self._l[i])) new_dict = {} for idx, _l in self._l.items(): if len(_l) > 0: new_dict[idx] = _l self._l = new_dict
Check whether a qubit pipeline must be sent on and, if so, optimize the pipeline and then send it on.
_check_and_send
python
ProjectQ-Framework/ProjectQ
projectq/cengines/_optimize.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_optimize.py
Apache-2.0
def _cache_cmd(self, cmd): """Cache a command, i.e., inserts it into the command lists of all qubits involved.""" # are there qubit ids that haven't been added to the list? idlist = [qubit.id for sublist in cmd.all_qubits for qubit in sublist] # add gate command to each of the qubits involved for qubit_id in idlist: if qubit_id not in self._l: self._l[qubit_id] = [] self._l[qubit_id] += [cmd] self._check_and_send()
Cache a command, i.e., inserts it into the command lists of all qubits involved.
_cache_cmd
python
ProjectQ-Framework/ProjectQ
projectq/cengines/_optimize.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_optimize.py
Apache-2.0
def receive(self, command_list): """ Receive a list of commands. Receive commands from the previous engine and cache them. If a flush gate arrives, the entire buffer is sent on. """ for cmd in command_list: if cmd.gate == FlushGate(): # flush gate --> optimize and flush # NB: self.optimize(i) modifies self._l for idx in self._l: # pylint: disable=consider-using-dict-items self._optimize(idx) self._send_qubit_pipeline(idx, len(self._l[idx])) new_dict = {} for idx, _l in self._l.items(): if len(_l) > 0: # pragma: no cover new_dict[idx] = _l self._l = new_dict if self._l: # pragma: no cover raise RuntimeError('Internal compiler error: qubits remaining in LocalOptimizer after a flush!') self.send([cmd]) else: self._cache_cmd(cmd)
Receive a list of commands. Receive commands from the previous engine and cache them. If a flush gate arrives, the entire buffer is sent on.
receive
python
ProjectQ-Framework/ProjectQ
projectq/cengines/_optimize.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_optimize.py
Apache-2.0
def __init__(self, connectivity): """ Initialize the engine. Args: connectivity (set): Set of tuples (c, t) where if (c, t) is an element of the set means that a CNOT can be performed between the physical ids (c, t) with c being the control and t being the target qubit. """ super().__init__() self.connectivity = connectivity
Initialize the engine. Args: connectivity (set): Set of tuples (c, t) where if (c, t) is an element of the set means that a CNOT can be performed between the physical ids (c, t) with c being the control and t being the target qubit.
__init__
python
ProjectQ-Framework/ProjectQ
projectq/cengines/_swapandcnotflipper.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_swapandcnotflipper.py
Apache-2.0
def _needs_flipping(self, cmd): """ Return True if cmd is a CNOT which needs to be flipped around. Args: cmd (Command): Command to check """ if not self._is_cnot(cmd): return False target = cmd.qubits[0][0].id control = cmd.control_qubits[0].id is_possible = (control, target) in self.connectivity if not is_possible and (target, control) not in self.connectivity: raise RuntimeError(f"The provided connectivity does not allow to execute the CNOT gate {str(cmd)}.") return not is_possible
Return True if cmd is a CNOT which needs to be flipped around. Args: cmd (Command): Command to check
_needs_flipping
python
ProjectQ-Framework/ProjectQ
projectq/cengines/_swapandcnotflipper.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_swapandcnotflipper.py
Apache-2.0
def receive(self, command_list): """ Receive a list of commands. Receive a command list and if the command is a CNOT gate, it flips it using Hadamard gates if necessary; if it is a Swap gate, it decomposes it using 3 CNOTs. All other gates are simply sent to the next engine. Args: command_list (list of Command objects): list of commands to receive. """ for cmd in command_list: if self._needs_flipping(cmd): self._send_cnot(cmd, cmd.control_qubits, cmd.qubits[0], True) elif self._is_swap(cmd): qubits = [qb for qr in cmd.qubits for qb in qr] ids = [qb.id for qb in qubits] if len(ids) != 2: raise RuntimeError('Swap gate is a 2-qubit gate!') if tuple(ids) in self.connectivity: control = [qubits[0]] target = [qubits[1]] elif tuple(reversed(ids)) in self.connectivity: control = [qubits[1]] target = [qubits[0]] else: raise RuntimeError(f"The provided connectivity does not allow to execute the Swap gate {str(cmd)}.") self._send_cnot(cmd, control, target) self._send_cnot(cmd, target, control, True) self._send_cnot(cmd, control, target) else: self.next_engine.receive([cmd])
Receive a list of commands. Receive a command list and if the command is a CNOT gate, it flips it using Hadamard gates if necessary; if it is a Swap gate, it decomposes it using 3 CNOTs. All other gates are simply sent to the next engine. Args: command_list (list of Command objects): list of commands to receive.
receive
python
ProjectQ-Framework/ProjectQ
projectq/cengines/_swapandcnotflipper.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_swapandcnotflipper.py
Apache-2.0
def __init__(self, tags=None): """ Initialize a TagRemover object. Args: tags: A list of meta tag classes (e.g., [ComputeTag, UncomputeTag]) denoting the tags to remove """ super().__init__() if not tags: self._tags = [ComputeTag, UncomputeTag] elif isinstance(tags, list): self._tags = tags else: raise TypeError(f'tags should be a list! Got: {tags}')
Initialize a TagRemover object. Args: tags: A list of meta tag classes (e.g., [ComputeTag, UncomputeTag]) denoting the tags to remove
__init__
python
ProjectQ-Framework/ProjectQ
projectq/cengines/_tagremover.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_tagremover.py
Apache-2.0
def receive(self, command_list): """ Receive a list of commands. Receive a list of commands from the previous engine, remove all tags which are an instance of at least one of the meta tags provided in the constructor, and then send them on to the next compiler engine. Args: command_list (list<Command>): List of commands to receive and then (after removing tags) send on. """ for cmd in command_list: for tag in self._tags: cmd.tags = [t for t in cmd.tags if not isinstance(t, tag)] self.send([cmd])
Receive a list of commands. Receive a list of commands from the previous engine, remove all tags which are an instance of at least one of the meta tags provided in the constructor, and then send them on to the next compiler engine. Args: command_list (list<Command>): List of commands to receive and then (after removing tags) send on.
receive
python
ProjectQ-Framework/ProjectQ
projectq/cengines/_tagremover.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_tagremover.py
Apache-2.0
def receive(self, command_list): """ Receive a list of commands. Receive a command list and, for each command, stores it inside the cache before sending it to the next compiler engine. Args: command_list (list of Command objects): list of commands to receive. """ for cmd in command_list: if not cmd.gate == FlushGate(): self.cache_cmd(cmd) if not self.is_last_engine: self.send(command_list)
Receive a list of commands. Receive a command list and, for each command, stores it inside the cache before sending it to the next compiler engine. Args: command_list (list of Command objects): list of commands to receive.
receive
python
ProjectQ-Framework/ProjectQ
projectq/cengines/_testengine.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_testengine.py
Apache-2.0
def __str__(self): """Return a string representation of the object.""" string = "" for qubit_id, _l in enumerate(self._l): string += f"Qubit {qubit_id} : " for command in self._l[qubit_id]: string += f"{str(command)}, " string = f"{string[:-2]}\n" return string
Return a string representation of the object.
__str__
python
ProjectQ-Framework/ProjectQ
projectq/cengines/_testengine.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_testengine.py
Apache-2.0
def __init__(self, save_commands=False): """ Initialize a DummyEngine. Args: save_commands (default = False): If True, commands are saved in self.received_commands. """ super().__init__() self.save_commands = save_commands self.received_commands = []
Initialize a DummyEngine. Args: save_commands (default = False): If True, commands are saved in self.received_commands.
__init__
python
ProjectQ-Framework/ProjectQ
projectq/cengines/_testengine.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_testengine.py
Apache-2.0
def receive(self, command_list): """ Receive a list of commands. Receive a command list and, for each command, stores it internally if requested before sending it to the next compiler engine. Args: command_list (list of Command objects): list of commands to receive. """ if self.save_commands: self.received_commands.extend(command_list) if not self.is_last_engine: self.send(command_list)
Receive a list of commands. Receive a command list and, for each command, stores it internally if requested before sending it to the next compiler engine. Args: command_list (list of Command objects): list of commands to receive.
receive
python
ProjectQ-Framework/ProjectQ
projectq/cengines/_testengine.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_testengine.py
Apache-2.0
def __init__( # pylint: disable=too-many-arguments self, num_rows, num_columns, mapped_ids_to_backend_ids=None, storage=1000, optimization_function=return_swap_depth, num_optimization_steps=50, ): """ Initialize a GridMapper compiler engine. Args: num_rows(int): Number of rows in the grid num_columns(int): Number of columns in the grid. mapped_ids_to_backend_ids(dict): Stores a mapping from mapped ids which are 0,...,self.num_qubits-1 in row-major order on the grid to the corresponding qubit ids of the backend. Key: mapped id. Value: corresponding backend id. Default is None which means backend ids are identical to mapped ids. storage: Number of gates to temporarily store optimization_function: Function which takes a list of swaps and returns a cost value. Mapper chooses a permutation which minimizes this cost. Default optimizes for circuit depth. num_optimization_steps(int): Number of different permutations to of the matching to try and minimize the cost. Raises: RuntimeError: if incorrect `mapped_ids_to_backend_ids` parameter """ super().__init__() self.num_rows = num_rows self.num_columns = num_columns self.num_qubits = num_rows * num_columns # Internally we use the mapped ids until sending a command. # Before sending we use this map to translate to backend ids: self._mapped_ids_to_backend_ids = mapped_ids_to_backend_ids if self._mapped_ids_to_backend_ids is None: self._mapped_ids_to_backend_ids = {} for i in range(self.num_qubits): self._mapped_ids_to_backend_ids[i] = i if not (set(self._mapped_ids_to_backend_ids.keys()) == set(range(self.num_qubits))) or not ( len(set(self._mapped_ids_to_backend_ids.values())) == self.num_qubits ): raise RuntimeError("Incorrect mapped_ids_to_backend_ids parameter") self._backend_ids_to_mapped_ids = {} for mapped_id, backend_id in self._mapped_ids_to_backend_ids.items(): self._backend_ids_to_mapped_ids[backend_id] = mapped_id # As we use internally the mapped ids which are in row-major order, # we have an internal current mapping which maps from logical ids to # these mapped ids: self._current_row_major_mapping = deepcopy(self.current_mapping) self.storage = storage self.optimization_function = optimization_function self.num_optimization_steps = num_optimization_steps # Randomness to pick permutations if there are too many. # This creates an own instance of Random in order to not influence # the bound methods of the random module which might be used in other # places. self._rng = random.Random(11) # Storing commands self._stored_commands = [] # Logical qubit ids for which the Allocate gate has already been # processed and sent to the next engine but which are not yet # deallocated: self._currently_allocated_ids = set() # Change between 2D and 1D mappings (2D is a snake like 1D chain) # Note it translates to our mapped ids in row major order and not # backend ids which might be different. self._map_2d_to_1d = {} self._map_1d_to_2d = {} for row_index in range(self.num_rows): for column_index in range(self.num_columns): if row_index % 2 == 0: mapped_id = row_index * self.num_columns + column_index self._map_2d_to_1d[mapped_id] = mapped_id self._map_1d_to_2d[mapped_id] = mapped_id else: mapped_id_2d = row_index * self.num_columns + column_index mapped_id_1d = (row_index + 1) * self.num_columns - column_index - 1 self._map_2d_to_1d[mapped_id_2d] = mapped_id_1d self._map_1d_to_2d[mapped_id_1d] = mapped_id_2d # Statistics: self.num_mappings = 0 self.depth_of_swaps = {} self.num_of_swaps_per_mapping = {}
Initialize a GridMapper compiler engine. Args: num_rows(int): Number of rows in the grid num_columns(int): Number of columns in the grid. mapped_ids_to_backend_ids(dict): Stores a mapping from mapped ids which are 0,...,self.num_qubits-1 in row-major order on the grid to the corresponding qubit ids of the backend. Key: mapped id. Value: corresponding backend id. Default is None which means backend ids are identical to mapped ids. storage: Number of gates to temporarily store optimization_function: Function which takes a list of swaps and returns a cost value. Mapper chooses a permutation which minimizes this cost. Default optimizes for circuit depth. num_optimization_steps(int): Number of different permutations to of the matching to try and minimize the cost. Raises: RuntimeError: if incorrect `mapped_ids_to_backend_ids` parameter
__init__
python
ProjectQ-Framework/ProjectQ
projectq/cengines/_twodmapper.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_twodmapper.py
Apache-2.0
def is_available(self, cmd): """Only allow 1 or two qubit gates.""" num_qubits = 0 for qureg in cmd.all_qubits: num_qubits += len(qureg) return num_qubits <= 2
Only allow 1 or two qubit gates.
is_available
python
ProjectQ-Framework/ProjectQ
projectq/cengines/_twodmapper.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_twodmapper.py
Apache-2.0
def _return_new_mapping(self): """ Return a new mapping of the qubits. It goes through self._saved_commands and tries to find a mapping to apply these gates on a first come first served basis. It reuses the function of a 1D mapper and creates a mapping for a 1D linear chain and then wraps it like a snake onto the square grid. One might create better mappings by specializing this function for a square grid. Returns: A new mapping as a dict. key is logical qubit id, value is mapped id """ # Change old mapping to 1D in order to use LinearChain heuristic if self._current_row_major_mapping: old_mapping_1d = {} for logical_id, mapped_id in self._current_row_major_mapping.items(): old_mapping_1d[logical_id] = self._map_2d_to_1d[mapped_id] else: old_mapping_1d = self._current_row_major_mapping new_mapping_1d = LinearMapper.return_new_mapping( num_qubits=self.num_qubits, cyclic=False, currently_allocated_ids=self._currently_allocated_ids, stored_commands=self._stored_commands, current_mapping=old_mapping_1d, ) new_mapping_2d = {} for logical_id, mapped_id in new_mapping_1d.items(): new_mapping_2d[logical_id] = self._map_1d_to_2d[mapped_id] return new_mapping_2d
Return a new mapping of the qubits. It goes through self._saved_commands and tries to find a mapping to apply these gates on a first come first served basis. It reuses the function of a 1D mapper and creates a mapping for a 1D linear chain and then wraps it like a snake onto the square grid. One might create better mappings by specializing this function for a square grid. Returns: A new mapping as a dict. key is logical qubit id, value is mapped id
_return_new_mapping
python
ProjectQ-Framework/ProjectQ
projectq/cengines/_twodmapper.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_twodmapper.py
Apache-2.0
def _compare_and_swap(self, element0, element1, key): """If swapped (inplace), then return swap operation so that key(element0) < key(element1).""" if key(element0) > key(element1): mapped_id0 = element0.current_column + element0.current_row * self.num_columns mapped_id1 = element1.current_column + element1.current_row * self.num_columns swap_operation = (mapped_id0, mapped_id1) # swap elements but update also current position: tmp_0 = element0.final_row tmp_1 = element0.final_column tmp_2 = element0.row_after_step_1 element0.final_row = element1.final_row element0.final_column = element1.final_column element0.row_after_step_1 = element1.row_after_step_1 element1.final_row = tmp_0 element1.final_column = tmp_1 element1.row_after_step_1 = tmp_2 return swap_operation return None
If swapped (inplace), then return swap operation so that key(element0) < key(element1).
_compare_and_swap
python
ProjectQ-Framework/ProjectQ
projectq/cengines/_twodmapper.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_twodmapper.py
Apache-2.0
def return_swaps( # pylint: disable=too-many-locals,too-many-branches,too-many-statements self, old_mapping, new_mapping, permutation=None ): """ Return the swap operation to change mapping. Args: old_mapping: dict: keys are logical ids and values are mapped qubit ids new_mapping: dict: keys are logical ids and values are mapped qubit ids permutation: list of int from 0, 1, ..., self.num_rows-1. It is used to permute the found perfect matchings. Default is None which keeps the original order. Returns: List of tuples. Each tuple is a swap operation which needs to be applied. Tuple contains the two mapped qubit ids for the Swap. """ if permutation is None: permutation = list(range(self.num_rows)) swap_operations = [] class Position: # pylint: disable=too-few-public-methods """Custom Container.""" def __init__( # pylint: disable=too-many-arguments self, current_row, current_column, final_row, final_column, row_after_step_1=None, ): self.current_row = current_row self.current_column = current_column self.final_row = final_row self.final_column = final_column self.row_after_step_1 = row_after_step_1 # final_positions contains info containers # final_position[i][j] contains info container with # current_row == i and current_column == j final_positions = [[None for i in range(self.num_columns)] for j in range(self.num_rows)] # move qubits which are in both mappings used_mapped_ids = set() for logical_id in old_mapping: if logical_id in new_mapping: used_mapped_ids.add(new_mapping[logical_id]) old_column = old_mapping[logical_id] % self.num_columns old_row = old_mapping[logical_id] // self.num_columns new_column = new_mapping[logical_id] % self.num_columns new_row = new_mapping[logical_id] // self.num_columns info_container = Position( current_row=old_row, current_column=old_column, final_row=new_row, final_column=new_column, ) final_positions[old_row][old_column] = info_container # exchange all remaining None with the not yet used mapped ids all_ids = set(range(self.num_qubits)) not_used_mapped_ids = list(all_ids.difference(used_mapped_ids)) not_used_mapped_ids = sorted(not_used_mapped_ids, reverse=True) for row in range(self.num_rows): for column in range(self.num_columns): if final_positions[row][column] is None: mapped_id = not_used_mapped_ids.pop() new_column = mapped_id % self.num_columns new_row = mapped_id // self.num_columns info_container = Position( current_row=row, current_column=column, final_row=new_row, final_column=new_column, ) final_positions[row][column] = info_container if len(not_used_mapped_ids) > 0: # pragma: no cover raise RuntimeError('Internal compiler error: len(not_used_mapped_ids) > 0') # 1. Assign column_after_step_1 for each element # Matching contains the num_columns matchings matchings = [None for i in range(self.num_rows)] # Build bipartite graph. Nodes are the current columns numbered (0, 1, ...) and the destination columns # numbered with an offset of self.num_columns (0 + offset, 1+offset, ...) graph = nx.Graph() offset = self.num_columns graph.add_nodes_from(range(self.num_columns), bipartite=0) graph.add_nodes_from(range(offset, offset + self.num_columns), bipartite=1) # Add an edge to the graph from (i, j+offset) for every element currently in column i which should go to # column j for the new mapping for row in range(self.num_rows): for column in range(self.num_columns): destination_column = final_positions[row][column].final_column if not graph.has_edge(column, destination_column + offset): graph.add_edge(column, destination_column + offset) # Keep manual track of multiple edges between nodes graph[column][destination_column + offset]['num'] = 1 else: graph[column][destination_column + offset]['num'] += 1 # Find perfect matching, remove those edges from the graph and do it again: for i in range(self.num_rows): top_nodes = range(self.num_columns) matching = nx.bipartite.maximum_matching(graph, top_nodes) matchings[i] = matching # Remove all edges of the current perfect matching for node in range(self.num_columns): if graph[node][matching[node]]['num'] == 1: graph.remove_edge(node, matching[node]) else: graph[node][matching[node]]['num'] -= 1 # permute the matchings: tmp = deepcopy(matchings) for i in range(self.num_rows): matchings[i] = tmp[permutation[i]] # Assign row_after_step_1 for column in range(self.num_columns): for row_after_step_1 in range(self.num_rows): dest_column = matchings[row_after_step_1][column] - offset best_element = None for row in range(self.num_rows): element = final_positions[row][column] if element.row_after_step_1 is not None: continue if element.final_column == dest_column: if best_element is None: best_element = element elif best_element.final_row > element.final_row: best_element = element best_element.row_after_step_1 = row_after_step_1 # 2. Sort inside all the rows swaps = self._sort_within_columns(final_positions=final_positions, key=lambda x: x.row_after_step_1) swap_operations += swaps # 3. Sort inside all the columns swaps = self._sort_within_rows(final_positions=final_positions, key=lambda x: x.final_column) swap_operations += swaps # 4. Sort inside all the rows swaps = self._sort_within_columns(final_positions=final_positions, key=lambda x: x.final_row) swap_operations += swaps return swap_operations
Return the swap operation to change mapping. Args: old_mapping: dict: keys are logical ids and values are mapped qubit ids new_mapping: dict: keys are logical ids and values are mapped qubit ids permutation: list of int from 0, 1, ..., self.num_rows-1. It is used to permute the found perfect matchings. Default is None which keeps the original order. Returns: List of tuples. Each tuple is a swap operation which needs to be applied. Tuple contains the two mapped qubit ids for the Swap.
return_swaps
python
ProjectQ-Framework/ProjectQ
projectq/cengines/_twodmapper.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_twodmapper.py
Apache-2.0
def _send_possible_commands(self): # pylint: disable=too-many-branches """ Send the stored commands possible without changing the mapping. Note: self._current_row_major_mapping (hence also self.current_mapping) must exist already """ active_ids = deepcopy(self._currently_allocated_ids) for logical_id in self._current_row_major_mapping: # So that loop doesn't stop before AllocateGate applied active_ids.add(logical_id) new_stored_commands = [] for i, cmd in enumerate(self._stored_commands): if len(active_ids) == 0: new_stored_commands += self._stored_commands[i:] break if isinstance(cmd.gate, AllocateQubitGate): if cmd.qubits[0][0].id in self._current_row_major_mapping: self._currently_allocated_ids.add(cmd.qubits[0][0].id) mapped_id = self._current_row_major_mapping[cmd.qubits[0][0].id] qb = WeakQubitRef(engine=self, idx=self._mapped_ids_to_backend_ids[mapped_id]) new_cmd = Command( engine=self, gate=AllocateQubitGate(), qubits=([qb],), tags=[LogicalQubitIDTag(cmd.qubits[0][0].id)], ) self.send([new_cmd]) else: new_stored_commands.append(cmd) elif isinstance(cmd.gate, DeallocateQubitGate): if cmd.qubits[0][0].id in active_ids: mapped_id = self._current_row_major_mapping[cmd.qubits[0][0].id] qb = WeakQubitRef(engine=self, idx=self._mapped_ids_to_backend_ids[mapped_id]) new_cmd = Command( engine=self, gate=DeallocateQubitGate(), qubits=([qb],), tags=[LogicalQubitIDTag(cmd.qubits[0][0].id)], ) self._currently_allocated_ids.remove(cmd.qubits[0][0].id) active_ids.remove(cmd.qubits[0][0].id) self._current_row_major_mapping.pop(cmd.qubits[0][0].id) self._current_mapping.pop(cmd.qubits[0][0].id) self.send([new_cmd]) else: new_stored_commands.append(cmd) else: send_gate = True mapped_ids = set() for qureg in cmd.all_qubits: for qubit in qureg: if qubit.id not in active_ids: send_gate = False break mapped_ids.add(self._current_row_major_mapping[qubit.id]) # Check that mapped ids are nearest neighbour on 2D grid if len(mapped_ids) == 2: qb0, qb1 = sorted(mapped_ids) send_gate = False if qb1 - qb0 == self.num_columns: send_gate = True elif qb1 - qb0 == 1 and qb1 % self.num_columns != 0: send_gate = True if send_gate: # Note: This sends the cmd correctly with the backend ids as it looks up the mapping in # self.current_mapping and not our internal mapping self._current_row_major_mapping self._send_cmd_with_mapped_ids(cmd) else: for qureg in cmd.all_qubits: for qubit in qureg: active_ids.discard(qubit.id) new_stored_commands.append(cmd) self._stored_commands = new_stored_commands
Send the stored commands possible without changing the mapping. Note: self._current_row_major_mapping (hence also self.current_mapping) must exist already
_send_possible_commands
python
ProjectQ-Framework/ProjectQ
projectq/cengines/_twodmapper.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_twodmapper.py
Apache-2.0
def _run(self): # pylint: disable=too-many-locals.too-many-branches,too-many-statements """ Create a new mapping and executes possible gates. It first allocates all 0, ..., self.num_qubits-1 mapped qubit ids, if they are not already used because we might need them all for the swaps. Then it creates a new map, swaps all the qubits to the new map, executes all possible gates, and finally deallocates mapped qubit ids which don't store any information. """ num_of_stored_commands_before = len(self._stored_commands) if not self.current_mapping: self.current_mapping = {} else: self._send_possible_commands() if len(self._stored_commands) == 0: return new_row_major_mapping = self._return_new_mapping() # Find permutation of matchings with lowest cost swaps = None lowest_cost = None matchings_numbers = list(range(self.num_rows)) if self.num_optimization_steps <= math.factorial(self.num_rows): permutations = itertools.permutations(matchings_numbers, self.num_rows) else: permutations = [] for _ in range(self.num_optimization_steps): permutations.append(self._rng.sample(matchings_numbers, self.num_rows)) for permutation in permutations: trial_swaps = self.return_swaps( old_mapping=self._current_row_major_mapping, new_mapping=new_row_major_mapping, permutation=permutation, ) if swaps is None: swaps = trial_swaps lowest_cost = self.optimization_function(trial_swaps) elif lowest_cost > self.optimization_function(trial_swaps): swaps = trial_swaps lowest_cost = self.optimization_function(trial_swaps) if swaps: # first mapping requires no swaps # Allocate all mapped qubit ids (which are not already allocated, # i.e., contained in self._currently_allocated_ids) mapped_ids_used = set() for logical_id in self._currently_allocated_ids: mapped_ids_used.add(self._current_row_major_mapping[logical_id]) not_allocated_ids = set(range(self.num_qubits)).difference(mapped_ids_used) for mapped_id in not_allocated_ids: qb = WeakQubitRef(engine=self, idx=self._mapped_ids_to_backend_ids[mapped_id]) cmd = Command(engine=self, gate=AllocateQubitGate(), qubits=([qb],)) self.send([cmd]) # Send swap operations to arrive at new_mapping: for qubit_id0, qubit_id1 in swaps: qb0 = WeakQubitRef(engine=self, idx=self._mapped_ids_to_backend_ids[qubit_id0]) qb1 = WeakQubitRef(engine=self, idx=self._mapped_ids_to_backend_ids[qubit_id1]) cmd = Command(engine=self, gate=Swap, qubits=([qb0], [qb1])) self.send([cmd]) # Register statistics: self.num_mappings += 1 depth = return_swap_depth(swaps) if depth not in self.depth_of_swaps: self.depth_of_swaps[depth] = 1 else: self.depth_of_swaps[depth] += 1 if len(swaps) not in self.num_of_swaps_per_mapping: self.num_of_swaps_per_mapping[len(swaps)] = 1 else: self.num_of_swaps_per_mapping[len(swaps)] += 1 # Deallocate all previously mapped ids which we only needed for the # swaps: mapped_ids_used = set() for logical_id in self._currently_allocated_ids: mapped_ids_used.add(new_row_major_mapping[logical_id]) not_needed_anymore = set(range(self.num_qubits)).difference(mapped_ids_used) for mapped_id in not_needed_anymore: qb = WeakQubitRef(engine=self, idx=self._mapped_ids_to_backend_ids[mapped_id]) cmd = Command(engine=self, gate=DeallocateQubitGate(), qubits=([qb],)) self.send([cmd]) # Change to new map: self._current_row_major_mapping = new_row_major_mapping new_mapping = {} for logical_id, mapped_id in new_row_major_mapping.items(): new_mapping[logical_id] = self._mapped_ids_to_backend_ids[mapped_id] self.current_mapping = new_mapping # Send possible gates: self._send_possible_commands() # Check that mapper actually made progress if len(self._stored_commands) == num_of_stored_commands_before: raise RuntimeError( "Mapper is potentially in an infinite loop. It is likely that the algorithm requires too" "many qubits. Increase the number of qubits for this mapper." )
Create a new mapping and executes possible gates. It first allocates all 0, ..., self.num_qubits-1 mapped qubit ids, if they are not already used because we might need them all for the swaps. Then it creates a new map, swaps all the qubits to the new map, executes all possible gates, and finally deallocates mapped qubit ids which don't store any information.
_run
python
ProjectQ-Framework/ProjectQ
projectq/cengines/_twodmapper.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_twodmapper.py
Apache-2.0
def receive(self, command_list): """ Receive a list of commands. Receive a command list and, for each command, stores it until we do a mapping (FlushGate or Cache of stored commands is full). Args: command_list (list of Command objects): list of commands to receive. """ for cmd in command_list: if isinstance(cmd.gate, FlushGate): while self._stored_commands: self._run() self.send([cmd]) else: self._stored_commands.append(cmd) # Storage is full: Create new map and send some gates away: if len(self._stored_commands) >= self.storage: self._run()
Receive a list of commands. Receive a command list and, for each command, stores it until we do a mapping (FlushGate or Cache of stored commands is full). Args: command_list (list of Command objects): list of commands to receive.
receive
python
ProjectQ-Framework/ProjectQ
projectq/cengines/_twodmapper.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_twodmapper.py
Apache-2.0
def test_with_flushing_with_exception(): """Test with flushing() as eng: with an exception raised in the 'with' block.""" try: with flushing(DummyEngine()) as engine: engine.flush = MagicMock() assert engine.flush.call_count == 0 raise ValueError("An exception is raised in the 'with' block") except ValueError: pass assert engine.flush.call_count == 1
Test with flushing() as eng: with an exception raised in the 'with' block.
test_with_flushing_with_exception
python
ProjectQ-Framework/ProjectQ
projectq/cengines/_withflushing_test.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_withflushing_test.py
Apache-2.0
def flushing(engine): """ Context manager to flush the given engine at the end of the 'with' context block. Example: with flushing(MainEngine()) as eng: qubit = eng.allocate_qubit() ... Calling 'eng.flush()' is no longer needed because the engine will be flushed at the end of the 'with' block even if an exception has been raised within that block. """ try: yield engine finally: engine.flush()
Context manager to flush the given engine at the end of the 'with' context block. Example: with flushing(MainEngine()) as eng: qubit = eng.allocate_qubit() ... Calling 'eng.flush()' is no longer needed because the engine will be flushed at the end of the 'with' block even if an exception has been raised within that block.
flushing
python
ProjectQ-Framework/ProjectQ
projectq/cengines/__init__.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/__init__.py
Apache-2.0
def __init__(self, gate_class, gate_decomposer, gate_recognizer=lambda cmd: True): """ Initialize a DecompositionRule object. Args: gate_class (type): The type of gate that this rule decomposes. The gate class is redundant information used to make lookups faster when iterating over a circuit and deciding "which rules apply to this gate?" again and again. Note that this parameter is a gate type, not a gate instance. You supply gate_class=MyGate or gate_class=MyGate().__class__, not gate_class=MyGate(). gate_decomposer (function[projectq.ops.Command]): Function which, given the command to decompose, applies a sequence of gates corresponding to the high-level function of a gate of type gate_class. gate_recognizer (function[projectq.ops.Command] : boolean): A predicate that determines if the decomposition applies to the given command (on top of the filtering by gate_class). For example, a decomposition rule may only to apply rotation gates that rotate by a specific angle. If no gate_recognizer is given, the decomposition applies to all gates matching the gate_class. """ # Check for common gate_class type mistakes. if isinstance(gate_class, BasicGate): raise ThisIsNotAGateClassError( "gate_class is a gate instance instead of a type of BasicGate." "\nDid you pass in someGate instead of someGate.__class__?" ) if gate_class == type.__class__: raise ThisIsNotAGateClassError( "gate_class is type.__class__ instead of a type of BasicGate." "\nDid you pass in GateType.__class__ instead of GateType?" ) self.gate_class = gate_class self.gate_decomposer = gate_decomposer self.gate_recognizer = gate_recognizer
Initialize a DecompositionRule object. Args: gate_class (type): The type of gate that this rule decomposes. The gate class is redundant information used to make lookups faster when iterating over a circuit and deciding "which rules apply to this gate?" again and again. Note that this parameter is a gate type, not a gate instance. You supply gate_class=MyGate or gate_class=MyGate().__class__, not gate_class=MyGate(). gate_decomposer (function[projectq.ops.Command]): Function which, given the command to decompose, applies a sequence of gates corresponding to the high-level function of a gate of type gate_class. gate_recognizer (function[projectq.ops.Command] : boolean): A predicate that determines if the decomposition applies to the given command (on top of the filtering by gate_class). For example, a decomposition rule may only to apply rotation gates that rotate by a specific angle. If no gate_recognizer is given, the decomposition applies to all gates matching the gate_class.
__init__
python
ProjectQ-Framework/ProjectQ
projectq/cengines/_replacer/_decomposition_rule.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_replacer/_decomposition_rule.py
Apache-2.0
def __init__(self, rules=None, modules=None): """ Initialize a DecompositionRuleSet object. Args: rules list[DecompositionRule]: Initial decomposition rules. modules (iterable[ModuleWithDecompositionRuleSet]): A list of things with an "all_defined_decomposition_rules" property containing decomposition rules to add to the rule set. """ self.decompositions = {} if rules: self.add_decomposition_rules(rules) if modules: self.add_decomposition_rules( [rule for module in modules for rule in module.all_defined_decomposition_rules] )
Initialize a DecompositionRuleSet object. Args: rules list[DecompositionRule]: Initial decomposition rules. modules (iterable[ModuleWithDecompositionRuleSet]): A list of things with an "all_defined_decomposition_rules" property containing decomposition rules to add to the rule set.
__init__
python
ProjectQ-Framework/ProjectQ
projectq/cengines/_replacer/_decomposition_rule_set.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_replacer/_decomposition_rule_set.py
Apache-2.0
def add_decomposition_rule(self, rule): """ Add a decomposition rule to the rule set. Args: rule (DecompositionRuleGate): The decomposition rule to add. """ decomp_obj = _Decomposition(rule.gate_decomposer, rule.gate_recognizer) cls = rule.gate_class.__name__ if cls not in self.decompositions: self.decompositions[cls] = [] self.decompositions[cls].append(decomp_obj)
Add a decomposition rule to the rule set. Args: rule (DecompositionRuleGate): The decomposition rule to add.
add_decomposition_rule
python
ProjectQ-Framework/ProjectQ
projectq/cengines/_replacer/_decomposition_rule_set.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_replacer/_decomposition_rule_set.py
Apache-2.0
def __init__(self, replacement_fun, recogn_fun): """ Initialize a Decomposition object. Args: replacement_fun: Function that, when called with a `Command` object, decomposes this command. recogn_fun: Function that, when called with a `Command` object, returns True if and only if the replacement rule can handle this command. Every Decomposition is registered with the gate class. The Decomposition rule is then potentially valid for all objects which are an instance of that same class (i.e., instance of gate_object.__class__). All other parameters have to be checked by the recogn_fun, i.e., it has to decide whether the decomposition rule can indeed be applied to replace the given Command. As an example, consider recognizing the Toffoli gate, which is a Pauli-X gate with 2 control qubits. The recognizer function would then be: .. code-block:: python def recogn_toffoli(cmd): # can be applied if the gate is an X-gate with 2 controls: return len(cmd.control_qubits) == 2 and, given a replacement function `replace_toffoli`, the decomposition rule can be registered as .. code-block:: python register_decomposition(X.__class__, decompose_toffoli, recogn_toffoli) Note: See projectq.setups.decompositions for more example codes. """ self.decompose = replacement_fun self.check = recogn_fun
Initialize a Decomposition object. Args: replacement_fun: Function that, when called with a `Command` object, decomposes this command. recogn_fun: Function that, when called with a `Command` object, returns True if and only if the replacement rule can handle this command. Every Decomposition is registered with the gate class. The Decomposition rule is then potentially valid for all objects which are an instance of that same class (i.e., instance of gate_object.__class__). All other parameters have to be checked by the recogn_fun, i.e., it has to decide whether the decomposition rule can indeed be applied to replace the given Command. As an example, consider recognizing the Toffoli gate, which is a Pauli-X gate with 2 control qubits. The recognizer function would then be: .. code-block:: python def recogn_toffoli(cmd): # can be applied if the gate is an X-gate with 2 controls: return len(cmd.control_qubits) == 2 and, given a replacement function `replace_toffoli`, the decomposition rule can be registered as .. code-block:: python register_decomposition(X.__class__, decompose_toffoli, recogn_toffoli) Note: See projectq.setups.decompositions for more example codes.
__init__
python
ProjectQ-Framework/ProjectQ
projectq/cengines/_replacer/_decomposition_rule_set.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_replacer/_decomposition_rule_set.py
Apache-2.0
def get_inverse_decomposition(self): """ Return the Decomposition object which handles the inverse of the original command. This simulates the user having added a decomposition rule for the inverse as well. Since decomposing the inverse of a command can be achieved by running the original decomposition inside a `with Dagger(engine):` statement, this is not necessary (and will be done automatically by the framework). Returns: Decomposition handling the inverse of the original command. """ def decomp(cmd): with Dagger(cmd.engine): self.decompose(cmd.get_inverse()) def recogn(cmd): return self.check(cmd.get_inverse()) return _Decomposition(decomp, recogn)
Return the Decomposition object which handles the inverse of the original command. This simulates the user having added a decomposition rule for the inverse as well. Since decomposing the inverse of a command can be achieved by running the original decomposition inside a `with Dagger(engine):` statement, this is not necessary (and will be done automatically by the framework). Returns: Decomposition handling the inverse of the original command.
get_inverse_decomposition
python
ProjectQ-Framework/ProjectQ
projectq/cengines/_replacer/_decomposition_rule_set.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_replacer/_decomposition_rule_set.py
Apache-2.0
def __init__(self, filterfun): """ Initialize an InstructionFilter object. Initializer: The provided filterfun returns True for all commands which do not need replacement and False for commands that do. Args: filterfun (function): Filter function which returns True for available commands, and False otherwise. filterfun will be called as filterfun(self, cmd). """ super().__init__() self._filterfun = filterfun
Initialize an InstructionFilter object. Initializer: The provided filterfun returns True for all commands which do not need replacement and False for commands that do. Args: filterfun (function): Filter function which returns True for available commands, and False otherwise. filterfun will be called as filterfun(self, cmd).
__init__
python
ProjectQ-Framework/ProjectQ
projectq/cengines/_replacer/_replacer.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_replacer/_replacer.py
Apache-2.0
def __init__( self, decomposition_rule_se, decomposition_chooser=lambda cmd, decomposition_list: decomposition_list[0], ): """ Initialize an AutoReplacer. Args: decomposition_chooser (function): A function which, given the Command to decompose and a list of potential Decomposition objects, determines (and then returns) the 'best' decomposition. The default decomposition chooser simply returns the first list element, i.e., calling .. code-block:: python repl = AutoReplacer() Amounts to .. code-block:: python def decomposition_chooser(cmd, decomp_list): return decomp_list[0] repl = AutoReplacer(decomposition_chooser) """ super().__init__() self._decomp_chooser = decomposition_chooser self.decomposition_rule_set = decomposition_rule_se
Initialize an AutoReplacer. Args: decomposition_chooser (function): A function which, given the Command to decompose and a list of potential Decomposition objects, determines (and then returns) the 'best' decomposition. The default decomposition chooser simply returns the first list element, i.e., calling .. code-block:: python repl = AutoReplacer() Amounts to .. code-block:: python def decomposition_chooser(cmd, decomp_list): return decomp_list[0] repl = AutoReplacer(decomposition_chooser)
__init__
python
ProjectQ-Framework/ProjectQ
projectq/cengines/_replacer/_replacer.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_replacer/_replacer.py
Apache-2.0
def _process_command(self, cmd): # pylint: disable=too-many-locals,too-many-branches """ Process a command. Check whether a command cmd can be handled by further engines and, if not, replace it using the decomposition rules loaded with the setup (e.g., setups.default). Args: cmd (Command): Command to process. Raises: Exception if no replacement is available in the loaded setup. """ if self.is_available(cmd): # pylint: disable=too-many-nested-blocks self.send([cmd]) else: # First check for a decomposition rules of the gate class, then # the gate class of the inverse gate. If nothing is found, do the # same for the first parent class, etc. gate_mro = type(cmd.gate).mro()[:-1] # If gate does not have an inverse it's parent classes are # DaggeredGate, BasicGate, object. Hence don't check the last two inverse_mro = type(get_inverse(cmd.gate)).mro()[:-2] rules = self.decomposition_rule_set.decompositions # If the decomposition rule to remove negatively controlled qubits is present in the list of potential # decompositions, we process it immediately, before any other decompositions. controlstate_rule = [ rule for rule in rules.get('BasicGate', []) if rule.decompose.__name__ == '_decompose_controlstate' ] if controlstate_rule and controlstate_rule[0].check(cmd): chosen_decomp = controlstate_rule[0] else: # check for decomposition rules decomp_list = [] potential_decomps = [] for level in range(max(len(gate_mro), len(inverse_mro))): # Check for forward rules if level < len(gate_mro): class_name = gate_mro[level].__name__ try: potential_decomps = rules[class_name] except KeyError: pass # throw out the ones which don't recognize the command for decomp in potential_decomps: if decomp.check(cmd): decomp_list.append(decomp) if len(decomp_list) != 0: break # Check for rules implementing the inverse gate # and run them in reverse if level < len(inverse_mro): inv_class_name = inverse_mro[level].__name__ try: potential_decomps += [d.get_inverse_decomposition() for d in rules[inv_class_name]] except KeyError: pass # throw out the ones which don't recognize the command for decomp in potential_decomps: if decomp.check(cmd): decomp_list.append(decomp) if len(decomp_list) != 0: break if len(decomp_list) == 0: raise NoGateDecompositionError(f"\nNo replacement found for {str(cmd)}!") # use decomposition chooser to determine the best decomposition chosen_decomp = self._decomp_chooser(cmd, decomp_list) # the decomposed command must have the same tags # (plus the ones it gets from meta-statements inside the # decomposition rule). # --> use a CommandModifier with a ForwarderEngine to achieve this. old_tags = cmd.tags[:] def cmd_mod_fun(cmd): # Adds the tags cmd.tags = old_tags[:] + cmd.tags cmd.engine = self.main_engine return cmd # the CommandModifier calls cmd_mod_fun for each command # --> commands get the right tags. cmod_eng = CommandModifier(cmd_mod_fun) cmod_eng.next_engine = self # send modified commands back here cmod_eng.main_engine = self.main_engine # forward everything to cmod_eng using the ForwarderEngine # which behaves just like MainEngine # (--> meta functions still work) forwarder_eng = ForwarderEngine(cmod_eng) cmd.engine = forwarder_eng # send gates directly to forwarder # (and not to main engine, which would screw up the ordering). chosen_decomp.decompose(cmd) # run the decomposition
Process a command. Check whether a command cmd can be handled by further engines and, if not, replace it using the decomposition rules loaded with the setup (e.g., setups.default). Args: cmd (Command): Command to process. Raises: Exception if no replacement is available in the loaded setup.
_process_command
python
ProjectQ-Framework/ProjectQ
projectq/cengines/_replacer/_replacer.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_replacer/_replacer.py
Apache-2.0
def receive(self, command_list): """ Receive a list of commands. Receive a list of commands from the previous compiler engine and, if necessary, replace/decompose the gates according to the decomposition rules in the loaded setup. Args: command_list (list<Command>): List of commands to handle. """ for cmd in command_list: if not isinstance(cmd.gate, FlushGate): self._process_command(cmd) else: self.send([cmd])
Receive a list of commands. Receive a list of commands from the previous compiler engine and, if necessary, replace/decompose the gates according to the decomposition rules in the loaded setup. Args: command_list (list<Command>): List of commands to handle.
receive
python
ProjectQ-Framework/ProjectQ
projectq/cengines/_replacer/_replacer.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_replacer/_replacer.py
Apache-2.0
def histogram(backend, qureg): """ Make a measurement outcome probability histogram for the given qubits. Args: backend (BasicEngine): A ProjectQ backend qureg (list of qubits and/or quregs): The qubits, for which to make the histogram Returns: A tuple (fig, axes, probabilities), where: fig: The histogram as figure axes: The axes of the histogram probabilities (dict): A dictionary mapping outcomes as string to their probabilities Note: Don't forget to call eng.flush() before using this function. """ qubit_list = [] for qb in qureg: if isinstance(qb, list): qubit_list.extend(qb) else: qubit_list.append(qb) if len(qubit_list) > 5: print(f'Warning: For {len(qubit_list)} qubits there are 2^{len(qubit_list)} different outcomes') print("The resulting histogram may look bad and/or take too long.") print("Consider calling histogram() with a sublist of the qubits.") if hasattr(backend, 'get_probabilities'): probabilities = backend.get_probabilities(qureg) elif isinstance(backend, Simulator): outcome = [0] * len(qubit_list) n_outcomes = 1 << len(qubit_list) probabilities = {} for i in range(n_outcomes): for pos in range(len(qubit_list)): if (1 << pos) & i: outcome[pos] = 1 else: outcome[pos] = 0 probabilities[''.join([str(bit) for bit in outcome])] = backend.get_probability(outcome, qubit_list) else: raise RuntimeError('Unable to retrieve probabilities from backend') # Empirical figure size for up to 5 qubits fig, axes = plt.subplots(figsize=(min(21.2, 2 + 0.6 * (1 << len(qubit_list))), 7)) names = list(probabilities.keys()) values = list(probabilities.values()) axes.bar(names, values) fig.suptitle('Measurement Probabilities') return (fig, axes, probabilities)
Make a measurement outcome probability histogram for the given qubits. Args: backend (BasicEngine): A ProjectQ backend qureg (list of qubits and/or quregs): The qubits, for which to make the histogram Returns: A tuple (fig, axes, probabilities), where: fig: The histogram as figure axes: The axes of the histogram probabilities (dict): A dictionary mapping outcomes as string to their probabilities Note: Don't forget to call eng.flush() before using this function.
histogram
python
ProjectQ-Framework/ProjectQ
projectq/libs/hist/_histogram.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/libs/hist/_histogram.py
Apache-2.0
def add_constant(eng, constant, quint): """ Add a classical constant c to the quantum integer (qureg) quint using Draper addition. Note: Uses the Fourier-transform adder from https://arxiv.org/abs/quant-ph/0008033. """ with Compute(eng): QFT | quint for i, qubit in enumerate(quint): for j in range(i, -1, -1): if (constant >> j) & 1: R(math.pi / (1 << (i - j))) | qubit Uncompute(eng)
Add a classical constant c to the quantum integer (qureg) quint using Draper addition. Note: Uses the Fourier-transform adder from https://arxiv.org/abs/quant-ph/0008033.
add_constant
python
ProjectQ-Framework/ProjectQ
projectq/libs/math/_constantmath.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/libs/math/_constantmath.py
Apache-2.0
def add_constant_modN(eng, constant, N, quint): # pylint: disable=invalid-name """ Add a classical constant c to a quantum integer (qureg) quint modulo N using Draper addition. This function uses Draper addition and the construction from https://arxiv.org/abs/quant-ph/0205095. """ if constant < 0 or constant > N: raise ValueError('Pre-condition failed: 0 <= constant < N') AddConstant(constant) | quint with Compute(eng): SubConstant(N) | quint ancilla = eng.allocate_qubit() CNOT | (quint[-1], ancilla) with Control(eng, ancilla): AddConstant(N) | quint SubConstant(constant) | quint with CustomUncompute(eng): X | quint[-1] CNOT | (quint[-1], ancilla) X | quint[-1] del ancilla AddConstant(constant) | quint
Add a classical constant c to a quantum integer (qureg) quint modulo N using Draper addition. This function uses Draper addition and the construction from https://arxiv.org/abs/quant-ph/0205095.
add_constant_modN
python
ProjectQ-Framework/ProjectQ
projectq/libs/math/_constantmath.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/libs/math/_constantmath.py
Apache-2.0
def mul_by_constant_modN(eng, constant, N, quint_in): # pylint: disable=invalid-name """ Multiply a quantum integer by a classical number a modulo N. i.e., |x> -> |a*x mod N> (only works if a and N are relative primes, otherwise the modular inverse does not exist). """ if constant < 0 or constant > N: raise ValueError('Pre-condition failed: 0 <= constant < N') if gcd(constant, N) != 1: raise ValueError('Pre-condition failed: gcd(constant, N) == 1') n_qubits = len(quint_in) quint_out = eng.allocate_qureg(n_qubits + 1) for i in range(n_qubits): with Control(eng, quint_in[i]): AddConstantModN((constant << i) % N, N) | quint_out for i in range(n_qubits): Swap | (quint_out[i], quint_in[i]) cinv = inv_mod_N(constant, N) for i in range(n_qubits): with Control(eng, quint_in[i]): SubConstantModN((cinv << i) % N, N) | quint_out del quint_out
Multiply a quantum integer by a classical number a modulo N. i.e., |x> -> |a*x mod N> (only works if a and N are relative primes, otherwise the modular inverse does not exist).
mul_by_constant_modN
python
ProjectQ-Framework/ProjectQ
projectq/libs/math/_constantmath.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/libs/math/_constantmath.py
Apache-2.0
def __init__(self, a): # pylint: disable=invalid-name """ Initialize the gate to the number to add. Args: a (int): Number to add to a quantum register. It also initializes its base class, BasicMathGate, with the corresponding function, so it can be emulated efficiently. """ super().__init__(lambda x: ((x + a),)) self.a = a # pylint: disable=invalid-name
Initialize the gate to the number to add. Args: a (int): Number to add to a quantum register. It also initializes its base class, BasicMathGate, with the corresponding function, so it can be emulated efficiently.
__init__
python
ProjectQ-Framework/ProjectQ
projectq/libs/math/_gates.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/libs/math/_gates.py
Apache-2.0
def __init__(self, a, N): """ Initialize the gate to the number to add modulo N. Args: a (int): Number to add to a quantum register (0 <= a < N). N (int): Number modulo which the addition is carried out. It also initializes its base class, BasicMathGate, with the corresponding function, so it can be emulated efficiently. """ super().__init__(lambda x: ((x + a) % N,)) self.a = a # pylint: disable=invalid-name self.N = N
Initialize the gate to the number to add modulo N. Args: a (int): Number to add to a quantum register (0 <= a < N). N (int): Number modulo which the addition is carried out. It also initializes its base class, BasicMathGate, with the corresponding function, so it can be emulated efficiently.
__init__
python
ProjectQ-Framework/ProjectQ
projectq/libs/math/_gates.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/libs/math/_gates.py
Apache-2.0
def __init__(self, a, N): # pylint: disable=invalid-name """ Initialize the gate to the number to multiply with modulo N. Args: a (int): Number by which to multiply a quantum register (0 <= a < N). N (int): Number modulo which the multiplication is carried out. It also initializes its base class, BasicMathGate, with the corresponding function, so it can be emulated efficiently. """ super().__init__(lambda x: ((a * x) % N,)) self.a = a # pylint: disable=invalid-name self.N = N
Initialize the gate to the number to multiply with modulo N. Args: a (int): Number by which to multiply a quantum register (0 <= a < N). N (int): Number modulo which the multiplication is carried out. It also initializes its base class, BasicMathGate, with the corresponding function, so it can be emulated efficiently.
__init__
python
ProjectQ-Framework/ProjectQ
projectq/libs/math/_gates.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/libs/math/_gates.py
Apache-2.0
def get_math_function(self, qubits): """Get the math function associated with an AddQuantumGate.""" n_qubits = len(qubits[0]) def math_fun(a): # pylint: disable=invalid-name a[1] = a[0] + a[1] if len(bin(a[1])[2:]) > n_qubits: a[1] = a[1] % (2**n_qubits) if len(a) == 3: # Flip the last bit of the carry register a[2] ^= 1 return a return math_fun
Get the math function associated with an AddQuantumGate.
get_math_function
python
ProjectQ-Framework/ProjectQ
projectq/libs/math/_gates.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/libs/math/_gates.py
Apache-2.0
def __init__(self): """ Initialize a SubtractQuantumGate object. Initializes the gate to its base class, BasicMathGate, with the corresponding function, so it can be emulated efficiently. """ def subtract(a, b): # pylint: disable=invalid-name return (a, b - a) super().__init__(subtract)
Initialize a SubtractQuantumGate object. Initializes the gate to its base class, BasicMathGate, with the corresponding function, so it can be emulated efficiently.
__init__
python
ProjectQ-Framework/ProjectQ
projectq/libs/math/_gates.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/libs/math/_gates.py
Apache-2.0
def __init__(self): """ Initialize a ComparatorQuantumGate object. Initialize the gate and its base class, BasicMathGate, with the corresponding function, so it can be emulated efficiently. """ def compare(a, b, c): # pylint: disable=invalid-name # pylint: disable=invalid-name if b < a: if c == 0: c = 1 else: c = 0 return (a, b, c) super().__init__(compare)
Initialize a ComparatorQuantumGate object. Initialize the gate and its base class, BasicMathGate, with the corresponding function, so it can be emulated efficiently.
__init__
python
ProjectQ-Framework/ProjectQ
projectq/libs/math/_gates.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/libs/math/_gates.py
Apache-2.0
def __init__(self): """ Initialize a DivideQuantumGate object. Initialize the gate and its base class, BasicMathGate, with the corresponding function, so it can be emulated efficiently. """ def division(dividend, remainder, divisor): if divisor == 0 or divisor > dividend: return (remainder, dividend, divisor) quotient = remainder + dividend // divisor return ((dividend - (quotient * divisor)), quotient, divisor) super().__init__(division)
Initialize a DivideQuantumGate object. Initialize the gate and its base class, BasicMathGate, with the corresponding function, so it can be emulated efficiently.
__init__
python
ProjectQ-Framework/ProjectQ
projectq/libs/math/_gates.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/libs/math/_gates.py
Apache-2.0
def __init__(self): """ Initialize a MultiplyQuantumGate object. Initialize the gate and its base class, BasicMathGate, with the corresponding function, so it can be emulated efficiently. """ def multiply(a, b, c): # pylint: disable=invalid-name return (a, b, c + a * b) super().__init__(multiply)
Initialize a MultiplyQuantumGate object. Initialize the gate and its base class, BasicMathGate, with the corresponding function, so it can be emulated efficiently.
__init__
python
ProjectQ-Framework/ProjectQ
projectq/libs/math/_gates.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/libs/math/_gates.py
Apache-2.0
def add_quantum(eng, quint_a, quint_b, carry=None): """ Add two quantum integers. i.e., |a0...a(n-1)>|b(0)...b(n-1)>|c> -> |a0...a(n-1)>|b+a(0)...b+a(n)> (only works if quint_a and quint_b are the same size and carry is a single qubit) Args: eng (MainEngine): ProjectQ MainEngine quint_a (list): Quantum register (or list of qubits) quint_b (list): Quantum register (or list of qubits) carry (list): Carry qubit Notes: Ancilla: 0, size: 7n-6, toffoli: 2n-1, depth: 5n-3. .. rubric:: References Quantum addition using ripple carry from: https://arxiv.org/pdf/0910.2530.pdf """ # pylint: disable = pointless-statement if len(quint_a) != len(quint_b): raise ValueError('quint_a and quint_b must have the same size!') if carry and len(carry) != 1: raise ValueError('Either no carry bit or a single carry qubit is allowed!') n_qubits = len(quint_a) + 1 for i in range(1, n_qubits - 1): CNOT | (quint_a[i], quint_b[i]) if carry: CNOT | (quint_a[n_qubits - 2], carry) for j in range(n_qubits - 3, 0, -1): CNOT | (quint_a[j], quint_a[j + 1]) for k in range(0, n_qubits - 2): with Control(eng, [quint_a[k], quint_b[k]]): X | (quint_a[k + 1]) if carry: with Control(eng, [quint_a[n_qubits - 2], quint_b[n_qubits - 2]]): X | carry for i in range(n_qubits - 2, 0, -1): # noqa: E741 CNOT | (quint_a[i], quint_b[i]) with Control(eng, [quint_a[i - 1], quint_b[i - 1]]): X | quint_a[i] for j in range(1, n_qubits - 2): CNOT | (quint_a[j], quint_a[j + 1]) for n_qubits in range(0, n_qubits - 1): CNOT | (quint_a[n_qubits], quint_b[n_qubits])
Add two quantum integers. i.e., |a0...a(n-1)>|b(0)...b(n-1)>|c> -> |a0...a(n-1)>|b+a(0)...b+a(n)> (only works if quint_a and quint_b are the same size and carry is a single qubit) Args: eng (MainEngine): ProjectQ MainEngine quint_a (list): Quantum register (or list of qubits) quint_b (list): Quantum register (or list of qubits) carry (list): Carry qubit Notes: Ancilla: 0, size: 7n-6, toffoli: 2n-1, depth: 5n-3. .. rubric:: References Quantum addition using ripple carry from: https://arxiv.org/pdf/0910.2530.pdf
add_quantum
python
ProjectQ-Framework/ProjectQ
projectq/libs/math/_quantummath.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/libs/math/_quantummath.py
Apache-2.0
def subtract_quantum(eng, quint_a, quint_b): """ Subtract two quantum integers. i.e., |a>|b> -> |a>|b-a> (only works if quint_a and quint_b are the same size) Args: eng (MainEngine): ProjectQ MainEngine quint_a (list): Quantum register (or list of qubits) quint_b (list): Quantum register (or list of qubits) Notes: Quantum subtraction using bitwise complementation of quantum adder: b-a = (a + b')'. Same as the quantum addition circuit except that the steps involving the carry qubit are left out and complement b at the start and at the end of the circuit is added. Ancilla: 0, size: 9n-8, toffoli: 2n-2, depth: 5n-5. .. rubric:: References Quantum addition using ripple carry from: https://arxiv.org/pdf/0910.2530.pdf """ # pylint: disable = pointless-statement, expression-not-assigned if len(quint_a) != len(quint_b): raise ValueError('quint_a and quint_b must have the same size!') n_qubits = len(quint_a) + 1 All(X) | quint_b for i in range(1, n_qubits - 1): CNOT | (quint_a[i], quint_b[i]) for j in range(n_qubits - 3, 0, -1): CNOT | (quint_a[j], quint_a[j + 1]) for k in range(0, n_qubits - 2): with Control(eng, [quint_a[k], quint_b[k]]): X | (quint_a[k + 1]) for i in range(n_qubits - 2, 0, -1): # noqa: E741 CNOT | (quint_a[i], quint_b[i]) with Control(eng, [quint_a[i - 1], quint_b[i - 1]]): X | quint_a[i] for j in range(1, n_qubits - 2): CNOT | (quint_a[j], quint_a[j + 1]) for n_qubits in range(0, n_qubits - 1): CNOT | (quint_a[n_qubits], quint_b[n_qubits]) All(X) | quint_b
Subtract two quantum integers. i.e., |a>|b> -> |a>|b-a> (only works if quint_a and quint_b are the same size) Args: eng (MainEngine): ProjectQ MainEngine quint_a (list): Quantum register (or list of qubits) quint_b (list): Quantum register (or list of qubits) Notes: Quantum subtraction using bitwise complementation of quantum adder: b-a = (a + b')'. Same as the quantum addition circuit except that the steps involving the carry qubit are left out and complement b at the start and at the end of the circuit is added. Ancilla: 0, size: 9n-8, toffoli: 2n-2, depth: 5n-5. .. rubric:: References Quantum addition using ripple carry from: https://arxiv.org/pdf/0910.2530.pdf
subtract_quantum
python
ProjectQ-Framework/ProjectQ
projectq/libs/math/_quantummath.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/libs/math/_quantummath.py
Apache-2.0
def inverse_add_quantum_carry(eng, quint_a, quint_b): """ Inverse of quantum addition with carry. Args: eng (MainEngine): ProjectQ MainEngine quint_a (list): Quantum register (or list of qubits) quint_b (list): Quantum register (or list of qubits) """ # pylint: disable = pointless-statement, expression-not-assigned # pylint: disable = unused-argument if len(quint_a) != len(quint_b[0]): raise ValueError('quint_a and quint_b must have the same size!') All(X) | quint_b[0] X | quint_b[1][0] AddQuantum | (quint_a, quint_b[0], quint_b[1]) All(X) | quint_b[0] X | quint_b[1][0]
Inverse of quantum addition with carry. Args: eng (MainEngine): ProjectQ MainEngine quint_a (list): Quantum register (or list of qubits) quint_b (list): Quantum register (or list of qubits)
inverse_add_quantum_carry
python
ProjectQ-Framework/ProjectQ
projectq/libs/math/_quantummath.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/libs/math/_quantummath.py
Apache-2.0
def comparator(eng, quint_a, quint_b, comp): """ Compare the size of two quantum integers. i.e, if a>b: |a>|b>|c> -> |a>|b>|c+1> else: |a>|b>|c> -> |a>|b>|c> (only works if quint_a and quint_b are the same size and the comparator is 1 qubit) Args: eng (MainEngine): ProjectQ MainEngine quint_a (list): Quantum register (or list of qubits) quint_b (list): Quantum register (or list of qubits) comp (Qubit): Comparator qubit Notes: Comparator flipping a compare qubit by computing the high bit of b-a, which is 1 if and only if a > b. The high bit is computed using the first half of circuit in AddQuantum (such that the high bit is written to the carry qubit) and then undoing the first half of the circuit. By complementing b at the start and b+a at the end the high bit of b-a is calculated. Ancilla: 0, size: 8n-3, toffoli: 2n+1, depth: 4n+3. """ # pylint: disable = pointless-statement, expression-not-assigned if len(quint_a) != len(quint_b): raise ValueError('quint_a and quint_b must have the same size!') if len(comp) != 1: raise ValueError('Comparator output qubit must be a single qubit!') n_qubits = len(quint_a) + 1 All(X) | quint_b for i in range(1, n_qubits - 1): CNOT | (quint_a[i], quint_b[i]) CNOT | (quint_a[n_qubits - 2], comp) for j in range(n_qubits - 3, 0, -1): CNOT | (quint_a[j], quint_a[j + 1]) for k in range(0, n_qubits - 2): with Control(eng, [quint_a[k], quint_b[k]]): X | (quint_a[k + 1]) with Control(eng, [quint_a[n_qubits - 2], quint_b[n_qubits - 2]]): X | comp for k in range(0, n_qubits - 2): with Control(eng, [quint_a[k], quint_b[k]]): X | (quint_a[k + 1]) for j in range(n_qubits - 3, 0, -1): CNOT | (quint_a[j], quint_a[j + 1]) for i in range(1, n_qubits - 1): CNOT | (quint_a[i], quint_b[i]) All(X) | quint_b
Compare the size of two quantum integers. i.e, if a>b: |a>|b>|c> -> |a>|b>|c+1> else: |a>|b>|c> -> |a>|b>|c> (only works if quint_a and quint_b are the same size and the comparator is 1 qubit) Args: eng (MainEngine): ProjectQ MainEngine quint_a (list): Quantum register (or list of qubits) quint_b (list): Quantum register (or list of qubits) comp (Qubit): Comparator qubit Notes: Comparator flipping a compare qubit by computing the high bit of b-a, which is 1 if and only if a > b. The high bit is computed using the first half of circuit in AddQuantum (such that the high bit is written to the carry qubit) and then undoing the first half of the circuit. By complementing b at the start and b+a at the end the high bit of b-a is calculated. Ancilla: 0, size: 8n-3, toffoli: 2n+1, depth: 4n+3.
comparator
python
ProjectQ-Framework/ProjectQ
projectq/libs/math/_quantummath.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/libs/math/_quantummath.py
Apache-2.0
def quantum_conditional_add(eng, quint_a, quint_b, conditional): """ Add up two quantum integers if conditional is high. i.e., |a>|b>|c> -> |a>|b+a>|c> (without a carry out qubit) if conditional is low, no operation is performed, i.e., |a>|b>|c> -> |a>|b>|c> Args: eng (MainEngine): ProjectQ MainEngine quint_a (list): Quantum register (or list of qubits) quint_b (list): Quantum register (or list of qubits) conditional (list): Conditional qubit Notes: Ancilla: 0, Size: 7n-7, Toffoli: 3n-3, Depth: 5n-3. .. rubric:: References Quantum Conditional Add from https://arxiv.org/pdf/1609.01241.pdf """ # pylint: disable = pointless-statement, expression-not-assigned if len(quint_a) != len(quint_b): raise ValueError('quint_a and quint_b must have the same size!') if len(conditional) != 1: raise ValueError('Conditional qubit must be a single qubit!') n_qubits = len(quint_a) + 1 for i in range(1, n_qubits - 1): CNOT | (quint_a[i], quint_b[i]) for i in range(n_qubits - 2, 1, -1): CNOT | (quint_a[i - 1], quint_a[i]) for k in range(0, n_qubits - 2): with Control(eng, [quint_a[k], quint_b[k]]): X | (quint_a[k + 1]) with Control(eng, [quint_a[n_qubits - 2], conditional[0]]): X | quint_b[n_qubits - 2] for i in range(n_qubits - 2, 0, -1): # noqa: E741 with Control(eng, [quint_a[i - 1], quint_b[i - 1]]): X | quint_a[i] with Control(eng, [quint_a[i - 1], conditional[0]]): X | (quint_b[i - 1]) for j in range(1, n_qubits - 2): CNOT | (quint_a[j], quint_a[j + 1]) for k in range(1, n_qubits - 1): CNOT | (quint_a[k], quint_b[k])
Add up two quantum integers if conditional is high. i.e., |a>|b>|c> -> |a>|b+a>|c> (without a carry out qubit) if conditional is low, no operation is performed, i.e., |a>|b>|c> -> |a>|b>|c> Args: eng (MainEngine): ProjectQ MainEngine quint_a (list): Quantum register (or list of qubits) quint_b (list): Quantum register (or list of qubits) conditional (list): Conditional qubit Notes: Ancilla: 0, Size: 7n-7, Toffoli: 3n-3, Depth: 5n-3. .. rubric:: References Quantum Conditional Add from https://arxiv.org/pdf/1609.01241.pdf
quantum_conditional_add
python
ProjectQ-Framework/ProjectQ
projectq/libs/math/_quantummath.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/libs/math/_quantummath.py
Apache-2.0
def quantum_division(eng, dividend, remainder, divisor): """ Perform restoring integer division. i.e., |dividend>|remainder>|divisor> -> |remainder>|quotient>|divisor> (only works if all three qubits are of equal length) Args: eng (MainEngine): ProjectQ MainEngine dividend (list): Quantum register (or list of qubits) remainder (list): Quantum register (or list of qubits) divisor (list): Quantum register (or list of qubits) Notes: Ancilla: n, size 16n^2 - 13, toffoli: 5n^2 -5 , depth: 10n^2-6. .. rubric:: References Quantum Restoring Integer Division from: https://arxiv.org/pdf/1609.01241.pdf. """ # The circuit consists of three parts # i) leftshift # ii) subtraction # iii) conditional add operation. if not len(dividend) == len(remainder) == len(divisor): raise ValueError('Size mismatch in dividend, divisor and remainder!') j = len(remainder) n_dividend = len(dividend) while j != 0: combined_reg = [] combined_reg.append(dividend[n_dividend - 1]) for i in range(0, n_dividend - 1): combined_reg.append(remainder[i]) SubtractQuantum | (divisor[0:n_dividend], combined_reg) CNOT | (combined_reg[n_dividend - 1], remainder[n_dividend - 1]) with Control(eng, remainder[n_dividend - 1]): AddQuantum | (divisor[0:n_dividend], combined_reg) X | remainder[n_dividend - 1] remainder.insert(0, dividend[n_dividend - 1]) dividend.insert(0, remainder[n_dividend]) del remainder[n_dividend] del dividend[n_dividend] j -= 1
Perform restoring integer division. i.e., |dividend>|remainder>|divisor> -> |remainder>|quotient>|divisor> (only works if all three qubits are of equal length) Args: eng (MainEngine): ProjectQ MainEngine dividend (list): Quantum register (or list of qubits) remainder (list): Quantum register (or list of qubits) divisor (list): Quantum register (or list of qubits) Notes: Ancilla: n, size 16n^2 - 13, toffoli: 5n^2 -5 , depth: 10n^2-6. .. rubric:: References Quantum Restoring Integer Division from: https://arxiv.org/pdf/1609.01241.pdf.
quantum_division
python
ProjectQ-Framework/ProjectQ
projectq/libs/math/_quantummath.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/libs/math/_quantummath.py
Apache-2.0
def inverse_quantum_division(eng, remainder, quotient, divisor): """ Perform the inverse of a restoring integer division. i.e., |remainder>|quotient>|divisor> -> |dividend>|remainder(0)>|divisor> Args: eng (MainEngine): ProjectQ MainEngine dividend (list): Quantum register (or list of qubits) remainder (list): Quantum register (or list of qubits) divisor (list): Quantum register (or list of qubits) """ if not len(quotient) == len(remainder) == len(divisor): raise ValueError('Size mismatch in quotient, divisor and remainder!') j = 0 n_quotient = len(quotient) while j != n_quotient: X | quotient[0] with Control(eng, quotient[0]): SubtractQuantum | (divisor, remainder) CNOT | (remainder[-1], quotient[0]) AddQuantum | (divisor, remainder) remainder.insert(n_quotient, quotient[0]) quotient.insert(n_quotient, remainder[0]) del remainder[0] del quotient[0] j += 1
Perform the inverse of a restoring integer division. i.e., |remainder>|quotient>|divisor> -> |dividend>|remainder(0)>|divisor> Args: eng (MainEngine): ProjectQ MainEngine dividend (list): Quantum register (or list of qubits) remainder (list): Quantum register (or list of qubits) divisor (list): Quantum register (or list of qubits)
inverse_quantum_division
python
ProjectQ-Framework/ProjectQ
projectq/libs/math/_quantummath.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/libs/math/_quantummath.py
Apache-2.0
def quantum_conditional_add_carry(eng, quint_a, quint_b, ctrl, z): # pylint: disable=invalid-name """ Add up two quantum integers if the control qubit is |1>. i.e., |a>|b>|ctrl>|z(0)z(1)> -> |a>|s(0)...s(n-1)>|ctrl>|s(n)z(1)> (where s denotes the sum of a and b) If the control qubit is |0> no operation is performed: |a>|b>|ctrl>|z(0)z(1)> -> |a>|b>|ctrl>|z(0)z(1)> (only works if quint_a and quint_b are of the same size, ctrl is a single qubit and z is a quantum register with 2 qubits. Args: eng (MainEngine): ProjectQ MainEngine quint_a (list): Quantum register (or list of qubits) quint_b (list): Quantum register (or list of qubits) ctrl (list): Control qubit z (list): Quantum register with 2 qubits Notes: Ancilla: 2, size: 7n - 4, toffoli: 3n + 2, depth: 5n. .. rubric:: References Quantum conditional add with no input carry from: https://arxiv.org/pdf/1706.05113.pdf """ if len(quint_a) != len(quint_b): raise ValueError('quint_a and quint_b must have the same size!') if len(ctrl) != 1: raise ValueError('Only a single control qubit is allowed!') if len(z) != 2: raise ValueError('Z quantum register must have 2 qubits!') n_a = len(quint_a) for i in range(1, n_a): CNOT | (quint_a[i], quint_b[i]) with Control(eng, [quint_a[n_a - 1], ctrl[0]]): X | z[0] for j in range(n_a - 2, 0, -1): CNOT | (quint_a[j], quint_a[j + 1]) for k in range(0, n_a - 1): with Control(eng, [quint_b[k], quint_a[k]]): X | quint_a[k + 1] with Control(eng, [quint_b[n_a - 1], quint_a[n_a - 1]]): X | z[1] with Control(eng, [ctrl[0], z[1]]): X | z[0] with Control(eng, [quint_b[n_a - 1], quint_a[n_a - 1]]): X | z[1] for i in range(n_a - 1, 0, -1): # noqa: E741 with Control(eng, [ctrl[0], quint_a[i]]): X | quint_b[i] with Control(eng, [quint_a[i - 1], quint_b[i - 1]]): X | quint_a[i] with Control(eng, [quint_a[0], ctrl[0]]): X | quint_b[0] for j in range(1, n_a - 1): CNOT | (quint_a[j], quint_a[j + 1]) for n_a in range(1, n_a): CNOT | (quint_a[n_a], quint_b[n_a])
Add up two quantum integers if the control qubit is |1>. i.e., |a>|b>|ctrl>|z(0)z(1)> -> |a>|s(0)...s(n-1)>|ctrl>|s(n)z(1)> (where s denotes the sum of a and b) If the control qubit is |0> no operation is performed: |a>|b>|ctrl>|z(0)z(1)> -> |a>|b>|ctrl>|z(0)z(1)> (only works if quint_a and quint_b are of the same size, ctrl is a single qubit and z is a quantum register with 2 qubits. Args: eng (MainEngine): ProjectQ MainEngine quint_a (list): Quantum register (or list of qubits) quint_b (list): Quantum register (or list of qubits) ctrl (list): Control qubit z (list): Quantum register with 2 qubits Notes: Ancilla: 2, size: 7n - 4, toffoli: 3n + 2, depth: 5n. .. rubric:: References Quantum conditional add with no input carry from: https://arxiv.org/pdf/1706.05113.pdf
quantum_conditional_add_carry
python
ProjectQ-Framework/ProjectQ
projectq/libs/math/_quantummath.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/libs/math/_quantummath.py
Apache-2.0
def quantum_multiplication(eng, quint_a, quint_b, product): """ Multiplies two quantum integers. i.e, |a>|b>|0> -> |a>|b>|a*b> (only works if quint_a and quint_b are of the same size, n qubits and product has size 2n+1). Args: eng (MainEngine): ProjectQ MainEngine quint_a (list): Quantum register (or list of qubits) quint_b (list): Quantum register (or list of qubits) product (list): Quantum register (or list of qubits) storing the result Notes: Ancilla: 2n + 1, size: 7n^2 - 9n + 4, toffoli: 5n^2 - 4n, depth: 3n^2 - 2. .. rubric:: References Quantum multiplication from: https://arxiv.org/abs/1706.05113. """ n_a = len(quint_a) if len(quint_a) != len(quint_b): raise ValueError('quint_a and quint_b must have the same size!') if len(product) != ((2 * n_a) + 1): raise ValueError('product size must be 2*n + 1') for i in range(0, n_a): with Control(eng, [quint_a[i], quint_b[0]]): X | product[i] with Control(eng, quint_b[1]): AddQuantum | ( quint_a[0 : (n_a - 1)], # noqa: E203 product[1:n_a], [product[n_a + 1], product[n_a + 2]], ) for j in range(2, n_a): with Control(eng, quint_b[j]): AddQuantum | ( quint_a[0 : (n_a - 1)], # noqa: E203 product[(0 + j) : (n_a - 1 + j)], # noqa: E203 [product[n_a + j], product[n_a + j + 1]], )
Multiplies two quantum integers. i.e, |a>|b>|0> -> |a>|b>|a*b> (only works if quint_a and quint_b are of the same size, n qubits and product has size 2n+1). Args: eng (MainEngine): ProjectQ MainEngine quint_a (list): Quantum register (or list of qubits) quint_b (list): Quantum register (or list of qubits) product (list): Quantum register (or list of qubits) storing the result Notes: Ancilla: 2n + 1, size: 7n^2 - 9n + 4, toffoli: 5n^2 - 4n, depth: 3n^2 - 2. .. rubric:: References Quantum multiplication from: https://arxiv.org/abs/1706.05113.
quantum_multiplication
python
ProjectQ-Framework/ProjectQ
projectq/libs/math/_quantummath.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/libs/math/_quantummath.py
Apache-2.0
def inverse_quantum_multiplication(eng, quint_a, quint_b, product): """ Inverse of the multiplication of two quantum integers. i.e, |a>|b>|a*b> -> |a>|b>|0> (only works if quint_a and quint_b are of the same size, n qubits and product has size 2n+1) Args: eng (MainEngine): ProjectQ MainEngine quint_a (list): Quantum register (or list of qubits) quint_b (list): Quantum register (or list of qubits) product (list): Quantum register (or list of qubits) storing the result """ n_a = len(quint_a) if len(quint_a) != len(quint_b): raise ValueError('quint_a and quint_b must have the same size!') if len(product) != ((2 * n_a) + 1): raise ValueError('product size must be 2*n + 1') for j in range(2, n_a): with Control(eng, quint_b[j]): SubtractQuantum | ( quint_a[0 : (n_a - 1)], # noqa: E203 product[(0 + j) : (n_a - 1 + j)], # noqa: E203 [product[n_a + j], product[n_a + j + 1]], ) for i in range(0, n_a): with Control(eng, [quint_a[i], quint_b[0]]): X | product[i] with Control(eng, quint_b[1]): SubtractQuantum | ( quint_a[0 : (n_a - 1)], # noqa: E203 product[1:n_a], [product[n_a + 1], product[n_a + 2]], )
Inverse of the multiplication of two quantum integers. i.e, |a>|b>|a*b> -> |a>|b>|0> (only works if quint_a and quint_b are of the same size, n qubits and product has size 2n+1) Args: eng (MainEngine): ProjectQ MainEngine quint_a (list): Quantum register (or list of qubits) quint_b (list): Quantum register (or list of qubits) product (list): Quantum register (or list of qubits) storing the result
inverse_quantum_multiplication
python
ProjectQ-Framework/ProjectQ
projectq/libs/math/_quantummath.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/libs/math/_quantummath.py
Apache-2.0
def __init__(self, function, **kwargs): """ Initialize a control function oracle. Args: function (int): Function truth table. Keyword Args: synth: A RevKit synthesis command which creates a reversible circuit based on a truth table and requires no additional ancillae (e.g., ``revkit.esopbs``). Can also be a nullary lambda that calls several RevKit commands. **Default:** ``revkit.esopbs`` """ if isinstance(function, int): self.function = function else: try: import dormouse # pylint: disable=import-outside-toplevel self.function = dormouse.to_truth_table(function) except ImportError as err: # pragma: no cover raise RuntimeError( "The dormouse library needs to be installed in order to " "automatically compile Python code into functions. Try " "to install dormouse with 'pip install dormouse'." ) from err self.kwargs = kwargs self._check_function()
Initialize a control function oracle. Args: function (int): Function truth table. Keyword Args: synth: A RevKit synthesis command which creates a reversible circuit based on a truth table and requires no additional ancillae (e.g., ``revkit.esopbs``). Can also be a nullary lambda that calls several RevKit commands. **Default:** ``revkit.esopbs``
__init__
python
ProjectQ-Framework/ProjectQ
projectq/libs/revkit/_control_function.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/libs/revkit/_control_function.py
Apache-2.0
def __or__(self, qubits): """ Apply control function to qubits (and synthesizes circuit). Args: qubits (tuple<Qureg>): Qubits to which the control function is being applied. The first `n` qubits are for the controls, the last qubit is for the target qubit. """ try: import revkit # pylint: disable=import-outside-toplevel except ImportError as err: # pragma: no cover raise RuntimeError( "The RevKit Python library needs to be installed and in the " "PYTHONPATH in order to call this function" ) from err # pylint: disable=invalid-name # convert qubits to tuple qs = [] for item in BasicGate.make_tuple_of_qureg(qubits): qs += item if isinstance(item, list) else [item] # function truth table cannot be larger than number of control qubits # allow if 2 ** (2 ** (len(qs) - 1)) <= self.function: raise AttributeError("Function truth table exceeds number of control qubits") # create truth table from function integer hex_length = max(2 ** (len(qs) - 1) // 4, 1) revkit.tt(table=f"{self.function:#0{hex_length}x}") # create reversible circuit from truth table self.kwargs.get("synth", revkit.esopbs)() # check whether circuit has correct signature if revkit.ps(mct=True, silent=True)['qubits'] != len(qs): raise RuntimeError("Generated circuit lines does not match provided qubits") # convert reversible circuit to ProjectQ code and execute it _exec(revkit.to_projectq(mct=True), qs)
Apply control function to qubits (and synthesizes circuit). Args: qubits (tuple<Qureg>): Qubits to which the control function is being applied. The first `n` qubits are for the controls, the last qubit is for the target qubit.
__or__
python
ProjectQ-Framework/ProjectQ
projectq/libs/revkit/_control_function.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/libs/revkit/_control_function.py
Apache-2.0
def __init__(self, permutation, **kwargs): """ Initialize a permutation oracle. Args: permutation (list<int>): Permutation (starting from 0). Keyword Args: synth: A RevKit synthesis command which creates a reversible circuit based on a reversible truth table (e.g., ``revkit.tbs`` or ``revkit.dbs``). Can also be a nullary lambda that calls several RevKit commands. **Default:** ``revkit.tbs`` """ self.permutation = permutation self.kwargs = kwargs self._check_permutation()
Initialize a permutation oracle. Args: permutation (list<int>): Permutation (starting from 0). Keyword Args: synth: A RevKit synthesis command which creates a reversible circuit based on a reversible truth table (e.g., ``revkit.tbs`` or ``revkit.dbs``). Can also be a nullary lambda that calls several RevKit commands. **Default:** ``revkit.tbs``
__init__
python
ProjectQ-Framework/ProjectQ
projectq/libs/revkit/_permutation.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/libs/revkit/_permutation.py
Apache-2.0
def __or__(self, qubits): """ Apply permutation to qubits (and synthesizes circuit). Args: qubits (tuple<Qureg>): Qubits to which the permutation is being applied. """ try: import revkit # pylint: disable=import-outside-toplevel except ImportError as err: # pragma: no cover raise RuntimeError( "The RevKit Python library needs to be installed and in the " "PYTHONPATH in order to call this function" ) from err # pylint: disable=invalid-name # convert qubits to flattened list qs = BasicGate.make_tuple_of_qureg(qubits) qs = sum(qs, []) # permutation must have 2*q elements, where q is the number of qubits if 2 ** (len(qs)) != len(self.permutation): raise AttributeError("Number of qubits does not fit to the size of the permutation") # create reversible truth table from permutation revkit.perm(permutation=" ".join(map(str, self.permutation))) # create reversible circuit from reversible truth table self.kwargs.get("synth", revkit.tbs)() # convert reversible circuit to ProjectQ code and execute it _exec(revkit.to_projectq(mct=True), qs)
Apply permutation to qubits (and synthesizes circuit). Args: qubits (tuple<Qureg>): Qubits to which the permutation is being applied.
__or__
python
ProjectQ-Framework/ProjectQ
projectq/libs/revkit/_permutation.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/libs/revkit/_permutation.py
Apache-2.0
def __init__(self, function, **kwargs): """ Initialize a phase oracle. Args: function (int): Function truth table. Keyword Args: synth: A RevKit synthesis command which creates a reversible circuit based on a truth table and requires no additional ancillae (e.g., ``revkit.esopps``). Can also be a nullary lambda that calls several RevKit commands. **Default:** ``revkit.esopps`` """ if isinstance(function, int): self.function = function else: try: import dormouse # pylint: disable=import-outside-toplevel self.function = dormouse.to_truth_table(function) except ImportError as err: # pragma: no cover raise RuntimeError( "The dormouse library needs to be installed in order to " "automatically compile Python code into functions. Try " "to install dormouse with 'pip install dormouse'." ) from err self.kwargs = kwargs self._check_function()
Initialize a phase oracle. Args: function (int): Function truth table. Keyword Args: synth: A RevKit synthesis command which creates a reversible circuit based on a truth table and requires no additional ancillae (e.g., ``revkit.esopps``). Can also be a nullary lambda that calls several RevKit commands. **Default:** ``revkit.esopps``
__init__
python
ProjectQ-Framework/ProjectQ
projectq/libs/revkit/_phase.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/libs/revkit/_phase.py
Apache-2.0
def __or__(self, qubits): """ Apply phase circuit to qubits (and synthesizes circuit). Args: qubits (tuple<Qureg>): Qubits to which the phase circuit is being applied. """ try: import revkit # pylint: disable=import-outside-toplevel except ImportError as err: # pragma: no cover raise RuntimeError( "The RevKit Python library needs to be installed and in the " "PYTHONPATH in order to call this function" ) from err # pylint: disable=invalid-name # convert qubits to tuple qs = [] for item in BasicGate.make_tuple_of_qureg(qubits): qs += item if isinstance(item, list) else [item] # function truth table cannot be larger than number of control qubits # allow if 2 ** (2 ** len(qs)) <= self.function: raise AttributeError("Function truth table exceeds number of control qubits") # create truth table from function integer hex_length = max(2 ** (len(qs) - 1) // 4, 1) revkit.tt(table=f"{self.function:#0{hex_length}x}") # create phase circuit from truth table self.kwargs.get("synth", revkit.esopps)() # check whether circuit has correct signature if revkit.ps(mct=True, silent=True)['qubits'] != len(qs): raise RuntimeError("Generated circuit lines does not match provided qubits") # convert reversible circuit to ProjectQ code and execute it _exec(revkit.to_projectq(mct=True), qs)
Apply phase circuit to qubits (and synthesizes circuit). Args: qubits (tuple<Qureg>): Qubits to which the phase circuit is being applied.
__or__
python
ProjectQ-Framework/ProjectQ
projectq/libs/revkit/_phase.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/libs/revkit/_phase.py
Apache-2.0
def run_uncompute(self): # pylint: disable=too-many-branches,too-many-statements """ Send uncomputing gates. Sends the inverse of the stored commands in reverse order down to the next engine. And also deals with allocated qubits in Compute section. If a qubit has been allocated during compute, it will be deallocated during uncompute. If a qubit has been allocated and deallocated during compute, then a new qubit is allocated and deallocated during uncompute. """ # No qubits allocated during Compute section -> do standard uncompute if len(self._allocated_qubit_ids) == 0: self.send([_add_uncompute_tag(cmd.get_inverse()) for cmd in reversed(self._l)]) return # qubits ids which were allocated and deallocated in Compute section ids_local_to_compute = self._allocated_qubit_ids.intersection(self._deallocated_qubit_ids) # No qubits allocated and already deallocated during compute. # Don't inspect each command as below -> faster uncompute # Just find qubits which have been allocated and deallocate them if len(ids_local_to_compute) == 0: for cmd in reversed(self._l): if cmd.gate == Allocate: qubit_id = cmd.qubits[0][0].id # Remove this qubit from MainEngine.active_qubits and # set qubit.id to = -1 in Qubit object such that it won't # send another deallocate when it goes out of scope qubit_found = False for active_qubit in self.main_engine.active_qubits: if active_qubit.id == qubit_id: active_qubit.id = -1 del active_qubit qubit_found = True break if not qubit_found: raise QubitManagementError("\nQubit was not found in " + "MainEngine.active_qubits.\n") self.send([_add_uncompute_tag(cmd.get_inverse())]) else: self.send([_add_uncompute_tag(cmd.get_inverse())]) return # There was at least one qubit allocated and deallocated within # compute section. Handle uncompute in most general case new_local_id = {} for cmd in reversed(self._l): if cmd.gate == Deallocate: if not cmd.qubits[0][0].id in ids_local_to_compute: # pragma: no cover raise RuntimeError( 'Internal compiler error: qubit being deallocated is not found in the list of qubits local to ' 'the Compute section' ) # Create new local qubit which lives within uncompute section # Allocate needs to have old tags + uncompute tag def add_uncompute(command, old_tags=deepcopy(cmd.tags)): command.tags = old_tags + [UncomputeTag()] return command tagger_eng = CommandModifier(add_uncompute) insert_engine(self, tagger_eng) new_local_qb = self.allocate_qubit() drop_engine_after(self) new_local_id[cmd.qubits[0][0].id] = deepcopy(new_local_qb[0].id) # Set id of new_local_qb to -1 such that it doesn't send a # deallocate gate new_local_qb[0].id = -1 elif cmd.gate == Allocate: # Deallocate qubit if cmd.qubits[0][0].id in ids_local_to_compute: # Deallocate local qubit and remove id from new_local_id old_id = deepcopy(cmd.qubits[0][0].id) cmd.qubits[0][0].id = new_local_id[cmd.qubits[0][0].id] del new_local_id[old_id] self.send([_add_uncompute_tag(cmd.get_inverse())]) else: # Deallocate qubit which was allocated in compute section: qubit_id = cmd.qubits[0][0].id # Remove this qubit from MainEngine.active_qubits and # set qubit.id to = -1 in Qubit object such that it won't # send another deallocate when it goes out of scope qubit_found = False for active_qubit in self.main_engine.active_qubits: if active_qubit.id == qubit_id: active_qubit.id = -1 del active_qubit qubit_found = True break if not qubit_found: raise QubitManagementError("\nQubit was not found in " + "MainEngine.active_qubits.\n") self.send([_add_uncompute_tag(cmd.get_inverse())]) else: # Process commands by replacing each local qubit from # compute section with new local qubit from the uncompute # section if new_local_id: # Only if we still have local qubits for qureg in cmd.all_qubits: for qubit in qureg: if qubit.id in new_local_id: qubit.id = new_local_id[qubit.id] self.send([_add_uncompute_tag(cmd.get_inverse())])
Send uncomputing gates. Sends the inverse of the stored commands in reverse order down to the next engine. And also deals with allocated qubits in Compute section. If a qubit has been allocated during compute, it will be deallocated during uncompute. If a qubit has been allocated and deallocated during compute, then a new qubit is allocated and deallocated during uncompute.
run_uncompute
python
ProjectQ-Framework/ProjectQ
projectq/meta/_compute.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/meta/_compute.py
Apache-2.0
def end_compute(self): """ End the compute step (exit the with Compute() - statement). Will tell the Compute-engine to stop caching. It then waits for the uncompute instruction, which is when it sends all cached commands inverted and in reverse order down to the next compiler engine. Raises: QubitManagementError: If qubit has been deallocated in Compute section which has not been allocated in Compute section """ self._compute = False if not self._allocated_qubit_ids.issuperset(self._deallocated_qubit_ids): raise QubitManagementError( "\nQubit has been deallocated in with Compute(eng) context \n" "which has not been allocated within this Compute section" )
End the compute step (exit the with Compute() - statement). Will tell the Compute-engine to stop caching. It then waits for the uncompute instruction, which is when it sends all cached commands inverted and in reverse order down to the next compiler engine. Raises: QubitManagementError: If qubit has been deallocated in Compute section which has not been allocated in Compute section
end_compute
python
ProjectQ-Framework/ProjectQ
projectq/meta/_compute.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/meta/_compute.py
Apache-2.0
def receive(self, command_list): """ Receive a list of commands. If in compute-mode, receive commands and store deepcopy of each cmd. Add ComputeTag to received cmd and send it on. Otherwise, send all received commands directly to next_engine. Args: command_list (list<Command>): List of commands to receive. """ if self._compute: for cmd in command_list: if cmd.gate == Allocate: self._allocated_qubit_ids.add(cmd.qubits[0][0].id) elif cmd.gate == Deallocate: self._deallocated_qubit_ids.add(cmd.qubits[0][0].id) self._l.append(deepcopy(cmd)) tags = cmd.tags tags.append(ComputeTag()) self.send(command_list) else: self.send(command_list)
Receive a list of commands. If in compute-mode, receive commands and store deepcopy of each cmd. Add ComputeTag to received cmd and send it on. Otherwise, send all received commands directly to next_engine. Args: command_list (list<Command>): List of commands to receive.
receive
python
ProjectQ-Framework/ProjectQ
projectq/meta/_compute.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/meta/_compute.py
Apache-2.0
def receive(self, command_list): """ Receive a list of commands. Receive commands and add an UncomputeTag to their tags. Args: command_list (list<Command>): List of commands to handle. """ for cmd in command_list: if cmd.gate == Allocate: self._allocated_qubit_ids.add(cmd.qubits[0][0].id) elif cmd.gate == Deallocate: self._deallocated_qubit_ids.add(cmd.qubits[0][0].id) tags = cmd.tags tags.append(UncomputeTag()) self.send([cmd])
Receive a list of commands. Receive commands and add an UncomputeTag to their tags. Args: command_list (list<Command>): List of commands to handle.
receive
python
ProjectQ-Framework/ProjectQ
projectq/meta/_compute.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/meta/_compute.py
Apache-2.0
def __init__(self, engine): """ Initialize a Compute context. Args: engine (BasicEngine): Engine which is the first to receive all commands (normally: MainEngine). """ self.engine = engine self._compute_eng = None
Initialize a Compute context. Args: engine (BasicEngine): Engine which is the first to receive all commands (normally: MainEngine).
__init__
python
ProjectQ-Framework/ProjectQ
projectq/meta/_compute.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/meta/_compute.py
Apache-2.0
def __init__(self, engine): """ Initialize a CustomUncompute context. Args: engine (BasicEngine): Engine which is the first to receive all commands (normally: MainEngine). """ self.engine = engine # Save all qubit ids from qubits which are created or destroyed. self._allocated_qubit_ids = set() self._deallocated_qubit_ids = set() self._uncompute_eng = None
Initialize a CustomUncompute context. Args: engine (BasicEngine): Engine which is the first to receive all commands (normally: MainEngine).
__init__
python
ProjectQ-Framework/ProjectQ
projectq/meta/_compute.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/meta/_compute.py
Apache-2.0
def Uncompute(engine): # pylint: disable=invalid-name """ Uncompute automatically. Example: .. code-block:: python with Compute(eng): do_something(qubits) action(qubits) Uncompute(eng) # runs inverse of the compute section """ compute_eng = engine.next_engine if not isinstance(compute_eng, ComputeEngine): raise NoComputeSectionError("Invalid call to Uncompute: No corresponding 'with Compute' statement found.") compute_eng.run_uncompute() drop_engine_after(engine)
Uncompute automatically. Example: .. code-block:: python with Compute(eng): do_something(qubits) action(qubits) Uncompute(eng) # runs inverse of the compute section
Uncompute
python
ProjectQ-Framework/ProjectQ
projectq/meta/_compute.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/meta/_compute.py
Apache-2.0
def canonical_ctrl_state(ctrl_state, num_qubits): """ Return canonical form for control state. Args: ctrl_state (int,str,CtrlAll): Initial control state representation num_qubits (int): number of control qubits Returns: Canonical form of control state (currently a string composed of '0' and '1') Note: In case of integer values for `ctrl_state`, the least significant bit applies to the first qubit in the qubit register, e.g. if ctrl_state == 2, its binary representation if '10' with the least significant bit being 0. This means in particular that the following are equivalent: .. code-block:: python canonical_ctrl_state(6, 3) == canonical_ctrl_state(6, '110') """ if not num_qubits: return '' if isinstance(ctrl_state, CtrlAll): if ctrl_state == CtrlAll.One: return '1' * num_qubits return '0' * num_qubits if isinstance(ctrl_state, int): # If the user inputs an integer, convert it to binary bit string converted_str = f'{ctrl_state:b}'.zfill(num_qubits)[::-1] if len(converted_str) != num_qubits: raise ValueError( f'Control state specified as {ctrl_state} ({converted_str}) is higher than maximum for {num_qubits} ' f'qubits: {2 ** num_qubits - 1}' ) return converted_str if isinstance(ctrl_state, str): # If the user inputs bit string, directly use it if len(ctrl_state) != num_qubits: raise ValueError( f'Control state {ctrl_state} has different length than the number of control qubits {num_qubits}' ) if not set(ctrl_state).issubset({'0', '1'}): raise ValueError(f'Control state {ctrl_state} has string other than 1 and 0') return ctrl_state raise TypeError('Input must be a string, an integer or an enum value of class State')
Return canonical form for control state. Args: ctrl_state (int,str,CtrlAll): Initial control state representation num_qubits (int): number of control qubits Returns: Canonical form of control state (currently a string composed of '0' and '1') Note: In case of integer values for `ctrl_state`, the least significant bit applies to the first qubit in the qubit register, e.g. if ctrl_state == 2, its binary representation if '10' with the least significant bit being 0. This means in particular that the following are equivalent: .. code-block:: python canonical_ctrl_state(6, 3) == canonical_ctrl_state(6, '110')
canonical_ctrl_state
python
ProjectQ-Framework/ProjectQ
projectq/meta/_control.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/meta/_control.py
Apache-2.0
def _has_compute_uncompute_tag(cmd): """ Return True if command cmd has a compute/uncompute tag. Args: cmd (Command object): a command object. """ for tag in cmd.tags: if tag in [UncomputeTag(), ComputeTag()]: return True return False
Return True if command cmd has a compute/uncompute tag. Args: cmd (Command object): a command object.
_has_compute_uncompute_tag
python
ProjectQ-Framework/ProjectQ
projectq/meta/_control.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/meta/_control.py
Apache-2.0
def __init__(self, qubits, ctrl_state=CtrlAll.One): """ Initialize the control engine. Args: qubits (list of Qubit objects): qubits conditional on which the following operations are executed. """ super().__init__() self._qubits = qubits self._state = ctrl_state
Initialize the control engine. Args: qubits (list of Qubit objects): qubits conditional on which the following operations are executed.
__init__
python
ProjectQ-Framework/ProjectQ
projectq/meta/_control.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/meta/_control.py
Apache-2.0
def __init__(self, engine, qubits, ctrl_state=CtrlAll.One): """ Enter a controlled section. Args: engine: Engine which handles the commands (usually MainEngine) qubits (list of Qubit objects): Qubits to condition on Enter the section using a with-statement: .. code-block:: python with Control(eng, ctrlqubits): ... """ self.engine = engine if isinstance(qubits, tuple): raise TypeError('Control qubits must be a list, not a tuple!') if isinstance(qubits, BasicQubit): qubits = [qubits] self._qubits = qubits self._state = canonical_ctrl_state(ctrl_state, len(self._qubits))
Enter a controlled section. Args: engine: Engine which handles the commands (usually MainEngine) qubits (list of Qubit objects): Qubits to condition on Enter the section using a with-statement: .. code-block:: python with Control(eng, ctrlqubits): ...
__init__
python
ProjectQ-Framework/ProjectQ
projectq/meta/_control.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/meta/_control.py
Apache-2.0
def run(self): """Run the stored circuit in reverse and check that local qubits have been deallocated.""" if self._deallocated_qubit_ids != self._allocated_qubit_ids: raise QubitManagementError( "\n Error. Qubits have been allocated in 'with " + "Dagger(eng)' context,\n which have not explicitly " + "been deallocated.\n" + "Correct usage:\n" + "with Dagger(eng):\n" + " qubit = eng.allocate_qubit()\n" + " ...\n" + " del qubit[0]\n" ) for cmd in reversed(self._commands): self.send([cmd.get_inverse()])
Run the stored circuit in reverse and check that local qubits have been deallocated.
run
python
ProjectQ-Framework/ProjectQ
projectq/meta/_dagger.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/meta/_dagger.py
Apache-2.0
def receive(self, command_list): """ Receive a list of commands and store them for later inversion. Args: command_list (list<Command>): List of commands to temporarily store. """ for cmd in command_list: if cmd.gate == Allocate: self._allocated_qubit_ids.add(cmd.qubits[0][0].id) elif cmd.gate == Deallocate: self._deallocated_qubit_ids.add(cmd.qubits[0][0].id) self._commands.extend(command_list)
Receive a list of commands and store them for later inversion. Args: command_list (list<Command>): List of commands to temporarily store.
receive
python
ProjectQ-Framework/ProjectQ
projectq/meta/_dagger.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/meta/_dagger.py
Apache-2.0
def __init__(self, engine): """ Enter an inverted section. Args: engine: Engine which handles the commands (usually MainEngine) Example (executes an inverse QFT): .. code-block:: python with Dagger(eng): QFT | qubits """ self.engine = engine self._dagger_eng = None
Enter an inverted section. Args: engine: Engine which handles the commands (usually MainEngine) Example (executes an inverse QFT): .. code-block:: python with Dagger(eng): QFT | qubits
__init__
python
ProjectQ-Framework/ProjectQ
projectq/meta/_dagger.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/meta/_dagger.py
Apache-2.0
def __init__(self, num): """ Initialize a LoopEngine. Args: num (int): Number of loop iterations. """ super().__init__() self._tag = LoopTag(num) self._cmd_list = [] self._allocated_qubit_ids = set() self._deallocated_qubit_ids = set() # key: qubit id of a local qubit, i.e. a qubit which has been allocated # and deallocated within the loop body. # value: list contain reference to each weakref qubit with this qubit # id either within control_qubits or qubits. self._refs_to_local_qb = {} self._next_engines_support_loop_tag = False
Initialize a LoopEngine. Args: num (int): Number of loop iterations.
__init__
python
ProjectQ-Framework/ProjectQ
projectq/meta/_loop.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/meta/_loop.py
Apache-2.0
def run(self): """ Apply the loop statements to all stored commands. Unrolls the loop if LoopTag is not supported by any of the following engines, i.e., if .. code-block:: python is_meta_tag_supported(next_engine, LoopTag) == False """ error_message = ( "\n Error. Qubits have been allocated in with " "Loop(eng, num) context,\n which have not " "explicitly been deallocated in the Loop context.\n" "Correct usage:\nwith Loop(eng, 5):\n" " qubit = eng.allocate_qubit()\n" " ...\n" " del qubit[0]\n" ) if not self._next_engines_support_loop_tag: # pylint: disable=too-many-nested-blocks # Unroll the loop # Check that local qubits have been deallocated: if self._deallocated_qubit_ids != self._allocated_qubit_ids: raise QubitManagementError(error_message) if len(self._allocated_qubit_ids) == 0: # No local qubits, just send the circuit num times for i in range(self._tag.num): self.send(deepcopy(self._cmd_list)) else: # Ancilla qubits have been allocated in loop body # For each iteration, allocate and deallocate a new qubit and # replace the qubit id in all commands using it. for i in range(self._tag.num): if i == 0: # Don't change local qubit ids self.send(deepcopy(self._cmd_list)) else: # Change local qubit ids before sending them for refs_loc_qubit in self._refs_to_local_qb.values(): new_qb_id = self.main_engine.get_new_qubit_id() for qubit_ref in refs_loc_qubit: qubit_ref.id = new_qb_id self.send(deepcopy(self._cmd_list)) else: # Next engines support loop tag so no unrolling needed only # check that all qubits have been deallocated which have been # allocated in the loop body if self._deallocated_qubit_ids != self._allocated_qubit_ids: raise QubitManagementError(error_message)
Apply the loop statements to all stored commands. Unrolls the loop if LoopTag is not supported by any of the following engines, i.e., if .. code-block:: python is_meta_tag_supported(next_engine, LoopTag) == False
run
python
ProjectQ-Framework/ProjectQ
projectq/meta/_loop.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/meta/_loop.py
Apache-2.0
def receive(self, command_list): # pylint: disable=too-many-branches """ Receive (and potentially temporarily store) all commands. Add LoopTag to all receiving commands and send to the next engine if a further engine is a LoopTag-handling engine. Otherwise store all commands (to later unroll them). Check that within the loop body, all allocated qubits have also been deallocated. If loop needs to be unrolled and ancilla qubits have been allocated within the loop body, then store a reference all these qubit ids (to change them when unrolling the loop) Args: command_list (list<Command>): List of commands to store and later unroll or, if there is a LoopTag-handling engine, add the LoopTag. """ # pylint: disable=too-many-nested-blocks if self._next_engines_support_loop_tag or self.next_engine.is_meta_tag_supported(LoopTag): # Loop tag is supported, send everything with a LoopTag # Don't check is_meta_tag_supported anymore self._next_engines_support_loop_tag = True if self._tag.num == 0: return for cmd in command_list: if cmd.gate == Allocate: self._allocated_qubit_ids.add(cmd.qubits[0][0].id) elif cmd.gate == Deallocate: self._deallocated_qubit_ids.add(cmd.qubits[0][0].id) cmd.tags.append(self._tag) self.send([cmd]) else: # LoopTag is not supported, save the full loop body self._cmd_list += command_list # Check for all local qubits allocated and deallocated in loop body for cmd in command_list: if cmd.gate == Allocate: self._allocated_qubit_ids.add(cmd.qubits[0][0].id) # Save reference to this local qubit self._refs_to_local_qb[cmd.qubits[0][0].id] = [cmd.qubits[0][0]] elif cmd.gate == Deallocate: self._deallocated_qubit_ids.add(cmd.qubits[0][0].id) # Save reference to this local qubit self._refs_to_local_qb[cmd.qubits[0][0].id].append(cmd.qubits[0][0]) else: # Add a reference to each place a local qubit id is # used as within either control_qubit or qubits for control_qubit in cmd.control_qubits: if control_qubit.id in self._allocated_qubit_ids: self._refs_to_local_qb[control_qubit.id].append(control_qubit) for qureg in cmd.qubits: for qubit in qureg: if qubit.id in self._allocated_qubit_ids: self._refs_to_local_qb[qubit.id].append(qubit)
Receive (and potentially temporarily store) all commands. Add LoopTag to all receiving commands and send to the next engine if a further engine is a LoopTag-handling engine. Otherwise store all commands (to later unroll them). Check that within the loop body, all allocated qubits have also been deallocated. If loop needs to be unrolled and ancilla qubits have been allocated within the loop body, then store a reference all these qubit ids (to change them when unrolling the loop) Args: command_list (list<Command>): List of commands to store and later unroll or, if there is a LoopTag-handling engine, add the LoopTag.
receive
python
ProjectQ-Framework/ProjectQ
projectq/meta/_loop.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/meta/_loop.py
Apache-2.0
def __init__(self, engine, num): """ Enter a looped section. Args: engine: Engine handling the commands (usually MainEngine) num (int): Number of loop iterations Example: .. code-block:: python with Loop(eng, 4): H | qb Rz(M_PI / 3.0) | qb Raises: TypeError: If number of iterations (num) is not an integer ValueError: If number of iterations (num) is not >= 0 """ self.engine = engine if not isinstance(num, int): raise TypeError("Number of loop iterations must be an int.") if num < 0: raise ValueError("Number of loop iterations must be >=0.") self.num = num self._loop_eng = None
Enter a looped section. Args: engine: Engine handling the commands (usually MainEngine) num (int): Number of loop iterations Example: .. code-block:: python with Loop(eng, 4): H | qb Rz(M_PI / 3.0) | qb Raises: TypeError: If number of iterations (num) is not an integer ValueError: If number of iterations (num) is not >= 0
__init__
python
ProjectQ-Framework/ProjectQ
projectq/meta/_loop.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/meta/_loop.py
Apache-2.0
def insert_engine(prev_engine, engine_to_insert): """ Insert an engine into the singly-linked list of engines. It also sets the correct main_engine for engine_to_insert. Args: prev_engine (projectq.cengines.BasicEngine): The engine just before the insertion point. engine_to_insert (projectq.cengines.BasicEngine): The engine to insert at the insertion point. """ if prev_engine.main_engine is not None: prev_engine.main_engine.n_engines += 1 if prev_engine.main_engine.n_engines > prev_engine.main_engine.n_engines_max: raise RuntimeError('Too many compiler engines added to the MainEngine!') engine_to_insert.main_engine = prev_engine.main_engine engine_to_insert.next_engine = prev_engine.next_engine prev_engine.next_engine = engine_to_insert
Insert an engine into the singly-linked list of engines. It also sets the correct main_engine for engine_to_insert. Args: prev_engine (projectq.cengines.BasicEngine): The engine just before the insertion point. engine_to_insert (projectq.cengines.BasicEngine): The engine to insert at the insertion point.
insert_engine
python
ProjectQ-Framework/ProjectQ
projectq/meta/_util.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/meta/_util.py
Apache-2.0
def drop_engine_after(prev_engine): """ Remove an engine from the singly-linked list of engines. Args: prev_engine (projectq.cengines.BasicEngine): The engine just before the engine to drop. Returns: Engine: The dropped engine. """ dropped_engine = prev_engine.next_engine prev_engine.next_engine = dropped_engine.next_engine if prev_engine.main_engine is not None: prev_engine.main_engine.n_engines -= 1 dropped_engine.next_engine = None dropped_engine.main_engine = None return dropped_engine
Remove an engine from the singly-linked list of engines. Args: prev_engine (projectq.cengines.BasicEngine): The engine just before the engine to drop. Returns: Engine: The dropped engine.
drop_engine_after
python
ProjectQ-Framework/ProjectQ
projectq/meta/_util.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/meta/_util.py
Apache-2.0
def make_tuple_of_qureg(qubits): """ Convert quantum input of "gate | quantum input" to internal formatting. A Command object only accepts tuples of Quregs (list of Qubit objects) as qubits input parameter. However, with this function we allow the user to use a more flexible syntax: 1) Gate | qubit 2) Gate | [qubit0, qubit1] 3) Gate | qureg 4) Gate | (qubit, ) 5) Gate | (qureg, qubit) where qubit is a Qubit object and qureg is a Qureg object. This function takes the right hand side of | and transforms it to the correct input parameter of a Command object which is: 1) -> Gate | ([qubit], ) 2) -> Gate | ([qubit0, qubit1], ) 3) -> Gate | (qureg, ) 4) -> Gate | ([qubit], ) 5) -> Gate | (qureg, [qubit]) Args: qubits: a Qubit object, a list of Qubit objects, a Qureg object, or a tuple of Qubit or Qureg objects (can be mixed). Returns: Canonical representation (tuple<qureg>): A tuple containing Qureg (or list of Qubits) objects. """ if not isinstance(qubits, tuple): qubits = (qubits,) qubits = list(qubits) for i, qubit in enumerate(qubits): if isinstance(qubit, BasicQubit): qubits[i] = [qubit] return tuple(qubits)
Convert quantum input of "gate | quantum input" to internal formatting. A Command object only accepts tuples of Quregs (list of Qubit objects) as qubits input parameter. However, with this function we allow the user to use a more flexible syntax: 1) Gate | qubit 2) Gate | [qubit0, qubit1] 3) Gate | qureg 4) Gate | (qubit, ) 5) Gate | (qureg, qubit) where qubit is a Qubit object and qureg is a Qureg object. This function takes the right hand side of | and transforms it to the correct input parameter of a Command object which is: 1) -> Gate | ([qubit], ) 2) -> Gate | ([qubit0, qubit1], ) 3) -> Gate | (qureg, ) 4) -> Gate | ([qubit], ) 5) -> Gate | (qureg, [qubit]) Args: qubits: a Qubit object, a list of Qubit objects, a Qureg object, or a tuple of Qubit or Qureg objects (can be mixed). Returns: Canonical representation (tuple<qureg>): A tuple containing Qureg (or list of Qubits) objects.
make_tuple_of_qureg
python
ProjectQ-Framework/ProjectQ
projectq/ops/_basics.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_basics.py
Apache-2.0
def generate_command(self, qubits): """ Generate a command. The command object created consists of the gate and the qubits being acted upon. Args: qubits: see BasicGate.make_tuple_of_qureg(qubits) Returns: A Command object containing the gate and the qubits. """ qubits = self.make_tuple_of_qureg(qubits) engines = [q.engine for reg in qubits for q in reg] eng = engines[0] if not all(e is eng for e in engines): raise ValueError('All qubits must belong to the same engine!') return Command(eng, self, qubits)
Generate a command. The command object created consists of the gate and the qubits being acted upon. Args: qubits: see BasicGate.make_tuple_of_qureg(qubits) Returns: A Command object containing the gate and the qubits.
generate_command
python
ProjectQ-Framework/ProjectQ
projectq/ops/_basics.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_basics.py
Apache-2.0
def __eq__(self, other): """ Equal operator. Return True if instance of the same class, unless other is an instance of :class:MatrixGate, in which case equality is to be checked by testing for existence and (approximate) equality of matrix representations. """ if isinstance(other, self.__class__): return True if isinstance(other, MatrixGate): return NotImplemented return False
Equal operator. Return True if instance of the same class, unless other is an instance of :class:MatrixGate, in which case equality is to be checked by testing for existence and (approximate) equality of matrix representations.
__eq__
python
ProjectQ-Framework/ProjectQ
projectq/ops/_basics.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_basics.py
Apache-2.0
def __init__(self, matrix=None): """ Initialize a MatrixGate object. Args: matrix(numpy.matrix): matrix which defines the gate. Default: None """ super().__init__() self._matrix = np.matrix(matrix) if matrix is not None else None
Initialize a MatrixGate object. Args: matrix(numpy.matrix): matrix which defines the gate. Default: None
__init__
python
ProjectQ-Framework/ProjectQ
projectq/ops/_basics.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_basics.py
Apache-2.0
def __eq__(self, other): """ Equal operator. Return True only if both gates have a matrix representation and the matrices are (approximately) equal. Otherwise return False. """ if not hasattr(other, 'matrix'): return False if not isinstance(self.matrix, np.matrix) or not isinstance(other.matrix, np.matrix): raise TypeError("One of the gates doesn't have the correct type (numpy.matrix) for the matrix attribute.") if self.matrix.shape == other.matrix.shape and np.allclose( self.matrix, other.matrix, rtol=RTOL, atol=ATOL, equal_nan=False ): return True return False
Equal operator. Return True only if both gates have a matrix representation and the matrices are (approximately) equal. Otherwise return False.
__eq__
python
ProjectQ-Framework/ProjectQ
projectq/ops/_basics.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_basics.py
Apache-2.0
def __init__(self, angle): """ Initialize a basic rotation gate. Args: angle (float): Angle of rotation (saved modulo 4 * pi) """ super().__init__() rounded_angle = round(float(angle) % (4.0 * math.pi), ANGLE_PRECISION) if rounded_angle > 4 * math.pi - ANGLE_TOLERANCE: rounded_angle = 0.0 self.angle = rounded_angle
Initialize a basic rotation gate. Args: angle (float): Angle of rotation (saved modulo 4 * pi)
__init__
python
ProjectQ-Framework/ProjectQ
projectq/ops/_basics.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_basics.py
Apache-2.0
def to_string(self, symbols=False): """ Return the string representation of a BasicRotationGate. Args: symbols (bool): uses the pi character and round the angle for a more user friendly display if True, full angle written in radian otherwise. """ if symbols: angle = f"({str(round(self.angle / math.pi, 3))}{unicodedata.lookup('GREEK SMALL LETTER PI')})" else: angle = f"({str(self.angle)})" return str(self.__class__.__name__) + angle
Return the string representation of a BasicRotationGate. Args: symbols (bool): uses the pi character and round the angle for a more user friendly display if True, full angle written in radian otherwise.
to_string
python
ProjectQ-Framework/ProjectQ
projectq/ops/_basics.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_basics.py
Apache-2.0
def get_inverse(self): """Return the inverse of this rotation gate (negate the angle, return new object).""" if self.angle == 0: return self.__class__(0) return self.__class__(-self.angle + 4 * math.pi)
Return the inverse of this rotation gate (negate the angle, return new object).
get_inverse
python
ProjectQ-Framework/ProjectQ
projectq/ops/_basics.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_basics.py
Apache-2.0
def get_merged(self, other): """ Return self merged with another gate. Default implementation handles rotation gate of the same type, where angles are simply added. Args: other: Rotation gate of same type. Raises: NotMergeable: For non-rotation gates or rotation gates of different type. Returns: New object representing the merged gates. """ if isinstance(other, self.__class__): return self.__class__(self.angle + other.angle) raise NotMergeable("Can't merge different types of rotation gates.")
Return self merged with another gate. Default implementation handles rotation gate of the same type, where angles are simply added. Args: other: Rotation gate of same type. Raises: NotMergeable: For non-rotation gates or rotation gates of different type. Returns: New object representing the merged gates.
get_merged
python
ProjectQ-Framework/ProjectQ
projectq/ops/_basics.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_basics.py
Apache-2.0
def __eq__(self, other): """Return True if same class and same rotation angle.""" if isinstance(other, self.__class__): return self.angle == other.angle return False
Return True if same class and same rotation angle.
__eq__
python
ProjectQ-Framework/ProjectQ
projectq/ops/_basics.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_basics.py
Apache-2.0
def __init__(self, angle): """ Initialize a basic rotation gate. Args: angle (float): Angle of rotation (saved modulo 2 * pi) """ super().__init__() rounded_angle = round(float(angle) % (2.0 * math.pi), ANGLE_PRECISION) if rounded_angle > 2 * math.pi - ANGLE_TOLERANCE: rounded_angle = 0.0 self.angle = rounded_angle
Initialize a basic rotation gate. Args: angle (float): Angle of rotation (saved modulo 2 * pi)
__init__
python
ProjectQ-Framework/ProjectQ
projectq/ops/_basics.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_basics.py
Apache-2.0
def get_inverse(self): """Return the inverse of this rotation gate (negate the angle, return new object).""" if self.angle == 0: return self.__class__(0) return self.__class__(-self.angle + 2 * math.pi)
Return the inverse of this rotation gate (negate the angle, return new object).
get_inverse
python
ProjectQ-Framework/ProjectQ
projectq/ops/_basics.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_basics.py
Apache-2.0
def get_merged(self, other): """ Return self merged with another gate. Default implementation handles rotation gate of the same type, where angles are simply added. Args: other: Rotation gate of same type. Raises: NotMergeable: For non-rotation gates or rotation gates of different type. Returns: New object representing the merged gates. """ if isinstance(other, self.__class__): return self.__class__(self.angle + other.angle) raise NotMergeable("Can't merge different types of rotation gates.")
Return self merged with another gate. Default implementation handles rotation gate of the same type, where angles are simply added. Args: other: Rotation gate of same type. Raises: NotMergeable: For non-rotation gates or rotation gates of different type. Returns: New object representing the merged gates.
get_merged
python
ProjectQ-Framework/ProjectQ
projectq/ops/_basics.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_basics.py
Apache-2.0
def __eq__(self, other): """Return True if same class and same rotation angle.""" if isinstance(other, self.__class__): return self.angle == other.angle return False
Return True if same class and same rotation angle.
__eq__
python
ProjectQ-Framework/ProjectQ
projectq/ops/_basics.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_basics.py
Apache-2.0
def __init__(self, math_fun): """ Initialize a BasicMathGate by providing the mathematical function that it implements. Args: math_fun (function): Function which takes as many int values as input, as the gate takes registers. For each of these values, it then returns the output (i.e., it returns a list/tuple of output values). Example: .. code-block:: python def add(a, b): return (a, a + b) super().__init__(add) If the gate acts on, e.g., fixed point numbers, the number of bits per register is also required in order to describe the action of such a mathematical gate. For this reason, there is .. code-block:: python BasicMathGate.get_math_function(qubits) which can be overwritten by the gate deriving from BasicMathGate. Example: .. code-block:: python def get_math_function(self, qubits): n = len(qubits[0]) scal = 2.0**n def math_fun(a): return (int(scal * (math.sin(math.pi * a / scal))),) return math_fun """ super().__init__() def math_function(arg): return list(math_fun(*arg)) self._math_function = math_function
Initialize a BasicMathGate by providing the mathematical function that it implements. Args: math_fun (function): Function which takes as many int values as input, as the gate takes registers. For each of these values, it then returns the output (i.e., it returns a list/tuple of output values). Example: .. code-block:: python def add(a, b): return (a, a + b) super().__init__(add) If the gate acts on, e.g., fixed point numbers, the number of bits per register is also required in order to describe the action of such a mathematical gate. For this reason, there is .. code-block:: python BasicMathGate.get_math_function(qubits) which can be overwritten by the gate deriving from BasicMathGate. Example: .. code-block:: python def get_math_function(self, qubits): n = len(qubits[0]) scal = 2.0**n def math_fun(a): return (int(scal * (math.sin(math.pi * a / scal))),) return math_fun
__init__
python
ProjectQ-Framework/ProjectQ
projectq/ops/_basics.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_basics.py
Apache-2.0
def __init__( self, engine, gate, qubits, controls=(), tags=(), control_state=CtrlAll.One ): # pylint: disable=too-many-arguments """ Initialize a Command object. Note: control qubits (Command.control_qubits) are stored as a list of qubits, and command tags (Command.tags) as a list of tag-objects. All functions within this class also work if WeakQubitRefs are supplied instead of normal Qubit objects (see WeakQubitRef). Args: engine (projectq.cengines.BasicEngine): engine which created the qubit (mostly the MainEngine) gate (projectq.ops.Gate): Gate to be executed qubits (tuple[Qureg]): Tuple of quantum registers (to which the gate is applied) controls (Qureg|list[Qubit]): Qubits that condition the command. tags (list[object]): Tags associated with the command. control_state(int,str,projectq.meta.CtrlAll) Control state for any control qubits """ qubits = tuple([WeakQubitRef(qubit.engine, qubit.id) for qubit in qreg] for qreg in qubits) self.gate = gate self.tags = list(tags) self.qubits = qubits # property self.control_qubits = controls # property self.engine = engine # property self.control_state = control_state # property
Initialize a Command object. Note: control qubits (Command.control_qubits) are stored as a list of qubits, and command tags (Command.tags) as a list of tag-objects. All functions within this class also work if WeakQubitRefs are supplied instead of normal Qubit objects (see WeakQubitRef). Args: engine (projectq.cengines.BasicEngine): engine which created the qubit (mostly the MainEngine) gate (projectq.ops.Gate): Gate to be executed qubits (tuple[Qureg]): Tuple of quantum registers (to which the gate is applied) controls (Qureg|list[Qubit]): Qubits that condition the command. tags (list[object]): Tags associated with the command. control_state(int,str,projectq.meta.CtrlAll) Control state for any control qubits
__init__
python
ProjectQ-Framework/ProjectQ
projectq/ops/_command.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_command.py
Apache-2.0
def __deepcopy__(self, memo): """Deepcopy implementation. Engine should stay a reference.""" return Command( self.engine, deepcopy(self.gate), self.qubits, list(self.control_qubits), deepcopy(self.tags), )
Deepcopy implementation. Engine should stay a reference.
__deepcopy__
python
ProjectQ-Framework/ProjectQ
projectq/ops/_command.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_command.py
Apache-2.0
def get_inverse(self): """ Get the command object corresponding to the inverse of this command. Inverts the gate (if possible) and creates a new command object from the result. Raises: NotInvertible: If the gate does not provide an inverse (see BasicGate.get_inverse) """ return Command( self._engine, projectq.ops.get_inverse(self.gate), self.qubits, list(self.control_qubits), deepcopy(self.tags), )
Get the command object corresponding to the inverse of this command. Inverts the gate (if possible) and creates a new command object from the result. Raises: NotInvertible: If the gate does not provide an inverse (see BasicGate.get_inverse)
get_inverse
python
ProjectQ-Framework/ProjectQ
projectq/ops/_command.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_command.py
Apache-2.0
def get_merged(self, other): """ Merge this command with another one and return the merged command object. Args: other: Other command to merge with this one (self) Raises: NotMergeable: if the gates don't supply a get_merged()-function or can't be merged for other reasons. """ if self.tags == other.tags and self.all_qubits == other.all_qubits and self.engine == other.engine: return Command( self.engine, self.gate.get_merged(other.gate), self.qubits, self.control_qubits, deepcopy(self.tags), ) raise projectq.ops.NotMergeable("Commands not mergeable.")
Merge this command with another one and return the merged command object. Args: other: Other command to merge with this one (self) Raises: NotMergeable: if the gates don't supply a get_merged()-function or can't be merged for other reasons.
get_merged
python
ProjectQ-Framework/ProjectQ
projectq/ops/_command.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_command.py
Apache-2.0
def _order_qubits(self, qubits): """ Order the given qubits according to their IDs (for unique comparison of commands). Args: qubits: Tuple of quantum registers (i.e., tuple of lists of qubits) Returns: Ordered tuple of quantum registers """ ordered_qubits = list(qubits) # e.g. [[0,4],[1,2,3]] interchangeable_qubit_indices = self.interchangeable_qubit_indices for old_positions in interchangeable_qubit_indices: new_positions = sorted(old_positions, key=lambda x: ordered_qubits[x][0].id) qubits_new_order = [ordered_qubits[i] for i in new_positions] for i, pos in enumerate(old_positions): ordered_qubits[pos] = qubits_new_order[i] return tuple(ordered_qubits)
Order the given qubits according to their IDs (for unique comparison of commands). Args: qubits: Tuple of quantum registers (i.e., tuple of lists of qubits) Returns: Ordered tuple of quantum registers
_order_qubits
python
ProjectQ-Framework/ProjectQ
projectq/ops/_command.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_command.py
Apache-2.0
def control_qubits(self, qubits): """ Set control_qubits to qubits. Args: control_qubits (Qureg): quantum register """ self._control_qubits = [WeakQubitRef(qubit.engine, qubit.id) for qubit in qubits] self._control_qubits = sorted(self._control_qubits, key=lambda x: x.id)
Set control_qubits to qubits. Args: control_qubits (Qureg): quantum register
control_qubits
python
ProjectQ-Framework/ProjectQ
projectq/ops/_command.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_command.py
Apache-2.0