-
Notifications
You must be signed in to change notification settings - Fork 13
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Qaoa energy order #38
Open
danlkv
wants to merge
2
commits into
dev
Choose a base branch
from
qaoa_energy_order
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,114 @@ | ||
from networkx.classes.function import number_of_nodes | ||
import networkx as nx | ||
import qtensor | ||
|
||
def get_graph_order(graph: nx.Graph, opt_key:str): | ||
opt = qtensor.toolbox.get_ordering_algo(opt_key) | ||
peo, path = opt._get_ordering_ints(graph) # | ||
return peo | ||
|
||
|
||
def circ2gvars(qubit_count, circuit, pdict={}, | ||
omit_terminals=True): | ||
""" | ||
Constructs a graph from a circuit in the form of a | ||
list of lists. | ||
|
||
Parameters | ||
---------- | ||
qubit_count : int | ||
number of qubits in the circuit | ||
circuit : list of lists | ||
quantum circuit as returned by | ||
:py:meth:`operators.read_circuit_file` | ||
pdict : dict | ||
Dictionary with placeholders if any parameteric gates | ||
were unresolved | ||
max_depth : int, default None | ||
Maximal depth of the circuit which should be used | ||
omit_terminals : bool, default True | ||
If terminal nodes should be excluded from the final | ||
graph. | ||
|
||
Returns | ||
------- | ||
gvars: dict(int: list) | ||
""" | ||
import functools, itertools | ||
import qtree.operators as ops | ||
from qtree.optimizer import Var | ||
|
||
# The circuit is built from left to right, as it operates | ||
# on the ket ( |0> ) from the left. We thus first place | ||
# the bra ( <x| ) and then put gates in the reverse order | ||
|
||
# Fill the variable `frame` | ||
layer_variables = list(range(qubit_count)) | ||
result = {i: [v] for i, v in enumerate(layer_variables)} | ||
current_var_idx = qubit_count | ||
|
||
# Populate nodes and save variables of the bra | ||
bra_variables = [] | ||
for var in layer_variables: | ||
bra_variables.append(Var(var, name=f"o_{var}")) | ||
|
||
# Place safeguard measurement circuits before and after | ||
# the circuit | ||
measurement_circ = [[ops.M(qubit) for qubit in range(qubit_count)]] | ||
|
||
combined_circ = functools.reduce( | ||
lambda x, y: itertools.chain(x, y), | ||
[measurement_circ, reversed(circuit)]) | ||
|
||
# Start building the graph in reverse order | ||
for layer in combined_circ: | ||
for op in layer: | ||
# Update current variable frame | ||
for qubit in op.changed_qubits: | ||
new_var = Var(current_var_idx, name=f"o_{current_var_idx}") | ||
result[qubit].append(new_var) | ||
current_var_idx += 1 | ||
|
||
for qubit in range(qubit_count): | ||
var = layer_variables[qubit] | ||
new_var = Var(current_var_idx, name=f'i_{qubit}', size=2) | ||
# update graph and variable `frame` | ||
result[qubit].append(new_var) | ||
current_var_idx += 1 | ||
|
||
if omit_terminals: | ||
for k in result: | ||
# first and last elements will always be terminals | ||
result[k] = result[k][1:-1] | ||
|
||
return result | ||
|
||
|
||
def build_connectivity_graph(circuit): | ||
g = nx.Graph() | ||
for gate in circuit: | ||
if len(gate.qubits) == 2: | ||
# will add muliple edges several times, but who cares | ||
g.add_edge(gate.qubits[0], gate.qubits[1]) | ||
return g | ||
|
||
|
||
def get_qaoa_exp_ordering(circuit: list, algo='greedy') -> list: | ||
graph = build_connectivity_graph(circuit) | ||
cverts = circ2gvars(graph.number_of_nodes(), [circuit]) | ||
super_order = get_graph_order(graph, algo) | ||
order = [] | ||
for i in super_order: | ||
order += cverts[i] | ||
return order | ||
|
||
|
||
class QAOAEnergyOptimizer(qtensor.optimisation.GreedyOptimizer): | ||
# debt: this class is only usable for a single instance | ||
def __init__(self, circuit, *args, algo='greedy', **kwargs): | ||
super().__init__(*args, **kwargs) | ||
self.circuit = circuit | ||
self.algo = algo | ||
|
||
def _get_ordering_ints(self, old_graph, free_vars): | ||
return get_qaoa_exp_ordering(self.circuit, algo=self.algo) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
import qtensor | ||
import qtree | ||
import networkx as nx | ||
|
||
|
||
def test_column_verts(): | ||
from qtensor.tools.qaoa_ordering import circ2gvars | ||
g = nx.Graph() | ||
g.add_edge(0, 1) | ||
p = 2 | ||
comp = qtensor.DefaultQAOAComposer(g, gamma=[1]*p, beta=[2]*p) | ||
comp.energy_expectation_lightcone((0, 1)) | ||
cverts = circ2gvars(g.number_of_nodes(), [comp.circuit]) | ||
print('cverts', cverts) | ||
assert len(cverts.keys()) == g.number_of_nodes() | ||
assert len(cverts[0]) == 2*p + 2 + 1 | ||
|
||
tn = qtensor.optimisation.QtreeTensorNet.from_qtree_gates(comp.circuit) | ||
lg = tn.get_line_graph() | ||
verts = set(lg.nodes) | ||
cvert_merge = sum(cverts.values(), []) | ||
cvert_merge = [int(x) for x in cvert_merge] | ||
assert len(cvert_merge) == len(verts) | ||
assert set(cvert_merge) == verts | ||
|
||
|
||
def test_qaoa_ordering(): | ||
from qtensor.tools.qaoa_ordering import get_qaoa_exp_ordering | ||
p = 3 | ||
N = 50 | ||
g = nx.path_graph(N) | ||
comp = qtensor.DefaultQAOAComposer(g, gamma=[1]*p, beta=[2]*p) | ||
comp.energy_expectation_lightcone((0, 1)) | ||
order = get_qaoa_exp_ordering(comp.circuit, algo='greedy') | ||
tn = qtensor.optimisation.QtreeTensorNet.from_qtree_gates(comp.circuit) | ||
lg = tn.get_line_graph() | ||
nodes, path = qtensor.utils.get_neighbors_path(lg, peo=order) | ||
width = max(path) | ||
|
||
assert width == 2*p + 1 | ||
|
||
def test_qaoa_ordering_tree(): | ||
import time | ||
from qtensor.tools.qaoa_ordering import get_qaoa_exp_ordering | ||
p = 8 | ||
degree = 5 | ||
start = time.time() | ||
g = qtensor.toolbox.bethe_graph(p, degree=degree) | ||
print('P = ', p) | ||
print('D = ', degree) | ||
print('Bethe num of nodes', g.number_of_nodes()) | ||
comp = qtensor.DefaultQAOAComposer(g, gamma=[1]*p, beta=[2]*p) | ||
comp.energy_expectation_lightcone((0, 1)) | ||
order = get_qaoa_exp_ordering(comp.circuit, algo='greedy') | ||
print('Got ordering') | ||
tn = qtensor.optimisation.QtreeTensorNet.from_qtree_gates(comp.circuit) | ||
lg = tn.get_line_graph() | ||
assert lg.number_of_nodes() == len(order) | ||
print('Bethe LineGraph # of nodes', len(order)) | ||
nodes, path = qtensor.utils.get_neighbors_path(lg, peo=order) | ||
width = max(path) | ||
print('Synthetic width', width) | ||
print('Total time', time.time() - start) | ||
|
||
assert width == 2*p + 1 |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@cameton this function finds all the line graph vertices for qubit, then gets an ordering on the connectivity graph, then the order is constructed based on that
super_order
.