{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Synthesize Qiskit circuits to Clifford+T\n",
    "**Explore optimized synthesis strategies with fo-synth-qiskit**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Fault-tolerant algorithms often require decomposing arbitrary unitary operations, such as rotations, using a restricted discrete gate set. The `fo-synth-qiskit` package performs optimized synthesis to approximate those operations with Clifford+T circuits containing native H, S, T, X, and CNOT (`cx`) instructions. Clifford gates alone are not universal; adding the non-Clifford T gate enables universal quantum computation through approximation. T gates typically require costly magic-state resources in fault-tolerant implementations, so T-count is a useful resource indicator alongside CNOT count and circuit depth.\n",
    "\n",
    "In this tutorial, you will synthesize a small circuit, supply equivalent Qiskit and OpenQASM inputs, and measure how approximation tolerance and compilation strategy change the result."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Install and import the package\n",
    "\n",
    "Use Python 3.11 or newer and install the package in the Python environment used by your Jupyter kernel:\n",
    "\n",
    "```shell\n",
    "pip install fo-synth-qiskit\n",
    "```\n",
    "\n",
    "If not already present in your environment, the package installs Qiskit and the OpenQASM 3 importer as dependencies.\n",
    "Restart the kernel if you installed or upgraded packages while it was running."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import warnings\n",
    "from pathlib import Path\n",
    "from tempfile import TemporaryDirectory\n",
    "from time import perf_counter\n",
    "\n",
    "import numpy as np\n",
    "from fo_synth_qiskit import (\n",
    "    SynthesisStrategy,\n",
    "    UnsupportedOperationWarning,\n",
    "    synthesize_clifford_t,\n",
    ")\n",
    "from qiskit import QuantumCircuit, qasm2, qasm3\n",
    "from qiskit.circuit import Parameter\n",
    "from qiskit.quantum_info import Operator"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Synthesize your first circuit\n",
    "\n",
    "The `synthesize_clifford_t` function is the entry point for synthesis. It has three arguments:\n",
    "\n",
    "| Argument | Accepted values | Meaning |\n",
    "| --- | --- | --- |\n",
    "| `circuit` | A `QuantumCircuit`, OpenQASM 2 or 3 source string, or path-like object | The circuit to compile |\n",
    "| `tolerance` | A number in `(0, 1]`; default `1e-6` | Maximal allowed distance between the synthesized unitary and the ideal operation, in terms of the operator norm |\n",
    "| `strategy` | `SynthesisStrategy.SU2` or `SynthesisStrategy.SU4`, or strings `\"su2\"` or `\"su4\"`; default `SynthesisStrategy.SU2` | Selects single-qubit synthesis or combined two-qubit-block synthesis |\n",
    "\n",
    "Only `circuit` is required.\n",
    "You can supply `circuit` and `tolerance` positionally or by keyword, but `strategy` is keyword-only.\n",
    "\n",
    "Start with a numeric single-qubit U gate.\n",
    "Its three angles are in radians.\n",
    "Calling the function without optional arguments uses tolerance `1e-6` and the SU(2) strategy."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Input operations: {'u': 1}\n",
      "Output operations: {'h': 54, 't': 50, 's': 28}\n",
      "Input unchanged: True\n",
      "New circuit returned: True\n"
     ]
    }
   ],
   "source": [
    "circuit = QuantumCircuit(1)\n",
    "circuit.u(0.5, 0.7, -0.3, 0)\n",
    "original_circuit = circuit.copy()\n",
    "\n",
    "default_result = synthesize_clifford_t(circuit)\n",
    "\n",
    "print(\"Input operations:\", dict(circuit.count_ops()))\n",
    "print(\"Output operations:\", dict(default_result.count_ops()))\n",
    "print(\"Input unchanged:\", circuit == original_circuit)\n",
    "print(\"New circuit returned:\", default_result is not circuit)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The returned object is a new `QuantumCircuit` on the original wires, where the U gate has been replaced by individual native gates.\n",
    "The synthesizer also tracks global phase in the output circuit's `global_phase` attribute."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Measure approximation error\n",
    "\n",
    "The tolerance argument to `synthesize_clifford_t` provides an upper bound to **operator-norm error minimized over global phase**.\n",
    "The operator norm of a matrix is its largest singular value.\n",
    "For the difference between a target unitary $U$ and its approximation $V$, it measures the largest output-state-vector difference over normalized input states.\n",
    "Here, we minimize that difference over a global phase: $\\epsilon = \\min_\\phi \\lVert U - e^{i\\phi}V \\rVert_{\\mathrm{op}}$.\n",
    "Global phase does not change measurement probabilities, so two unitaries that differ only by a global phase have zero error under this metric.\n",
    "\n",
    "For the single-qubit unitaries considered here, the **average gate infidelity** $1-F_{\\mathrm{avg}}$ is related to this error by\n",
    "\n",
    "$$\n",
    "1-F_{\\mathrm{avg}} = \\frac{2}{3}\\epsilon^2\\left(1-\\frac{\\epsilon^2}{4}\\right) \\approx \\frac{2}{3}\\epsilon^2,\n",
    "$$\n",
    "\n",
    "where the approximation holds for small errors and $F_{\\mathrm{avg}}$ averages output-state fidelity over uniformly distributed pure input states.\n",
    "\n",
    "The helper below finds the shortest arc containing the eigenphases of the relative unitary.\n",
    "Centering that arc gives the optimal global-phase adjustment; its width determines the operator-norm distance.\n",
    "Use this diagnostic only for small, fully bound unitary circuits: constructing a full circuit matrix scales exponentially with qubit count and is not appropriate for measurements, resets, or dynamic control flow."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Default-call error: 9.731e-07\n"
     ]
    }
   ],
   "source": [
    "def operator_error(target, result):\n",
    "    \"\"\"Return the operator-norm distance between unitaries up to global phase.\"\"\"\n",
    "    target_matrix = Operator(target).data\n",
    "    result_matrix = Operator(result).data\n",
    "    relative = target_matrix.conj().T @ result_matrix\n",
    "    full_turn = 2 * np.pi\n",
    "    phases = np.sort(np.angle(np.linalg.eigvals(relative)) % full_turn)\n",
    "    gaps = np.diff(np.append(phases, phases[0] + full_turn))\n",
    "    arc_width = full_turn - np.max(gaps)\n",
    "    return float(2 * np.sin(arc_width / 4))\n",
    "\n",
    "\n",
    "print(f\"Default-call error: {operator_error(circuit, default_result):.3e}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Supply OpenQASM inputs\n",
    "\n",
    "The `synthesize_clifford_t` function also accepts OpenQASM 2 and OpenQASM 3 source strings, as shown below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "OpenQASM 2 source error: 8.497e-04\n",
      "OpenQASM 3 source error: 8.497e-04\n"
     ]
    }
   ],
   "source": [
    "qasm_sources = {\"OpenQASM 2\": qasm2.dumps(circuit), \"OpenQASM 3\": qasm3.dumps(circuit)}\n",
    "source_results = {}\n",
    "for label, source in qasm_sources.items():\n",
    "    result = synthesize_clifford_t(circuit=source, tolerance=1e-3)\n",
    "    source_results[label] = result\n",
    "    print(f\"{label} source error: {operator_error(circuit, result):.3e}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Instead of a source string, you can supply a `pathlib.Path` or another `os.PathLike` object pointing to a `.qasm` source file.\n",
    "Note that a plain string such as `\"circuit.qasm\"` is interpreted as QASM source, **not** as a filename, and fails header validation.\n",
    "Files must contain UTF-8 OpenQASM 2 or 3 source with the appropriate header.\n",
    "This example creates and automatically removes temporary files; substitute the path to your own file in a real workflow."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "OpenQASM 2 file error: 8.497e-04\n",
      "OpenQASM 3 file error: 8.497e-04\n"
     ]
    }
   ],
   "source": [
    "file_results = {}\n",
    "with TemporaryDirectory() as directory:\n",
    "    for label, source in qasm_sources.items():\n",
    "        qasm_path = Path(directory) / \"circuit.qasm\"\n",
    "        qasm_path.write_text(source, encoding=\"utf-8\")\n",
    "        result = synthesize_clifford_t(qasm_path, tolerance=1e-3)\n",
    "        file_results[label] = result\n",
    "        print(f\"{label} file error: {operator_error(circuit, result):.3e}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Trade approximation accuracy for synthesis cost\n",
    "\n",
    "Smaller `tolerance` values require a closer approximation, typically increasing the number of T gates and synthesis effort.\n",
    "Larger values permit a coarser approximation that may use fewer resources.\n",
    "\n",
    "To illustrate, below you can synthesize the same single-qubit target with four tolerances."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " Tolerance       Error     T   Gates   Depth   Seconds\n",
      "     1e-02   8.798e-03    15      46      46    0.0019\n",
      "     1e-03   8.497e-04    27      76      76    0.0010\n",
      "     1e-04   9.814e-05    37     102     102    0.0018\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     1e-06   9.731e-07    50     132     132    0.0017\n"
     ]
    }
   ],
   "source": [
    "tolerance_results = {}\n",
    "print(\n",
    "    f\"{'Tolerance':>10} {'Error':>11} {'T':>5} {'Gates':>7} {'Depth':>7} {'Seconds':>9}\"\n",
    ")\n",
    "for tolerance in [1e-2, 1e-3, 1e-4, 1e-6]:\n",
    "    start = perf_counter()\n",
    "    result = synthesize_clifford_t(circuit, tolerance)\n",
    "    elapsed = perf_counter() - start\n",
    "    tolerance_results[tolerance] = result\n",
    "    counts = result.count_ops()\n",
    "    error = operator_error(circuit, result)\n",
    "    print(\n",
    "        f\"{tolerance:10.0e} {error:11.3e} {counts.get('t', 0):5d} \"\n",
    "        f\"{result.size():7d} {result.depth():7d} {elapsed:9.4f}\"\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Notice how tightening the error target changes the T-count and depth, not just the error column.\n",
    "\n",
    "**Tolerance is not a whole-circuit error budget.**\n",
    "For a full circuit, a conservative bound is `N * tolerance`, where `N` is the number of single-qubit runs and two-qubit blocks actually sent to synthesis after decomposition and collection.\n",
    "It is not the number of input gates or emitted Clifford+T instructions.\n",
    "If you know your circuit contains `N` unitaries to synthesize and require a circuit bound of `epsilon`, choose a per-unit tolerance no greater than `epsilon / N`.\n",
    "For example, ten synthesized unitaries at tolerance `1e-4` give a conservative full-circuit bound of `1e-3`, not `1e-4`.\n",
    "\n",
    "**Very small tolerances emit warnings.**\n",
    "The synthesizer warns when called with `tolerance <= 1e-8`.\n",
    "Such tolerances may significantly extend synthesis time and/or fail to find a solution. Also, only devices with a QEC error per cycle `~1e-20` could take advantage of such accurate synthesis, whereas current long-term projections for achievable error per cycle are larger."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Compare synthesis strategies\n",
    "\n",
    "The default `strategy=\"su2\"` decomposes supported operations into CNOT and single-qubit U gates, merges adjacent single-qubit runs, and synthesizes those runs.\n",
    "The CNOT structure produced by decomposition is retained.\n",
    "\n",
    "With `strategy=\"su4\"`, the synthesizer collects numeric two-qubit blocks and synthesizes them jointly, using SU(2) for remaining single-qubit runs.\n",
    "Joint synthesis can change CNOT structure inside those blocks, creating a different resource tradeoff.\n",
    "A two-qubit block counts as one synthesized unitary for tolerance accounting.\n",
    "\n",
    "Both strategies accept multi-qubit circuits. The distinction is the size of the blocks synthesized, not the number of qubits in the input circuit.\n",
    "\n",
    "To illustrate, the example below has three non-native interactions on the same pair of qubits so that there is a genuine two-qubit region to collect.\n",
    "Note that the tolerance applies to each synthesized block, and the strategies partition the circuit differently. We therefore choose their tolerances independently to obtain approximately equal measured whole-circuit errors, then compare the required resources."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Strategy   Tolerance       Error     T    CX   Gates   Depth   Seconds\n",
      "     su2   3.200e-04   5.297e-04   101     6     288     282    0.0073\n",
      "     su4   1.000e-03   4.915e-04   101     4     277     184    0.0114\n"
     ]
    }
   ],
   "source": [
    "interactions = QuantumCircuit(2)\n",
    "interactions.rxx(0.31, 0, 1)\n",
    "interactions.ryy(-0.29, 0, 1)\n",
    "interactions.rzz(0.17, 0, 1)\n",
    "\n",
    "strategy_tolerances = {SynthesisStrategy.SU2: 3.2e-4, SynthesisStrategy.SU4: 1e-3}\n",
    "strategy_results = {}\n",
    "print(\n",
    "    f\"{'Strategy':>8} {'Tolerance':>11} {'Error':>11} {'T':>5} {'CX':>5} \"\n",
    "    f\"{'Gates':>7} {'Depth':>7} {'Seconds':>9}\"\n",
    ")\n",
    "for strategy, tolerance in strategy_tolerances.items():\n",
    "    start = perf_counter()\n",
    "    result = synthesize_clifford_t(interactions, tolerance=tolerance, strategy=strategy)\n",
    "    elapsed = perf_counter() - start\n",
    "    strategy_results[str(strategy)] = result\n",
    "    counts = result.count_ops()\n",
    "    error = operator_error(interactions, result)\n",
    "    print(\n",
    "        f\"{strategy:>8} {tolerance:11.3e} \"\n",
    "        f\"{error:11.3e} {counts.get('t', 0):5d} \"\n",
    "        f\"{counts.get('cx', 0):5d} {result.size():7d} {result.depth():7d} {elapsed:9.4f}\"\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Notice that in this case, the SU(4) strategy produces a lower whole-circuit error, CNOT count, overall gate count, and depth, at the cost of higher runtime.\n",
    "The preferable result depends on your circuit, architecture, and resource priorities; neither strategy is guaranteed to win for every circuit."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Preserve existing native gates\n",
    "\n",
    "The SU(4) strategy preserves original native H, S, T, X, and CX instructions, including in mixed circuits and control-flow bodies.\n",
    "Consequently, a circuit that is already entirely native retains its T-count and CNOT count exactly, as shown below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Before: {'h': 1, 't': 1, 'cx': 1, 's': 1, 'x': 1}\n",
      "After:  {'h': 1, 't': 1, 'cx': 1, 's': 1, 'x': 1}\n",
      "Circuit preserved: True\n"
     ]
    }
   ],
   "source": [
    "native = QuantumCircuit(2)\n",
    "native.h(0)\n",
    "native.t(1)\n",
    "native.cx(0, 1)\n",
    "native.s(0)\n",
    "native.x(1)\n",
    "\n",
    "preserved = synthesize_clifford_t(native, strategy=\"su4\")\n",
    "print(\"Before:\", dict(native.count_ops()))\n",
    "print(\"After: \", dict(preserved.count_ops()))\n",
    "print(\"Circuit preserved:\", preserved == native)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Preserved native instructions also form collection boundaries on the wires they touch.\n",
    "For example, an original native CX separating two non-native regions is not absorbed to make one larger SU(4) block."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Recognize and resolve incomplete synthesis\n",
    "\n",
    "A successful return does not always mean every operation is Clifford+T.\n",
    "For example, a rotation with an unbound parameter cannot be numerically approximated.\n",
    "Its symbolic U representation remains in the output, and the synthesizer emits `UnsupportedOperationWarning`.\n",
    "Capture and display that expected warning so you can inspect the incomplete result."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "UnsupportedOperationWarning: Output contains unsupported operations: u\n",
      "Remaining parameters: ['theta']\n",
      "Output operations: {'u': 1}\n"
     ]
    }
   ],
   "source": [
    "theta = Parameter(\"theta\")\n",
    "parameterized = QuantumCircuit(1)\n",
    "parameterized.ry(theta, 0)\n",
    "\n",
    "with warnings.catch_warnings(record=True) as caught:\n",
    "    warnings.simplefilter(\"always\", UnsupportedOperationWarning)\n",
    "    incomplete = synthesize_clifford_t(parameterized, tolerance=1e-3)\n",
    "\n",
    "for warning in caught:\n",
    "    print(f\"{warning.category.__name__}: {warning.message}\")\n",
    "print(\"Remaining parameters:\", [str(value) for value in incomplete.parameters])\n",
    "print(\"Output operations:\", dict(incomplete.count_ops()))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "After binding the parameter to an angle in radians, you can proceed with synthesis."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Remaining parameters: []\n",
      "Output operations: {'t': 30, 'h': 29, 's': 18, 'x': 1}\n",
      "Bound-circuit error: 6.511e-04\n"
     ]
    }
   ],
   "source": [
    "bound = incomplete.assign_parameters({theta: 0.31})\n",
    "complete = synthesize_clifford_t(bound, tolerance=1e-3)\n",
    "\n",
    "print(\"Remaining parameters:\", list(complete.parameters))\n",
    "print(\"Output operations:\", dict(complete.count_ops()))\n",
    "print(f\"Bound-circuit error: {operator_error(bound, complete):.3e}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Opaque operations without a usable decomposition or matrix can also remain unsynthesized.\n",
    "Under either strategy, the function emits one `UnsupportedOperationWarning` per call listing the unique unsupported operation names, including those in nested control-flow bodies.\n",
    "\n",
    "Measurements, resets, barriers, and delays are passed through unchanged.\n",
    "Control-flow conditions and structure are retained, and bodies are synthesized recursively using the selected strategy.\n",
    "If your circuits contain any such non-unitary operations, they are not suitable for analysis with the `operator_error` helper function defined above."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Choose settings for your own circuit\n",
    "\n",
    "You have now learned how to create QEC-ready circuits with the Fire Opal Clifford+T synthesizer! In particular, you have learned:\n",
    "- How to supply a bound `QuantumCircuit`, QASM source, or a QASM `Path` according to where your circuit originates.\n",
    "- How to choose a per-unitary `tolerance` that accounts for your circuit's error budget.\n",
    "- How to modify the synthesis `strategy`, and the resource tradeoff that it creates.\n",
    "- How to check unsupported-operation warnings to verify that the returned circuit is fully synthesized.\n",
    "\n",
    "You should now be ready to try the synthesizer out on your own circuits. Or, to explore performance beyond the examples here, use our `fo-synth-benchmarks` package to test the Fire Opal synthesizer against a broad variety of synthesis targets.\n",
    "Follow the [Benchmark Clifford+T synthesis](https://docs.q-ctrl.com/fire-opal/ftqc/compile/benchmark-cliffordt-synthesis) tutorial to compare synthesis runtime and T-counts across targets."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
