<jupyter_start><jupyter_text>Set up the functions<jupyter_code>@ex.provider
def graph(n, d, seed, graph_type='random'):
    if graph_type=='grid':
        n = int(np.sqrt(n))
        return nx.grid_graph(dim=[n, n], periodic=True)
    else:
        return qt.toolbox.random_graph(nodes=n, degree=d, seed=seed)

@ex.provider
def circuit(graph, p, circuit_type, composer_type='ZZ', operators='diagonal', edge_idx=0):
    beta, gamma = [.1]*p, [.2]*p
    if composer_type=='ZZ':
        if operators=='full':
            comp = qt.ZZQtreeFullQAOAComposer(graph, beta=beta, gamma=gamma)
        else:
            comp = qt.ZZQtreeQAOAComposer(graph, beta=beta, gamma=gamma)
    if composer_type=='default':
        if operators=='full':
            comp = qt.QtreeFullQAOAComposer(graph, beta=beta, gamma=gamma)
        else:
            comp = qt.QtreeQAOAComposer(graph, beta=beta, gamma=gamma)
            
    if circuit_type == 'ansatz':
        comp.ansatz_state()
    if circuit_type == 'energy':
        comp.energy_expectation_lightcone(list(graph.edges())[edge_idx])
    return comp.circuit
@ex.provider
def circuit_sim_costs(circuit, ordering_algo='greedy'):
    tn = qt.optimisation.TensorNet.QtreeTensorNet.from_qtree_gates(circuit)
    if ordering_algo=='greedy':
        opt = qt.optimisation.Optimizer.DefaultOptimizer()
    elif 'tamaki' in ordering_algo:
        if '_' in ordering_algo:
            _, time_str = ordering_algo.split('_')
            wait_time=int(time_str)
        else:
            wait_time=15
        opt = qt.optimisation.Optimizer.TamakiOptimizer(wait_time=wait_time)
    peo, _ = opt.optimize(tn)
    costs, mems = tn.simulation_cost(peo)
    return tuple(costs), tuple(mems)

@ex.provider
def max_memory(circuit_sim_costs):
    costs, mems = circuit_sim_costs
    return max(mems)

@ex.provider
def sum_flops(circuit_sim_costs):
    costs, mems = circuit_sim_costs
    return sum(costs)<jupyter_output><empty_output><jupyter_text>Plot complexity graphs<jupyter_code>plots_dir = '../data/figures/diagonal_zz_paper/'
Ns = 2*(1.41*np.arange(3,24)).astype(int)
fig = ex.plot_variables2d(('sum_flops','max_memory'),
                          plot_kwargs=dict(marker='*'),
                          circuit_type=['energy'],
                          operators=['diagonal', 'full']
                          ,graph_type='grid'
                          ,p=[1,2,3,4]
                   ,seed=[100], d=[3], n=[200], composer_type='ZZ'
                   )
titles = (x for x in ('Energy expectation lightcone', 'Ansatz state'))
titles = (x for x in ('Sum FLOPs', 'Maximum memory'))
for ax in fig.axes:
    ax.grid(which='major', color='0.8')
    ax.grid(which='minor', color='0.8', alpha=.5)
    ax.set_title(next(titles), fontsize=10, fontfamily='serif', style='italic')
    ax.set_yscale('log')
    ax.legend(loc='upper left')
fig.suptitle('Diagonal simplification', fontfamily='serif', style='italic')
fig.tight_layout(rect=[0, 0.03, 1, 0.95])
fig.set_dpi(120)
plt.savefig(plots_dir+'/diagonal_simplification_flops.pdf')
fig = ex.plot_variables2d(('sum_flops','max_memory'),
                          plot_kwargs=dict(marker='*'),
                          circuit_type=['energy']
                          ,composer_type=['ZZ', 'default']
                          ,p=[1,2,3,4,5]
                          ,graph_type=['grid']
                          ,n=[200]
                   ,seed=[100], d=[3], operators=['diagonal']
                   )

titles = (x for x in ('Energy expectation lightcone', 'Ansatz state'))
titles = (x for x in ('Sum FLOPs', 'Maximum memory'))
for ax in fig.axes:
    ax.grid(which='major', color='0.8')
    ax.grid(which='minor', color='0.8', alpha=.1)
    ax.set_title(next(titles), fontsize=10, fontfamily='serif', style='italic')
    ax.set_yscale('log')
    ax.legend(title='Circuit gate type', loc='upper left')
fig.suptitle('ZZ gate simplification', fontfamily='serif', style='italic')
fig.tight_layout(rect=[0, 0.03, 1, 0.95])
fig.set_dpi(120)
fig.set_size_inches((8,3))
plt.savefig(plots_dir+'/zz_simplification_flops.pdf')<jupyter_output><empty_output><jupyter_text>Problem graph<jupyter_code>import matplotlib as mpl
blue = mpl.cm.get_cmap('gnuplot2')(.51)
yellow = mpl.cm.get_cmap('gnuplot2')(.84)

f = plt.figure(figsize=(5, 4), dpi=(100))
G = nx.grid_graph([10, 10], periodic=True)
p = 3
G = qt.utils.get_edge_subgraph(G, list(G.edges())[0], p)
G = nx.relabel_nodes(G, {n:i for i, n in enumerate(G.nodes)})
colors =  [blue if node in (8, 23) else yellow for node in G.nodes]

nx.draw_kamada_kawai(G, node_color=colors, with_labels=True)
#nx.draw_spring(G, node_color=colors, with_labels=True)
plt.title(f'Lightcone subgraph for p={p}', style='italic', fontfamily='serif')
plt.savefig(plots_dir+f'/lightcone_graph_p{p}.pdf')<jupyter_output><empty_output><jupyter_text>Line graph<jupyter_code>p=2
circuits = ex.map_variable('circuit', p=[p], composer_type=['ZZ', 'default']
                           , operators=['diagonal', 'full']
                           , n=[200]
                           , graph_type=['grid']
                           , circuit_type=['energy']
                   ,seed=[100], d=[3]
                   )

fig, axs = plt.subplots(1,3, figsize=(10, 3), dpi=100)
titles = iter(['ZZ diagonal', 'diagonal', 'full tensor'])
indices = iter([(0, 0), (1, 0), (1,1)])
for ax in axs:
    circuit = circuits[next(indices)]
    plt.sca(ax)
    
    tn = qt.optimisation.TensorNet.QtreeTensorNet.from_qtree_gates(circuit)
    g = tn.get_line_graph()
    nx.draw_kamada_kawai(g, node_color=[yellow], node_size=10)
    plt.title(next(titles), style='italic', fontfamily='serif', fontsize=11)
    print('nnodes', g.number_of_nodes())
    
plt.suptitle(f'Line graphs for different representation of gates, p={p}', style='italic', fontfamily='serif')
fig.tight_layout(rect=[0, 0.03, 1, 0.95])

plt.savefig(plots_dir+f'/lightcone_line_graph_p{p}.pdf')<jupyter_output><empty_output><jupyter_text>Problem graph<jupyter_code>g.number_of_nodes()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1574946289869443, 'fraction_numerical': 0.021318790282597918, 'mean_word_length': 3.3259471050750538, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '383811', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 2291, 'n_tokens_neox': 2147, 'n_words': 365, 'path': 'analysis/Diagonal and ZZ plots.ipynb', 'repo_name': 'marwahaha/QTensor', 'size': '6051'}