{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "title",
   "metadata": {},
   "source": [
    "# Synthesize unitaries to Clifford+T\n",
    "**Explore unitary synthesis and the fo-synth-core Python API**"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "introduction",
   "metadata": {},
   "source": [
    "Fault-tolerant quantum algorithms must approximate arbitrary unitary operations using a discrete gate set. Clifford gates alone are not universal; adding the non-Clifford T gate enables universal quantum computation through approximation. T gates typically consume costly magic-state resources, making T-count an important measure of synthesis cost.\n",
    "\n",
    "The `fo-synth-core` package synthesizes single-qubit and two-qubit unitaries into Clifford+T gate words. It accepts numerical targets directly, without a circuit framework. If you instead want to compile entire Qiskit circuits, use the separate `fo-synth-qiskit` package.\n",
    "\n",
    "In this tutorial, you will synthesize a single-qubit target, verify its approximation error, explore the accuracy/resource tradeoff, and synthesize an entangling two-qubit target. An advanced appendix explains the remaining public APIs."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "installation",
   "metadata": {},
   "source": [
    "## Install and import the package\n",
    "\n",
    "Use Python 3.11 or newer. Install the package and NumPy into the Python environment used by your Jupyter kernel:\n",
    "\n",
    "```shell\n",
    "pip install fo-synth-core numpy\n",
    "```\n",
    "\n",
    "Restart the kernel if you installed or upgraded packages while it was running. NumPy is used here to construct targets and independently check the results."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "imports",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-24T19:42:37.512812Z",
     "iopub.status.busy": "2026-11-24T19:42:37.512704Z",
     "iopub.status.idle": "2026-11-24T19:42:37.880273Z",
     "shell.execute_reply": "2026-11-24T19:42:37.879747Z"
    }
   },
   "outputs": [],
   "source": [
    "from time import perf_counter\n",
    "\n",
    "import numpy as np\n",
    "from fo_synth_core import (\n",
    "    GateMetric,\n",
    "    clear_synthesis_cache,\n",
    "    synthesize_su2,\n",
    "    synthesize_su4,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "su2-inputs",
   "metadata": {},
   "source": [
    "## Synthesize a single-qubit unitary\n",
    "\n",
    "An SU(2) matrix is a single-qubit unitary with determinant one. It can be specified by two complex numbers, `alpha` and `beta`, with `abs(alpha)**2 + abs(beta)**2 = 1`:\n",
    "\n",
    "```text\n",
    "U = [[alpha, -conj(beta)],\n",
    "     [beta,   conj(alpha)]]\n",
    "```\n",
    "\n",
    "The `synthesize_su2` function takes these two entries, not the full matrix:\n",
    "\n",
    "| Argument | Meaning |\n",
    "| --- | --- |\n",
    "| `alpha`, `beta` | Finite complex entries satisfying the normalization above |\n",
    "| `tolerance` | Required maximum operator-norm error up to global phase; finite and in `(0, 1]` |\n",
    "\n",
    "The returned word has the lowest T-count among solutions within your tolerance. If no solution is found, the function raises an error rather than returning a less accurate word. You can try a larger `tolerance` if your application permits a coarser approximation.\n",
    "\n",
    "Start with a target that is not just a rotation about a coordinate axis."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "synthesize-su2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-24T19:42:37.881735Z",
     "iopub.status.busy": "2026-11-24T19:42:37.881607Z",
     "iopub.status.idle": "2026-11-24T19:42:37.886822Z",
     "shell.execute_reply": "2026-11-24T19:42:37.886401Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gate word: SSSHSHTHTHTSHTHTHTSHTHTSHTHTHTHTSHTHTHTHTSHTHTSHTHTHTSHTHTSHTHTSHTHSSWSHSHWWWWW\n",
      "T-count: 26\n",
      "CNOT count: 0\n",
      "Reported error: 5.403e-04\n"
     ]
    }
   ],
   "source": [
    "alpha = 0.6 * np.exp(-0.2j)\n",
    "beta = 0.8\n",
    "target_su2 = np.array([[alpha, -np.conj(beta)], [beta, np.conj(alpha)]])\n",
    "tolerance = 1e-3\n",
    "\n",
    "single_result = synthesize_su2(alpha, beta, tolerance=tolerance)\n",
    "\n",
    "print(\"Gate word:\", single_result.gates)\n",
    "print(\"T-count:\", single_result.t_count)\n",
    "print(\"CNOT count:\", single_result.cnot_count)\n",
    "print(f\"Reported error: {single_result.operator_error:.3e}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "result-model",
   "metadata": {},
   "source": [
    "The result is a `CliffordTWord`; its fields are `gates` (the gate word), `t_count`, `operator_error`, and `cnot_count`. The CNOT count is always zero for single-qubit synthesis. You can inspect fields directly, or use `model_dump()` to obtain a dictionary.\n",
    "\n",
    "For a single-qubit word, the allowed gates are H, S, T, X, I (identity), and W (the global phase `exp(i * pi / 4)` times identity). A word is a **matrix product written left to right**, so its **rightmost gate acts first**. For example, `HT` represents the matrix `H @ T`: apply T, then H.\n",
    "\n",
    "The following helper reconstructs that product."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "replay-su2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-24T19:42:37.887977Z",
     "iopub.status.busy": "2026-11-24T19:42:37.887888Z",
     "iopub.status.idle": "2026-11-24T19:42:37.891613Z",
     "shell.execute_reply": "2026-11-24T19:42:37.891164Z"
    }
   },
   "outputs": [],
   "source": [
    "identity = np.eye(2, dtype=complex)\n",
    "phase = np.exp(1j * np.pi / 4)\n",
    "gates = {\n",
    "    \"H\": np.array([[1, 1], [1, -1]], dtype=complex) / np.sqrt(2),\n",
    "    \"S\": np.diag([1, 1j]),\n",
    "    \"T\": np.diag([1, phase]),\n",
    "    \"X\": np.array([[0, 1], [1, 0]], dtype=complex),\n",
    "    \"W\": phase * identity,\n",
    "    \"I\": identity,\n",
    "}\n",
    "\n",
    "\n",
    "def su2_word_matrix(word):\n",
    "    \"\"\"Reconstruct a single-qubit word in matrix-product order.\"\"\"\n",
    "    matrix = identity.copy()\n",
    "    for letter in word:\n",
    "        matrix = matrix @ gates[letter]\n",
    "    return matrix\n",
    "\n",
    "\n",
    "single_matrix = su2_word_matrix(single_result.gates)\n",
    "assert single_result.t_count == single_result.gates.count(\"T\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "error-explanation",
   "metadata": {},
   "source": [
    "## Verify approximation error\n",
    "\n",
    "The operator norm of a matrix is its largest singular value. For the difference between target unitary U and approximation V, it measures the largest output-state-vector difference over normalized inputs. Here, error is minimized over a global phase: `min_phi ||U - exp(i * phi) V||_op`. Unitaries differing only by a global phase therefore have zero error.\n",
    "\n",
    "The helper below finds the shortest arc containing the eigenphases of `U.conj().T @ V`. Centering this arc gives the optimal phase adjustment, and its width determines the distance. It works for both matrix sizes used here. Constructing full matrices scales exponentially with qubit count, so this is not intended for verifying large circuits."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "verify-su2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-24T19:42:37.892695Z",
     "iopub.status.busy": "2026-11-24T19:42:37.892616Z",
     "iopub.status.idle": "2026-11-24T19:42:37.900578Z",
     "shell.execute_reply": "2026-11-24T19:42:37.900137Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Measured error: 5.403e-04\n",
      "Requested tolerance: 1.000e-03\n"
     ]
    }
   ],
   "source": [
    "def operator_error(target, candidate):\n",
    "    \"\"\"Return the operator-norm distance between unitaries up to global phase.\"\"\"\n",
    "    relative = target.conj().T @ candidate\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",
    "measured_error = operator_error(target_su2, single_matrix)\n",
    "print(f\"Measured error: {measured_error:.3e}\")\n",
    "print(f\"Requested tolerance: {tolerance:.3e}\")\n",
    "assert measured_error <= tolerance + 1e-10\n",
    "assert np.isclose(measured_error, single_result.operator_error, atol=1e-10)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "accuracy-tradeoff",
   "metadata": {},
   "source": [
    "## Trade approximation accuracy for synthesis cost\n",
    "\n",
    "Smaller tolerances require closer approximations and typically increase the T-count and search effort. Synthesize the same target at several tolerances and compare the independently measured errors and resource counts.\n",
    "\n",
    "Repeated synthesis calls can reuse previously computed results. Before each timed call below, `clear_synthesis_cache()` removes cached results and resets the cache counters without changing its capacity. This prevents a result from an earlier call from making synthesis appear faster."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "compare-tolerances",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-24T19:42:37.901740Z",
     "iopub.status.busy": "2026-11-24T19:42:37.901659Z",
     "iopub.status.idle": "2026-11-24T19:42:38.059589Z",
     "shell.execute_reply": "2026-11-24T19:42:38.059117Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " Tolerance       Error  T-count  Median ms\n",
      "     1e-02   8.700e-03       15      0.164\n",
      "     3e-03   2.222e-03       23      0.221\n",
      "     1e-03   5.403e-04       26      0.332\n"
     ]
    }
   ],
   "source": [
    "tolerances = [1e-2, 3e-3, 1e-3]\n",
    "repeats = 200\n",
    "for requested in tolerances:\n",
    "    clear_synthesis_cache()\n",
    "    synthesize_su2(alpha, beta, tolerance=requested)\n",
    "\n",
    "timings = {requested: [] for requested in tolerances}\n",
    "tolerance_results = {}\n",
    "for _ in range(repeats):\n",
    "    for requested in tolerances:\n",
    "        clear_synthesis_cache()\n",
    "        start = perf_counter()\n",
    "        result = synthesize_su2(alpha, beta, tolerance=requested)\n",
    "        elapsed = perf_counter() - start\n",
    "        timings[requested].append(elapsed)\n",
    "        tolerance_results[requested] = result\n",
    "\n",
    "print(f\"{'Tolerance':>10} {'Error':>11} {'T-count':>8} {'Median ms':>10}\")\n",
    "for requested in tolerances:\n",
    "    result = tolerance_results[requested]\n",
    "    median_ms = 1e3 * np.median(timings[requested])\n",
    "    measured = operator_error(target_su2, su2_word_matrix(result.gates))\n",
    "    print(f\"{requested:10.0e} {measured:11.3e} {result.t_count:8d} {median_ms:10.3f}\")\n",
    "    assert measured <= requested + 1e-10\n",
    "    assert np.isclose(measured, result.operator_error, atol=1e-10)\n",
    "    assert result.t_count == result.gates.count(\"T\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "accuracy-takeaway",
   "metadata": {},
   "source": [
    "For this target, tightening the tolerance produces a more accurate approximation at the cost of more T gates and a longer median synthesis time. These are two distinct costs: T-count reflects resources needed to implement the result, while synthesis time is the classical computation needed to find it. Choose a tolerance that meets your algorithm's error budget without paying for unnecessary accuracy.\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",
   "id": "su4-inputs",
   "metadata": {},
   "source": [
    "## Synthesize a two-qubit unitary\n",
    "\n",
    "The `synthesize_su4` function accepts a finite, unitary 4x4 matrix as a row-major nested sequence and a required `tolerance` in `(0, 1]`. Note that you do not need to remove an input matrix's global phase or enforce determinant one. Qubit 0 is the most significant tensor factor: the basis order is `|00>, |01>, |10>, |11>`.\n",
    "\n",
    "Below, combine XX and ZZ interactions. Each interaction has the form `cos(angle / 2) I - i sin(angle / 2) P`, where P is the tensor product of two Pauli matrices. This gives a genuinely entangling target, rather than a product of independent single-qubit gates.\n",
    "\n",
    "The optional `metric` argument defaults to `GateMetric.OPERATOR_NORM` (also accepted as `\"operator_norm\"`). This is the same global-phase-minimized distance used above. SU(4) synthesis returns a word within the requested distance."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "synthesize-su4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-24T19:42:38.060832Z",
     "iopub.status.busy": "2026-11-24T19:42:38.060744Z",
     "iopub.status.idle": "2026-11-24T19:42:38.064411Z",
     "shell.execute_reply": "2026-11-24T19:42:38.064035Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gate word: I0 I1 CX0,1 W0 W0 W0 W0 W0 S0 S0 X0 T0 H0 T0 H0 T0 H0 S0 T0 H0 T0 H0 S0 T0 H0 S0 T0 H0 T0 H0 S0 T0 H0 S0 T0 H0 S0 T0 H0 S0 T0 H0 S0 T0 H0 T0 H0 T0 H0 S0 T0 H0 S0 T0 H0 T0 H0 S0 T0 H0 T0 H0 T0 H0 T0 H0 S0 T0 W1 W1 S1 S1 S1 X1 H1 S1 T1 H1 T1 H1 T1 H1 T1 H1 S1 T1 H1 T1 H1 S1 T1 H1 T1 H1 T1 H1 T1 H1 S1 T1 H1 S1 T1 H1 S1 T1 H1 T1 H1 T1 H1 S1 T1 H1 S1 T1 H1 S1 T1 H1 S1 T1 H1 T1 H1 T1 H1 T1 CX0,1 I0 I1\n",
      "T-count: 45\n",
      "CNOT count: 2\n",
      "Reported error: 5.290e-03\n"
     ]
    }
   ],
   "source": [
    "pauli_x = gates[\"X\"]\n",
    "pauli_z = np.diag([1, -1])\n",
    "\n",
    "\n",
    "def interaction(pauli, angle):\n",
    "    return np.cos(angle / 2) * np.eye(4) - 1j * np.sin(angle / 2) * np.kron(\n",
    "        pauli, pauli\n",
    "    )\n",
    "\n",
    "\n",
    "target_su4 = interaction(pauli_x, 0.31) @ interaction(pauli_z, 0.17)\n",
    "two_qubit_tolerance = 1e-2\n",
    "two_qubit_result = synthesize_su4(target_su4.tolist(), tolerance=two_qubit_tolerance)\n",
    "\n",
    "print(\"Gate word:\", two_qubit_result.gates)\n",
    "print(\"T-count:\", two_qubit_result.t_count)\n",
    "print(\"CNOT count:\", two_qubit_result.cnot_count)\n",
    "print(f\"Reported error: {two_qubit_result.operator_error:.3e}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "su4-order",
   "metadata": {},
   "source": [
    "**Two-qubit gate words use a different ordering convention.** Their space-separated tokens appear in **execution order**, from left to right. Thus `H0 T1 CX0,1` means apply H on qubit 0, then T on qubit 1, then a CNOT controlled by qubit 0 targeting qubit 1. Its matrix is `CX0,1 @ T1 @ H0`.\n",
    "\n",
    "Single-qubit letters have the qubit index appended, including `I0` and `W1`. `CX1,0` reverses the CNOT control and target. The helper below uses the stated tensor-factor order and left-multiplies each gate to replay this execution order."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "verify-su4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-24T19:42:38.065656Z",
     "iopub.status.busy": "2026-11-24T19:42:38.065576Z",
     "iopub.status.idle": "2026-11-24T19:42:38.070329Z",
     "shell.execute_reply": "2026-11-24T19:42:38.069866Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Measured operator-norm error: 5.290e-03\n"
     ]
    }
   ],
   "source": [
    "cnot_gates = {\n",
    "    \"CX0,1\": np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]),\n",
    "    \"CX1,0\": np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]]),\n",
    "}\n",
    "\n",
    "\n",
    "def su4_word_matrix(word):\n",
    "    \"\"\"Reconstruct a two-qubit word in execution order; qubit 0 is most significant.\"\"\"\n",
    "    matrix = np.eye(4, dtype=complex)\n",
    "    for token in word.split():\n",
    "        if token in cnot_gates:\n",
    "            gate = cnot_gates[token]\n",
    "        else:\n",
    "            local = gates[token[0]]\n",
    "            if token[1] == \"0\":\n",
    "                gate = np.kron(local, identity)\n",
    "            else:\n",
    "                gate = np.kron(identity, local)\n",
    "        matrix = gate @ matrix\n",
    "    return matrix\n",
    "\n",
    "\n",
    "two_qubit_matrix = su4_word_matrix(two_qubit_result.gates)\n",
    "measured = operator_error(target_su4, two_qubit_matrix)\n",
    "tokens = two_qubit_result.gates.split()\n",
    "print(f\"Measured operator-norm error: {measured:.3e}\")\n",
    "assert measured <= two_qubit_tolerance + 1e-10\n",
    "assert np.isclose(measured, two_qubit_result.operator_error, atol=1e-10)\n",
    "assert two_qubit_result.t_count == sum(token in (\"T0\", \"T1\") for token in tokens)\n",
    "assert two_qubit_result.cnot_count == sum(token in cnot_gates for token in tokens)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fidelity-metric",
   "metadata": {},
   "source": [
    "### Choose the distance for two-qubit synthesis\n",
    "\n",
    "The other option is `GateMetric.FIDELITY` (or `\"fidelity\"`). Its distance is `sqrt(1 - abs(trace(U.conj().T @ V)) / 4)`. It is invariant under global phase, but it is **not average gate infidelity**, and a numerical tolerance in this metric is not the same requirement as that tolerance in operator norm.\n",
    "\n",
    "**For SU(4), `operator_error` contains the distance in the selected metric, despite its name.** Keep track of the metric alongside the result; the result model does not store it. Below, request the fidelity metric explicitly and verify that distance rather than comparing it with the operator-norm tolerance."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "verify-fidelity",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-24T19:42:38.071373Z",
     "iopub.status.busy": "2026-11-24T19:42:38.071296Z",
     "iopub.status.idle": "2026-11-24T19:42:38.075316Z",
     "shell.execute_reply": "2026-11-24T19:42:38.074969Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Measured fidelity distance: 2.645e-03\n",
      "Reported distance: 2.645e-03\n",
      "Operator-norm distance: 5.290e-03\n"
     ]
    }
   ],
   "source": [
    "fidelity_result = synthesize_su4(\n",
    "    target_su4.tolist(), tolerance=two_qubit_tolerance, metric=GateMetric.FIDELITY\n",
    ")\n",
    "fidelity_matrix = su4_word_matrix(fidelity_result.gates)\n",
    "trace_overlap = abs(np.trace(target_su4.conj().T @ fidelity_matrix)) / 4\n",
    "fidelity_distance = np.sqrt(np.clip(1 - trace_overlap, 0, 1))\n",
    "\n",
    "print(f\"Measured fidelity distance: {fidelity_distance:.3e}\")\n",
    "print(f\"Reported distance: {fidelity_result.operator_error:.3e}\")\n",
    "print(f\"Operator-norm distance: {operator_error(target_su4, fidelity_matrix):.3e}\")\n",
    "assert fidelity_distance <= two_qubit_tolerance + 1e-10\n",
    "assert np.isclose(fidelity_distance, fidelity_result.operator_error, atol=1e-10)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "conclusion",
   "metadata": {},
   "source": [
    "## Choose settings for your own unitaries\n",
    "\n",
    "You can now supply a normalized single-qubit target or a two-qubit unitary, interpret its gate word, and verify its approximation. Choose a tolerance that meets your accuracy needs, and compare the resulting T-count and CNOT count rather than assuming one resource determines the entire cost.\n",
    "\n",
    "Each tolerance applies to the **one target passed to that call**, not to an entire algorithm. When composing approximations measured in operator norm, the sum of their individual error bounds is a conservative bound on the full product's error. For `N` synthesized operations and an overall operator-norm budget of `epsilon`, assigning each at most `epsilon / N` is sufficient. Do not apply that rule directly to the fidelity-distance option.\n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "appendix-cache",
   "metadata": {},
   "source": [
    "## Advanced appendix: additional public APIs\n",
    "\n",
    "### Inspect the synthesis cache\n",
    "\n",
    "`synthesis_cache_info()` returns an immutable `CacheInfo` model describing the process-global SU(2) synthesis cache. Repeating an identical target with the same tolerance can reuse a previous result. A nearby target or a different tolerance is not an exact repeat. Two-qubit synthesis may use this cache for its constituent single-qubit searches; it is not a cache of complete two-qubit results.\n",
    "\n",
    "| Field | Meaning |\n",
    "| --- | --- |\n",
    "| `hits` | Successful result-cache lookups |\n",
    "| `misses` | Result-cache lookups that did not find the exact requested target |\n",
    "| `entries` | Number of retained results |\n",
    "| `capacity` | Maximum retained results before least-recently-used eviction |\n",
    "| `anchor_hits`, `anchor_misses`, `anchor_entries` | Reserved counters, currently zero |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "appendix-gridsynth",
   "metadata": {},
   "source": [
    "### Synthesize a Z rotation with gridsynth\n",
    "\n",
    "`gridsynth_rz(theta, epsilon)` uses the gridsynth algorithm to approximate `Rz(theta) = diag(exp(-i * theta / 2), exp(i * theta / 2))`. Supply a finite angle in radians and a finite precision `epsilon` in `(0, 1]`. The implementation uses a fixed random seed.\n",
    "\n",
    "It returns the same single-qubit word representation as the main synthesis interface, with its T-count and global-phase-minimized operator-norm error. This function can be used to compare gridsynth against the Fire Opal synthesizer."
   ]
  }
 ],
 "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",
   "version": "3.14.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
