{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "94471e6e",
   "metadata": {},
   "outputs": [],
   "source": [
    "from qiskit import QuantumCircuit\n",
    "\n",
    "from qndk.quantum_network import LinkSpec, QPUSpec, QubitLayout, SwitchSpec\n",
    "from qndk.quantum_network.topologies import build_clos\n",
    "from qndk.partition.kl import KernighanLinPartitioner\n",
    "from qndk.simulator.dqc import DQCScheduler, SimulationResult\n",
    "\n",
    "def new_circuit(rounds=3, local_depth=4):\n",
    "    clusters = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)]\n",
    "    qc = QuantumCircuit(12)\n",
    "    for _ in range(rounds):\n",
    "        for _ in range(local_depth):\n",
    "            for g in clusters:\n",
    "                qc.cx(g[0], g[1]); qc.cx(g[1], g[2]); qc.cx(g[0], g[2])\n",
    "        qc.cx(0, 3); qc.cx(1, 4); qc.cx(2, 5)\n",
    "        qc.cx(6, 9); qc.cx(7, 10); qc.cx(8, 11)\n",
    "    return qc\n",
    "\n",
    "def new_network(bsm=8, comp_qubits=3, comm_qubits=3, coherence_ms=1000.0, gen_rate_hz=1e4,\n",
    "             link_length_m=1000.0):\n",
    "    return build_clos(\n",
    "        qpu_spec=QPUSpec(\n",
    "            comp_qubits=comp_qubits, comm_qubits=comm_qubits, connectivity=\"all2all\",\n",
    "            layout=QubitLayout(flatten=True),\n",
    "            comm_qubit_coherence_time_ms=coherence_ms),\n",
    "        switch_spec=SwitchSpec(gen_rate_hz=gen_rate_hz, bsm_count=bsm),\n",
    "        link_spec=LinkSpec(length_m=link_length_m))\n",
    "\n",
    "def run(qc, network, lookahead_layers) -> SimulationResult:\n",
    "    pr = KernighanLinPartitioner(circuit=qc, network=network).partition()\n",
    "    sim = DQCScheduler(pr)\n",
    "    sim.use_epr_lookahead_pregen = lookahead_layers > 0\n",
    "    sim.num_lookahead_layers = max(lookahead_layers, 1)\n",
    "    sim_result = sim.run_simulation()\n",
    "    return sim_result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b7e8e6cf",
   "metadata": {},
   "outputs": [],
   "source": [
    "qc = QuantumCircuit(6)\n",
    "[(qc.h(i), qc.cx(i, i+1), qc.t(i)) for i in range(5)]\n",
    "\n",
    "result = run(qc, new_network(comp_qubits=2, comm_qubits=2), 1)\n",
    "print(result.execution_log_summary_table())\n",
    "result.dag_timestep_animation(show_qubits=True, scale=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e9902db6",
   "metadata": {},
   "outputs": [],
   "source": [
    "tiny = new_circuit(rounds=1, local_depth=1)\n",
    "_ = run(tiny, new_network(), 0).plot_gantt_by_device(title=\"No lookahead: remote gate waits on EPR\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f661d539",
   "metadata": {},
   "outputs": [],
   "source": [
    "_ = run(tiny, new_network(), 8).plot_gantt_by_device(title=\"Lookahead: EPR pre-generated during local gates\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "223e7301",
   "metadata": {},
   "outputs": [],
   "source": [
    "circuit = new_circuit()\n",
    "result = None\n",
    "print(f\"{'lookahead':<14}{'makespan (ms)':<16}\")\n",
    "for layers in (0, 1, 2, 4, 8, 16):\n",
    "    result = run(circuit, new_network(), layers)\n",
    "    label = \"none\" if layers == 0 else f\"{layers} layers\"\n",
    "    print(f\"{label:<14}{result.final_timestep:<16.2f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "636c7008",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(f\"{'coherence (ms)':<16}{'makespan (ms)':<16}\")\n",
    "for coherence in (1000.0, 1.0, 0.3, 0.1, 0.01, 0.001):\n",
    "    result = run(circuit, new_network(coherence_ms=coherence), 8)\n",
    "    print(f\"{coherence:<16}{result.final_timestep:<16.2f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "12609ae8",
   "metadata": {},
   "outputs": [],
   "source": [
    "result = run(circuit, new_network(coherence_ms=0.1), 8)\n",
    "ec = result.epr_cost()\n",
    "eg = result.epr_gens()\n",
    "_ = result.plot_epr_lifecycle(\n",
    "        title=f\"Deep lookahead, short comm-qubit coherence. Lots of expiration\\n{ec} eprs consumed    {eg} eprs generated\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ce91df82",
   "metadata": {},
   "outputs": [],
   "source": [
    "from collections import Counter\n",
    "\n",
    "print(f\"{'coherence':<11}{'length (m)':<12}{'pre-gen':<9}{'on-demand':<11}\"\n",
    "      f\"{'consumed':<10}{'expired':<9}{'gen total':<10}{'execution time':<10}\")\n",
    "for co in (0.01, 0.1, 1):\n",
    "    for length in (10.0, 1_000.0, 20_000.0, 50_000.0):\n",
    "        result = run(circuit, new_network(coherence_ms=co, link_length_m=length), 6)\n",
    "        c = Counter(e['event_type'] for e in result.execution_log)\n",
    "        pre, ond = c['epr-pre-gen'], c['epr-ondemand-gen']\n",
    "        print(f\"{co:<11}{length:<12,.0f}{pre:<9}{ond:<11}\"\n",
    "              f\"{c['epr-consumed']:<10}{c['epr-expired']:<9}{pre + ond:<10}{result.final_timestep:<10.2f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cb6fc454",
   "metadata": {},
   "outputs": [],
   "source": [
    "from qndk.circuit.qiskit_circuits import generate_predictable_circuit\n",
    "from qndk.transpile.transpile import TranspiledCircuit\n",
    "from qndk.quantum_network import build_bcube, QPUSpec\n",
    "from qndk.partition.kl import KernighanLinPartitioner\n",
    "from qndk.compile.distributed import new_exec_plan, simulate_circuit\n",
    "\n",
    "qc = generate_predictable_circuit(target_bitstring='11', depth=1, seed=56)\n",
    "tc = TranspiledCircuit(qc)\n",
    "tc.draw_qiskit_dag(figsize=(4, 4), dpi=200)\n",
    "monolithic_counts = simulate_circuit(tc.circuit, shots=500).get_counts()\n",
    "print(monolithic_counts)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d733a727",
   "metadata": {},
   "outputs": [],
   "source": [
    "network = build_bcube(\n",
    "    switch_layers=0, num_qpus=2,\n",
    "    qpu_spec=QPUSpec(comp_qubits=1, connectivity=\"all2all\"))\n",
    "\n",
    "\n",
    "partition = KernighanLinPartitioner(circuit=tc, network=network).partition()\n",
    "\n",
    "exec_plan = new_exec_plan(partition)\n",
    "exec_plan.draw_qiskit_dag(figsize=(4, 4), dpi=200)\n",
    "exec_plan.draw_qiskit_dag(figsize=(10, 16), dpi=200)\n",
    "\n",
    "distributed_counts = exec_plan.simulate(shots=500).get_counts()\n",
    "print(distributed_counts)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "env (3.13.5)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
