{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "1db6c3f9",
   "metadata": {},
   "source": [
    "# Importing quantum programs into QRE\n",
    "\n",
    "The Quantum Resource Estimator (QRE) can accept applications written in several quantum programming languages and frameworks. This notebook demonstrates how to import programs from **Q#**, **Cirq**, **QIR** (Quantum Intermediate Representation), and **OpenQASM**, and then run resource estimation on each of them.\n",
    "\n",
    "After running estimation on all four input formats, we go a step further and build a **custom application model**. This shows how to define your own `Application` subclass with configurable *trace parameters* (algorithmic hyperparameters that QRE varies automatically during estimation) and how to enrich results with custom columns derived from trace properties."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "138685c1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/javascript": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n// This file provides CodeMirror syntax highlighting for Q# magic cells\n// in classic Jupyter Notebooks. It does nothing in other (Jupyter Notebook 7,\n// VS Code, Azure Notebooks, etc.) environments.\n\n// Detect the prerequisites and do nothing if they don't exist.\nif (window.require && window.CodeMirror && window.Jupyter) {\n  // The simple mode plugin for CodeMirror is not loaded by default, so require it.\n  window.require([\"codemirror/addon/mode/simple\"], function defineMode() {\n    let rules = [\n      {\n        token: \"comment\",\n        regex: /(\\/\\/).*/,\n        beginWord: false,\n      },\n      {\n        token: \"string\",\n        regex: String.raw`^\\\"(?:[^\\\"\\\\]|\\\\[\\s\\S])*(?:\\\"|$)`,\n        beginWord: false,\n      },\n      {\n        token: \"keyword\",\n        regex: String.raw`(namespace|open|as|operation|function|body|adjoint|newtype|controlled|internal)\\b`,\n        beginWord: true,\n      },\n      {\n        token: \"keyword\",\n        regex: String.raw`(if|elif|else|repeat|until|fixup|for|in|return|fail|within|apply)\\b`,\n        beginWord: true,\n      },\n      {\n        token: \"keyword\",\n        regex: String.raw`(Adjoint|Controlled|Adj|Ctl|is|self|auto|distribute|invert|intrinsic)\\b`,\n        beginWord: true,\n      },\n      {\n        token: \"keyword\",\n        regex: String.raw`(let|set|use|borrow|mutable)\\b`,\n        beginWord: true,\n      },\n      {\n        token: \"operatorKeyword\",\n        regex: String.raw`(not|and|or)\\b|(w/)`,\n        beginWord: true,\n      },\n      {\n        token: \"operatorKeyword\",\n        regex: String.raw`(=)|(!)|(<)|(>)|(\\+)|(-)|(\\*)|(/)|(\\^)|(%)|(\\|)|(&&&)|(~~~)|(\\.\\.\\.)|(\\.\\.)|(\\?)`,\n        beginWord: false,\n      },\n      {\n        token: \"meta\",\n        regex: String.raw`(Int|BigInt|Double|Bool|Qubit|Pauli|Result|Range|String|Unit)\\b`,\n        beginWord: true,\n      },\n      {\n        token: \"atom\",\n        regex: String.raw`(true|false|Pauli(I|X|Y|Z)|One|Zero)\\b`,\n        beginWord: true,\n      },\n    ];\n    let simpleRules = [];\n    for (let rule of rules) {\n      simpleRules.push({\n        token: rule.token,\n        regex: new RegExp(rule.regex, \"g\"),\n        sol: rule.beginWord,\n      });\n      if (rule.beginWord) {\n        // Need an additional rule due to the fact that CodeMirror simple mode doesn't work with ^ token\n        simpleRules.push({\n          token: rule.token,\n          regex: new RegExp(String.raw`\\W` + rule.regex, \"g\"),\n          sol: false,\n        });\n      }\n    }\n\n    // Register the mode defined above with CodeMirror\n    window.CodeMirror.defineSimpleMode(\"qsharp\", { start: simpleRules });\n    window.CodeMirror.defineMIME(\"text/x-qsharp\", \"qsharp\");\n\n    // Tell Jupyter to associate %%qsharp magic cells with the qsharp mode\n    window.Jupyter.CodeCell.options_default.highlight_modes[\"qsharp\"] = {\n      reg: [/^%%qsharp/],\n    };\n\n    // Force re-highlighting of all cells the first time this code runs\n    for (const cell of window.Jupyter.notebook.get_cells()) {\n      cell.auto_highlight();\n    }\n  });\n}\n",
      "text/plain": []
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from dataclasses import dataclass, field\n",
    "from pathlib import Path\n",
    "from typing import Any\n",
    "\n",
    "import cirq\n",
    "import qdk\n",
    "\n",
    "from qiskit.circuit.library import RGQFTMultiplier\n",
    "from qiskit.qasm3.exporter import Exporter\n",
    "\n",
    "from qdk.qre import estimate, plot_estimates, Application\n",
    "from qdk.qre.interop import trace_from_entry_expr\n",
    "from qdk.qre.models import GateBased, RoundBasedFactory, SurfaceCode, TwoDimensionalYokedSurfaceCode\n",
    "from qdk.qre.application import QSharpApplication, QIRApplication, CirqApplication, OpenQASMApplication\n",
    "from qdk.qre.property_keys import custom_properties"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "54a49066",
   "metadata": {},
   "source": [
    "## From Q#\n",
    "\n",
    "Here we use the `%%qsharp` cell magic to define an inline Q# operation that performs ripple-carry addition on two registers of qubits. We then wrap the compiled entry point in a `QSharpApplication`, passing the register size as a runtime argument."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "082a75fc",
   "metadata": {
    "vscode": {
     "languageId": "qsharp"
    }
   },
   "outputs": [],
   "source": [
    "%%qsharp\n",
    "\n",
    "import Std.Arithmetic.*;\n",
    "\n",
    "// Ripple-carry addition on two n-qubit registers\n",
    "operation Program(n : Int) : Unit {\n",
    "    use a = Qubit[n];\n",
    "    use b = Qubit[n];\n",
    "\n",
    "    RippleCarryCGIncByLE(a, b);\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "f9a84bf7",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Wrap the compiled Q# entry point with a register size of 10 qubits\n",
    "qsharp_app = QSharpApplication(qdk.code.Program, args=(10,))  # type: ignore"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0d5625e1",
   "metadata": {},
   "source": [
    "## From Cirq\n",
    "\n",
    "`CirqApplication` accepts any `cirq.Circuit` directly. Here we build a 10-qubit Quantum Fourier Transform (QFT) circuit using Cirq's built-in `qft` helper and wrap it for resource estimation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "b81536f3",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Build a 10-qubit QFT circuit and wrap it for estimation\n",
    "circuit = cirq.Circuit(cirq.qft(*cirq.LineQubit.range(10)))\n",
    "cirq_app = CirqApplication(circuit)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f2f4db19",
   "metadata": {},
   "source": [
    "## From QIR\n",
    "\n",
    "Quantum Intermediate Representation (QIR) is an LLVM-based IR for quantum programs. `QIRApplication` accepts QIR as an LLVM IR string (or bitcode). Here we load a pre-compiled QIR file for a Hidden Shift algorithm."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "24dad0bb",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load a pre-compiled QIR file for the Hidden Shift algorithm\n",
    "qir_file = (\n",
    "    Path.cwd().parent.parent\n",
    "    / \"source\" / \"qdk_package\" / \"tests-integration\" / \"resources\"\n",
    "    / \"adaptive_ri\" / \"output\" / \"HiddenShiftNISQ.ll\"\n",
    ")\n",
    "qir_app = QIRApplication(qir_file.read_text(encoding=\"utf-8\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "95eccf1d",
   "metadata": {},
   "source": [
    "## From OpenQASM (via Qiskit)\n",
    "\n",
    "`OpenQASMApplication` accepts an OpenQASM 3 source string directly. Here we use Qiskit to generate an OpenQASM 3 program for a 4-qubit RGQFT multiplier and wrap it for resource estimation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "4f628862",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Export a Qiskit circuit to OpenQASM 3\n",
    "source = Exporter().dumps(RGQFTMultiplier(num_state_qubits=4))\n",
    "qasm_app = OpenQASMApplication(source)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d684e434",
   "metadata": {},
   "source": [
    "## Running resource estimation\n",
    "\n",
    "With all four applications defined, we run resource estimation on each one to illustrate that any of the supported input formats can be used interchangeably. We use a `GateBased` architecture with 100 ns gate time and 500 ns measurement time, and query over `SurfaceCode` distances crossed with `RoundBasedFactory` protocols. The `max_error` parameter caps the total error probability at 1%.\n",
    "\n",
    "Each call to `estimate` returns an `EstimationTable` of Pareto-optimal results: configurations where no other result achieves both fewer physical qubits *and* a shorter runtime within the error budget. Note that the four applications implement entirely different algorithms, so the results are not directly comparable; the purpose here is to show that QRE handles all input formats uniformly."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "0171b84b",
   "metadata": {},
   "outputs": [],
   "source": [
    "estimates = []\n",
    "\n",
    "# Define the target architecture: gate-based with specified timing (ns)\n",
    "arch = GateBased(gate_time=100, measurement_time=500)\n",
    "\n",
    "# Explore surface code distances × round-based magic state factories\n",
    "isa_query = SurfaceCode.q() * RoundBasedFactory.q()\n",
    "\n",
    "for name, app in [(\"Q# adder\", qsharp_app), (\"cirq QFT\", cirq_app), (\"QIR HiddenShift\", qir_app), (\"OpenQASM multiplier\", qasm_app)]:\n",
    "    estimates.append(estimate(app, arch, isa_query, max_error=0.01, name=name))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "00938f1d",
   "metadata": {},
   "source": [
    "We can plot the Pareto frontiers for each application. Since the four programs implement different algorithms, the plots are not meant for cross-algorithm comparison; they simply confirm that each input format produces valid estimation results."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "08fc2a22",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 24816 characters]",
      "text/plain": [
       "<Figure size 600x400 with 1 Axes>"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "plot_estimates(estimates, figsize=(6, 4))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8dfc16d9",
   "metadata": {},
   "source": [
    "## Custom application model\n",
    "\n",
    "The built-in application wrappers (`QSharpApplication`, `CirqApplication`, etc.) are convenient for importing existing circuits, but sometimes you need finer control. By subclassing `Application`, you can define a *custom application model* that separates two kinds of parameters:\n",
    "\n",
    "- **Instance parameters** define *which* problem you are solving. They are fixed for a given estimation run. For example, the bit-size of an adder or the key length of an encryption scheme.\n",
    "- **Trace parameters** are algorithmic hyperparameters that control *how* the problem is solved. QRE varies these automatically and explores all combinations during estimation. For example, the choice of adder circuit, the compute-to-memory ratio, or the eviction strategy.\n",
    "\n",
    "Below we build a configurable adder application that lets QRE explore different adder implementations, compute fractions, and memory-management strategies for a given bit-size, and then compare the Pareto-optimal results."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "932122cc",
   "metadata": {
    "vscode": {
     "languageId": "qsharp"
    }
   },
   "outputs": [],
   "source": [
    "%%qsharp\n",
    "import Std.Arithmetic.*;\n",
    "import Std.Convert.*;\n",
    "import Std.Math.*;\n",
    "import Std.ResourceEstimation.*;\n",
    "\n",
    "// An adder operation that we will estimate together with instance and trace parameters\n",
    "operation Adder(n : Int, adder: (Qubit[], Qubit[]) => Unit, computeFraction: Double, strategy: Int) : Unit {\n",
    "    use a = Qubit[n];\n",
    "    use b = Qubit[n];\n",
    "\n",
    "    if computeFraction > 0.0 {\n",
    "        // Enables an automatic memory/compute architecture with a fixed number of compute qubits\n",
    "        // (computed as a fraction of the total number of qubits).  The strategy controls how\n",
    "        // compute qubits are deallocated if free compute qubits are needed (either least recently\n",
    "        // used or least frequently used).\n",
    "        EnableMemoryComputeArchitecture(Ceiling(computeFraction * IntAsDouble(n)), strategy);\n",
    "    }\n",
    "\n",
    "    // Run the adder\n",
    "    adder(a, b);\n",
    "\n",
    "    // Reset all qubits (if code is used in simulation)\n",
    "    ResetAll(a + b);\n",
    "}\n",
    "\n",
    "// Re-export adders and strategies to use in Python, together with strings to use in displaying the results\n",
    "function CGAdder(): ((Qubit[], Qubit[]) => Unit, String) { (RippleCarryCGIncByLE, \"CG\") }\n",
    "function TTKAdder(): ((Qubit[], Qubit[]) => Unit, String) { (RippleCarryTTKIncByLE, \"TTK\") }\n",
    "function LRU(): (Int, String) { (LeastRecentlyUsed(), \"LRU\") }\n",
    "function LFU(): (Int, String) { (LeastFrequentlyUsed(), \"LFU\") }"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "df9bb728",
   "metadata": {},
   "source": [
    "Trace parameters are defined as a `dataclass` with `kw_only=True`. Only keyword-only fields are treated as enumerable parameters by QRE; regular fields are considered fixed. Each keyword field must specify a `domain` in its `metadata` dict; this tells QRE which values to explore during estimation.\n",
    "\n",
    "In the `AdderParameters` class below:\n",
    "\n",
    "- **`adder`** selects the adder implementation: the Craig Gidney (CG) ripple-carry adder or the Takahashi–Tani–Kunihiro (TTK) ripple-carry adder.\n",
    "- **`compute_fraction`** controls the ratio of qubits allocated to active computation versus memory, passed to `EnableMemoryComputeArchitecture` in the Q# operation.\n",
    "- **`strategy`** chooses the eviction policy when compute capacity is exceeded: Least Recently Used (LRU) or Least Frequently Used (LFU).\n",
    "\n",
    "Each field carries a default value (used when calling the application directly) and a domain (used when QRE enumerates all parameter combinations)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "cd26a6b7",
   "metadata": {},
   "outputs": [],
   "source": [
    "@dataclass(kw_only=True)\n",
    "class AdderParameters:\n",
    "    adder: tuple[Any, str] = field(default = qdk.code.CGAdder(), metadata={\"domain\": [qdk.code.CGAdder(), qdk.code.TTKAdder()]})\n",
    "    compute_fraction: float = field(default=1.0, metadata={\"domain\": [0.5, 1.0, 1.5, 2.0]})\n",
    "    strategy: tuple[int, str] = field(default=qdk.code.LRU(), metadata={\"domain\": [qdk.code.LRU(), qdk.code.LFU()]})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1d8f3f9d",
   "metadata": {},
   "source": [
    "The `Adder` class subclasses `Application[AdderParameters]`, binding the trace-parameter type. Its single instance parameter, `bitsize`, is a regular (non-keyword) dataclass field that defines which problem instance to estimate.\n",
    "\n",
    "Key details:\n",
    "\n",
    "- **`get_trace(parameters)`** is the core method that QRE calls once for every combination of trace parameters. It invokes the Q# `Adder` operation with the current `bitsize` and the selected `adder`, `compute_fraction`, and `strategy` values, producing a resource-estimation trace.\n",
    "- **`set_property`** attaches custom metadata (the adder name, compute fraction, and strategy name) to each trace. These properties are carried through estimation and can later be surfaced as custom columns in the results table."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "fe5f3ef6",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "# Property keys are integers; we can use the custom_properties function to\n",
    "# define custom properties that do not conflict with existing properties.\n",
    "ADDER, COMPUTE_FRACTION, STRATEGY = custom_properties(3)\n",
    "\n",
    "@dataclass\n",
    "class Adder(Application[AdderParameters]):\n",
    "    bitsize: int\n",
    "\n",
    "    def __post_init__(self):\n",
    "        # Disable parallel trace generation since passing the Q# adder operations is not thread-safe.\n",
    "        self.disable_parallel_traces()\n",
    "\n",
    "    def get_trace(self, parameters: AdderParameters):\n",
    "        # obtain the adder function and its name\n",
    "        adder_fn, adder_name = parameters.adder\n",
    "        # obtain the memory/compute strategy and its name\n",
    "        strategy, strategy_name = parameters.strategy\n",
    "        # generate a trace from the Q# entry point with the specified parameters\n",
    "        trace = trace_from_entry_expr(qdk.code.Adder, self.bitsize, adder_fn, parameters.compute_fraction, strategy)\n",
    "\n",
    "        # Set trace properties for later analysis and display\n",
    "        trace.set_property(ADDER, adder_name)\n",
    "        trace.set_property(COMPUTE_FRACTION, parameters.compute_fraction)\n",
    "        trace.set_property(STRATEGY, strategy_name)\n",
    "\n",
    "        return trace"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a466e2f2",
   "metadata": {},
   "source": [
    "Because the Q# operation enables a memory/compute architecture, the estimation must account for *memory qubits* in addition to compute and factory qubits. We extend the ISA query with `TwoDimensionalYokedSurfaceCode`, which models yoked surface codes for memory qubits on top of the lattice-surgery layer provided by `SurfaceCode`.\n",
    "\n",
    "We also enrich the results table with additional columns:\n",
    "\n",
    "- **`add_factory_summary_column()`** adds a human-readable summary of the magic-state factories used (e.g., `2×T, 1×CCZ`).\n",
    "- **`add_qubit_partition_column()`** breaks the total physical qubit count into compute, factory, and memory partitions.\n",
    "- Three **custom property columns** (`Adder`, `Compute fraction`, `Strategy`) surface the trace properties we attached earlier, so each row shows which algorithmic configuration produced that result."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "de782d73",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>name</th>\n",
       "      <th>qubits</th>\n",
       "      <th>runtime</th>\n",
       "      <th>error</th>\n",
       "      <th>factories</th>\n",
       "      <th>physical_compute_qubits</th>\n",
       "      <th>physical_factory_qubits</th>\n",
       "      <th>physical_memory_qubits</th>\n",
       "      <th>adder</th>\n",
       "      <th>compute_fraction</th>\n",
       "      <th>strategy</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Configurable adder</td>\n",
       "      <td>14048</td>\n",
       "      <td>0 days 00:00:00.007940</td>\n",
       "      <td>0.009500</td>\n",
       "      <td>5×T</td>\n",
       "      <td>7448</td>\n",
       "      <td>4900</td>\n",
       "      <td>1700</td>\n",
       "      <td>TTK</td>\n",
       "      <td>1.0</td>\n",
       "      <td>LRU</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Configurable adder</td>\n",
       "      <td>15028</td>\n",
       "      <td>0 days 00:00:00.006545</td>\n",
       "      <td>0.007920</td>\n",
       "      <td>6×T</td>\n",
       "      <td>7448</td>\n",
       "      <td>5880</td>\n",
       "      <td>1700</td>\n",
       "      <td>TTK</td>\n",
       "      <td>1.0</td>\n",
       "      <td>LFU</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Configurable adder</td>\n",
       "      <td>15233</td>\n",
       "      <td>0 days 00:00:00.006205</td>\n",
       "      <td>0.008384</td>\n",
       "      <td>2×T</td>\n",
       "      <td>3969</td>\n",
       "      <td>680</td>\n",
       "      <td>10584</td>\n",
       "      <td>CG</td>\n",
       "      <td>0.5</td>\n",
       "      <td>LRU</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>Configurable adder</td>\n",
       "      <td>17729</td>\n",
       "      <td>0 days 00:00:00.006180</td>\n",
       "      <td>0.008911</td>\n",
       "      <td>6×T</td>\n",
       "      <td>10829</td>\n",
       "      <td>5880</td>\n",
       "      <td>1020</td>\n",
       "      <td>TTK</td>\n",
       "      <td>1.5</td>\n",
       "      <td>LRU</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>Configurable adder</td>\n",
       "      <td>18709</td>\n",
       "      <td>0 days 00:00:00.005010</td>\n",
       "      <td>0.007249</td>\n",
       "      <td>7×T</td>\n",
       "      <td>10829</td>\n",
       "      <td>6860</td>\n",
       "      <td>1020</td>\n",
       "      <td>TTK</td>\n",
       "      <td>1.5</td>\n",
       "      <td>LFU</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>Configurable adder</td>\n",
       "      <td>19781</td>\n",
       "      <td>0 days 00:00:00.004375</td>\n",
       "      <td>0.008869</td>\n",
       "      <td>4×T</td>\n",
       "      <td>14161</td>\n",
       "      <td>3920</td>\n",
       "      <td>1700</td>\n",
       "      <td>CG</td>\n",
       "      <td>2.0</td>\n",
       "      <td>LFU</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>Configurable adder</td>\n",
       "      <td>20761</td>\n",
       "      <td>0 days 00:00:00.003805</td>\n",
       "      <td>0.007727</td>\n",
       "      <td>5×T</td>\n",
       "      <td>14161</td>\n",
       "      <td>4900</td>\n",
       "      <td>1700</td>\n",
       "      <td>CG</td>\n",
       "      <td>2.0</td>\n",
       "      <td>LRU</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>Configurable adder</td>\n",
       "      <td>31801</td>\n",
       "      <td>0 days 00:00:00.001890</td>\n",
       "      <td>0.003385</td>\n",
       "      <td>18×T</td>\n",
       "      <td>14161</td>\n",
       "      <td>17640</td>\n",
       "      <td>0</td>\n",
       "      <td>TTK</td>\n",
       "      <td>2.0</td>\n",
       "      <td>LRU</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                 name  qubits                runtime     error factories  \\\n",
       "0  Configurable adder   14048 0 days 00:00:00.007940  0.009500       5×T   \n",
       "1  Configurable adder   15028 0 days 00:00:00.006545  0.007920       6×T   \n",
       "2  Configurable adder   15233 0 days 00:00:00.006205  0.008384       2×T   \n",
       "3  Configurable adder   17729 0 days 00:00:00.006180  0.008911       6×T   \n",
       "4  Configurable adder   18709 0 days 00:00:00.005010  0.007249       7×T   \n",
       "5  Configurable adder   19781 0 days 00:00:00.004375  0.008869       4×T   \n",
       "6  Configurable adder   20761 0 days 00:00:00.003805  0.007727       5×T   \n",
       "7  Configurable adder   31801 0 days 00:00:00.001890  0.003385      18×T   \n",
       "\n",
       "   physical_compute_qubits  physical_factory_qubits  physical_memory_qubits  \\\n",
       "0                     7448                     4900                    1700   \n",
       "1                     7448                     5880                    1700   \n",
       "2                     3969                      680                   10584   \n",
       "3                    10829                     5880                    1020   \n",
       "4                    10829                     6860                    1020   \n",
       "5                    14161                     3920                    1700   \n",
       "6                    14161                     4900                    1700   \n",
       "7                    14161                    17640                       0   \n",
       "\n",
       "  adder  compute_fraction strategy  \n",
       "0   TTK               1.0      LRU  \n",
       "1   TTK               1.0      LFU  \n",
       "2    CG               0.5      LRU  \n",
       "3   TTK               1.5      LRU  \n",
       "4   TTK               1.5      LFU  \n",
       "5    CG               2.0      LFU  \n",
       "6    CG               2.0      LRU  \n",
       "7   TTK               2.0      LRU  "
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "isa_query = SurfaceCode.q() * RoundBasedFactory.q() * TwoDimensionalYokedSurfaceCode.q(source=SurfaceCode.q())\n",
    "\n",
    "results = estimate(Adder(64), arch, isa_query, max_error=0.01, name=\"Configurable adder\")\n",
    "results.add_factory_summary_column()\n",
    "results.add_qubit_partition_column()\n",
    "results.add_property_column(ADDER, \"adder\")\n",
    "results.add_property_column(COMPUTE_FRACTION, \"compute_fraction\")\n",
    "results.add_property_column(STRATEGY, \"strategy\")\n",
    "results.as_frame()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4e0ae55d",
   "metadata": {},
   "source": [
    "The table above shows the Pareto-optimal configurations for a 64-bit adder. Each row represents a point on the Pareto frontier where no other configuration achieves both fewer physical qubits *and* a shorter runtime within the 1% error budget. The custom columns make it easy to see which adder implementation, compute fraction, and eviction strategy each result uses.\n",
    "\n",
    "We can also visualize the Pareto frontier as a scatter plot of physical qubits versus runtime:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "7a33193a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 17452 characters]",
      "text/plain": [
       "<Figure size 400x400 with 1 Axes>"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "results.plot(figsize=(4, 4))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "57b74ab4",
   "metadata": {},
   "source": [
    "## Conclusion\n",
    "\n",
    "This notebook demonstrated two ways to use the Quantum Resource Estimator:\n",
    "\n",
    "1. **Importing existing programs.** QRE accepts quantum programs from Q#, Cirq, QIR, and OpenQASM through dedicated application wrappers, making it straightforward to estimate resources for circuits written in any of these frameworks.\n",
    "2. **Building a custom application model.** By subclassing `Application` and defining trace parameters as a dataclass, you can let QRE automatically explore algorithmic hyperparameters (adder choice, compute fraction, eviction strategy) and compare Pareto-optimal results across all combinations.\n",
    "\n",
    "For more details on inspecting and visualizing estimation results, see the [Analysing Resource Estimation Results](2_analysing_results.ipynb) notebook."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "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.11.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
