{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "43592151-8286-47fc-9df1-968aa0c2c70f",
   "metadata": {},
   "source": [
    "# Exact energy and noisy VQE\n",
    "\n",
    "Can a compact variational circuit reproduce the molecular ground-state energy under IBM device noise? [Overview](Overview.ipynb)\n",
    "\n",
    "## Exact finite-basis reference\n",
    "\n",
    "Full configuration interaction (FCI) diagonalizes the electronic Hamiltonian over all two-electron configurations in STO-3G. The reported total energy adds nuclear repulsion. We also diagonalize the qubit Hamiltonian in the physical electron-number sector and inspect its parity encoding."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "40de02c3-c427-4a58-aa7a-fe32e884816f",
   "metadata": {
    "jupyter": {
     "source_hidden": true
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'hf': -1.1166843870853405, 'fci': -1.1372701746609017} -1.1372701746609024 -1.1372701746609024\n",
      "1000 1 Tapering(hamiltonian=Hamiltonian(n_qubits=1, terms=[(-0.3287170282083124, {}), (0.7879673588770282, {0: 'Z'}), (-0.18128880821149584, {0: 'X'})], name='molecular-tapered'), generators=[{1: 'Z'}, {0: 'Z', 2: 'Z'}, {3: 'Z'}], removed=[1, 2, 3], sector=[1, -1, 1], kept=[0], discarded=0.0)\n",
      "[(-0.09886396933545849, {}), (-0.22278593040418435, {1: 'Z', 2: 'Z'}), (-0.22278593040418435, {2: 'Z', 3: 'Z'}), (0.17434844185575654, {1: 'Z', 3: 'Z'}), (0.17119774903432972, {0: 'Z', 1: 'Z'}), (0.12054482205301796, {0: 'Z', 1: 'Z', 2: 'Z', 3: 'Z'}), (0.17119774903432972, {0: 'Z'}), (0.16586702410589194, {0: 'Z', 2: 'Z', 3: 'Z'}), (0.16586702410589194, {0: 'Z', 2: 'Z'}), (0.12054482205301796, {0: 'Z', 1: 'Z', 2: 'Z'}), (0.04532220205287396, {0: 'Y', 2: 'Y'}), (0.04532220205287396, {0: 'X', 1: 'Z', 2: 'X'}), (0.04532220205287396, {0: 'X', 1: 'Z', 2: 'X', 3: 'Z'}), (0.04532220205287396, {0: 'Y', 2: 'Y', 3: 'Z'}), (0.1686221915892094, {1: 'Z'})]\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "os.environ[\"OMP_NUM_THREADS\"] = \"1\"\n",
    "import numpy as np\n",
    "import quantum_circuit_simulator as qcs\n",
    "from quantum_circuit_simulator import chemistry\n",
    "\n",
    "atoms = [('H',(0.,0.,0.)), ('H',(0.,0.,0.7414))]\n",
    "mol = chemistry.molecule(atoms, basis='sto-3g', mapping='parity')\n",
    "tapered = chemistry.molecule(atoms, basis='sto-3g', mapping='parity', taper=True)\n",
    "print(mol.energies, mol.exact_energy(), tapered.exact_energy())\n",
    "print(mol.hf_bitstring, tapered.hf_bitstring, tapered.tapering)\n",
    "print(mol.hamiltonian.terms)\n",
    "assert abs(mol.energies['fci']-mol.exact_energy()) < 1e-10\n",
    "assert abs(mol.energies['fci']-tapered.exact_energy()) < 1e-10"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "afede509-9d53-4951-ba5e-41b41a098a6c",
   "metadata": {},
   "source": [
    "The full configuration interaction result is **−1.137270174661 Ha**, including nuclear repulsion. The untapered four-qubit calculation and the fully symmetry-reduced one-qubit calculation agree within $10^{-10}$ Ha. The reduced Hamiltonian is a constant plus one $Z$ and one $X$ term. A single real rotation spans its ground state.\n",
    "\n",
    "## Native circuits and calibration\n",
    "\n",
    "IBM [lists Boston as a Heron r3 system](https://quantum.cloud.ibm.com/computers?system=ibm_boston&tab=systems). We use the [IBM-published calibration snapshot](https://github.com/Qiskit/qiskit-ibm-runtime/blob/main/qiskit_ibm_runtime/fake_provider/backends/boston/props_boston.json) dated 17 April 2026. To avoid picking a favorable qubit after seeing energies, use the lower median qubit by average assignment error among calibrated qubits. The device model applies relaxation and depolarization after each physical $\\sqrt{X}$ pulse, virtual $Z$ rotations, and asymmetric assignment errors. Both the state preparation and the $X$ measurement basis change are compiled to native gates."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "4e2d8084-0490-45bf-a849-21fa756aa24f",
   "metadata": {
    "jupyter": {
     "source_hidden": true
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2026-04-17T12:19:24+02:00 physical qubit 79 of 155 eligible\n",
      "T1 / T2 (µs): 262.39499447873516 196.14534009440058 | SX (ns), infidelity: 32 0.00014208857211616395\n",
      "P(1|0), P(0|1): 0.00634765625 0.00390625 | SHA256: 7b01268dcd423c94bbed2b6d5550ee40a96122603974cde3c46d1aedb28c481d\n",
      "Simulator versions: {'quantum-circuit-simulator': '0.5.0rc5', 'qiskit': '2.6.2', 'qiskit-aer': '0.18.4', 'pyscf': '2.15.1'}\n",
      "Z circuit: global phase: 3π/2\n",
      "   ┌───────┐┌────┐┌───────────────┐┌────┐┌────────┐\n",
      "q: ┤ Rz(0) ├┤ √X ├┤ Rz(π + theta) ├┤ √X ├┤ Rz(3π) ├\n",
      "   └───────┘└────┘└───────────────┘└────┘└────────┘\n",
      "X circuit: global phase: 7π/4\n",
      "   ┌───────┐┌────┐┌───────────────┐┌────┐┌────────┐┌─────────┐┌────┐┌─────────┐\n",
      "q: ┤ Rz(0) ├┤ √X ├┤ Rz(π + theta) ├┤ √X ├┤ Rz(3π) ├┤ Rz(π/2) ├┤ √X ├┤ Rz(π/2) ├\n",
      "   └───────┘└────┘└───────────────┘└────┘└────────┘└─────────┘└────┘└─────────┘\n",
      "Plan: {'n_qubits': 156, 'n_parameters': 1, 'stages': 14, 'observable_terms': 2, 'max_terms': 1000000, 'feasible': True, 'widest_cone_wires': 1, 'deepest_cone_stages': 14, 'cone_groups': 1, 'largest_term_bound': 4, 'exact_guaranteed': True, 'recommendations': ['Exact evaluation fits the term cap: `quantum-circuit-simulator run <input>`.', 'Every cone has at most 6 wires: `--backend dense` is exact regardless of depth.', 'For many parameter vectors of one circuit, `--backend graph` compiles once and evaluates each vector far faster.']}\n"
     ]
    }
   ],
   "source": [
    "import hashlib, json, math\n",
    "from pathlib import Path\n",
    "from importlib.metadata import version\n",
    "from qiskit import QuantumCircuit, transpile\n",
    "from qiskit.circuit import Parameter\n",
    "from quantum_circuit_simulator.compiler import compile_circuit\n",
    "from quantum_circuit_simulator.agent import plan\n",
    "from quantum_circuit_simulator import mitigation, measurement\n",
    "\n",
    "cal_path = Path('Data/props_boston.json')\n",
    "cal = json.loads(cal_path.read_text())\n",
    "from quantum_circuit_simulator import devices\n",
    "chip = devices.get('ibm_boston')\n",
    "def props(entries):\n",
    "    return {p['name']: p['value'] for p in entries}\n",
    "sx_cal = {g['qubits'][0]: props(g['parameters']) for g in cal['gates'] if g['gate']=='sx'}\n",
    "qubit_cal = [props(q) for q in cal['qubits']]\n",
    "rank = sorted((sum(chip.readout_map()[q])/2, q) for q in sx_cal if sx_cal[q]['gate_error'] < 0.1)\n",
    "physical = rank[(len(rank)-1)//2][1]\n",
    "qcal, sx = qubit_cal[physical], sx_cal[physical]\n",
    "p01, p10 = chip.readout_map()[physical]\n",
    "assert np.allclose([p01,p10,chip.qubit(physical,'error_1q')],\n",
    "                   [qcal['prob_meas1_prep0'], qcal['prob_meas0_prep1'],sx['gate_error']])\n",
    "assert np.isclose(chip.time_1q, sx['gate_length']*1e-9, atol=1e-13, rtol=0)\n",
    "theta = Parameter('theta')\n",
    "prep = QuantumCircuit(1)\n",
    "prep.ry(theta,0)\n",
    "basis_gates = ['rz','sx','x']\n",
    "native = {'Z': transpile(prep,basis_gates=basis_gates,optimization_level=0)}\n",
    "xbasis = QuantumCircuit(1)\n",
    "xbasis.h(0)\n",
    "native['X'] = native['Z'].compose(transpile(xbasis,basis_gates=basis_gates,optimization_level=0))\n",
    "print(cal['last_update_date'], 'physical qubit', physical, 'of', len(rank), 'eligible')\n",
    "print('T1 / T2 (µs):', qcal['T1'], qcal['T2'], '| SX (ns), infidelity:', sx['gate_length'], sx['gate_error'])\n",
    "print('P(1|0), P(0|1):', p01,p10, '| SHA256:', hashlib.sha256(cal_path.read_bytes()).hexdigest())\n",
    "print('Simulator versions:', {k: version(k) for k in ['quantum-circuit-simulator','qiskit','qiskit-aer','pyscf']})\n",
    "print('Z circuit:', native['Z'].draw(output='text')); print('X circuit:', native['X'].draw(output='text'))\n",
    "test = compile_circuit(native['X'], chip, layout=[physical])\n",
    "print('Plan:', plan(test.circuit, test.observable('Z0')))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d66bb14a-57ae-413b-9a6a-ae59ff2fd96e",
   "metadata": {},
   "source": [
    "Boston qubit 79 has assignment error of 0.635% for a prepared zero and 0.391% for a prepared one. The $Z$ and $X$ circuits use two and three physical pulses, respectively. No couplers are used.\n",
    "\n",
    "## Variational minima and mitigation\n",
    "\n",
    "Each circuit contains the angle once. Its mean is therefore a constant plus sine and cosine even under parameter-independent device noise. Evaluate at three angles and minimize that sinusoid analytically, then check other angles. For readout mitigation, invert the two measured assignment probabilities. For zero-noise extrapolation (ZNE), replace each native pulse $U$ by $U(U^\\dagger U)^k$ at fold factors 1, 3 and 5. This preserves the ideal operation but adds physical pulses. The two fits use factors 1 and 3 (linear), or all three (quadratic). Readout is corrected before either fit because folding does not amplify readout error."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "f02fe96c-89bf-4455-b0f9-c76576b3041a",
   "metadata": {
    "jupyter": {
     "source_hidden": true
    }
   },
   "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>angle</th>\n",
       "      <th>energy</th>\n",
       "      <th>bias_mha</th>\n",
       "      <th>bias_at_raw_angle_mha</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>method</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Ideal</th>\n",
       "      <td>2.915456</td>\n",
       "      <td>-1.137270</td>\n",
       "      <td>-0.000000</td>\n",
       "      <td>0.000002</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Raw</th>\n",
       "      <td>2.915521</td>\n",
       "      <td>-1.129932</td>\n",
       "      <td>7.338623</td>\n",
       "      <td>7.338623</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Readout correction</th>\n",
       "      <td>2.915521</td>\n",
       "      <td>-1.136736</td>\n",
       "      <td>0.534424</td>\n",
       "      <td>0.534424</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Readout + linear ZNE</th>\n",
       "      <td>2.915457</td>\n",
       "      <td>-1.137184</td>\n",
       "      <td>0.086641</td>\n",
       "      <td>0.086643</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Readout + quadratic ZNE</th>\n",
       "      <td>2.915456</td>\n",
       "      <td>-1.137184</td>\n",
       "      <td>0.086292</td>\n",
       "      <td>0.086293</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                            angle    energy  bias_mha  bias_at_raw_angle_mha\n",
       "method                                                                      \n",
       "Ideal                    2.915456 -1.137270 -0.000000               0.000002\n",
       "Raw                      2.915521 -1.129932  7.338623               7.338623\n",
       "Readout correction       2.915521 -1.136736  0.534424               0.534424\n",
       "Readout + linear ZNE     2.915457 -1.137184  0.086641               0.086643\n",
       "Readout + quadratic ZNE  2.915456 -1.137184  0.086292               0.086293"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Max QCS/Aer difference across six observed Pauli means: 1.937540028418283e-07\n",
      "Matched-model inversion (PNA) at raw optimum: -1.1372701729480954\n"
     ]
    }
   ],
   "source": [
    "from qiskit.quantum_info import Operator\n",
    "from qiskit_aer import AerSimulator\n",
    "from qiskit_aer.noise import NoiseModel, depolarizing_error, thermal_relaxation_error\n",
    "import pandas as pd\n",
    "\n",
    "paulis = ['Z','X']\n",
    "constant = next(c for c,p in tapered.hamiltonian.terms if not p)\n",
    "coeff = np.array([next(c for c,p in tapered.hamiltonian.terms if p == {0:k}) for k in paulis])\n",
    "exact = mol.energies['fci']\n",
    "def fold(circuit, factor):\n",
    "    out = QuantumCircuit(1)\n",
    "    out.global_phase = circuit.global_phase\n",
    "    for inst in circuit.data:\n",
    "        out.append(inst.operation,[0])\n",
    "        if inst.operation.name == 'sx':\n",
    "            for _ in range((factor-1)//2):\n",
    "                out.rz(np.pi,0); out.sx(0); out.rz(-np.pi,0) # SX inverse up to global phase\n",
    "                out.sx(0)\n",
    "    return out\n",
    "folded = {(s,k):fold(native[k],s) for s in (1,3,5) for k in paulis}\n",
    "for (s,k), c in folded.items():\n",
    "    assert Operator(c.assign_parameters({theta:0.37})).equiv(Operator(native[k].assign_parameters({theta:0.37})))\n",
    "compiled = {(s,k):compile_circuit(c,chip,layout=[physical]) for (s,k),c in folded.items()}\n",
    "compiled.update({(0,k):compile_circuit(native[k],chip,layout=[physical],noise=False) for k in paulis})\n",
    "plans = {key:c.circuit.prepare(c.observable('Z0')) for key,c in compiled.items()}\n",
    "def means(angle, scales):\n",
    "    return np.array([[plans[s,k].evaluate(compiled[s,k].shifts([angle])).value for k in paulis] for s in scales])\n",
    "alpha, beta = p10-p01, 1-p01-p10\n",
    "rules = {'Ideal':([0],[1.],False), 'Raw':([1],[1.],False), 'Readout correction':([1],[1.],True),\n",
    "         'Readout + linear ZNE':([1,3],[1.5,-0.5],True),\n",
    "         'Readout + quadratic ZNE':([1,3,5],[15/8,-5/4,3/8],True)}\n",
    "def objective(angle,name):\n",
    "    scales,w,correct = rules[name]\n",
    "    z = means(angle,scales)\n",
    "    if correct:\n",
    "        z = (z-alpha)/beta\n",
    "    return constant + np.asarray(w) @ z @ coeff\n",
    "angles_fit = np.array([0,np.pi/2,np.pi])\n",
    "def optimum(e):\n",
    "    offset = (e[0]+e[2])/2\n",
    "    a,b = (e[0]-e[2])/2, e[1]-offset\n",
    "    return np.arctan2(-b,-a), offset-np.hypot(a,b), (offset,a,b)\n",
    "rows = []\n",
    "curves = {}\n",
    "for name in rules:\n",
    "    ang,en,pars = optimum([objective(t,name) for t in angles_fit])\n",
    "    a0,a1,a2 = pars\n",
    "    for v in np.linspace(-np.pi,np.pi,21):\n",
    "        assert abs(objective(v,name)-(a0+a1*np.cos(v)+a2*np.sin(v))) < 1e-11\n",
    "    curves[name] = pars\n",
    "    rows.append(dict(method=name, angle=ang, energy=en, bias_mha=1000*(en-exact)))\n",
    "frame = pd.DataFrame(rows).set_index('method')\n",
    "assert abs(frame.loc['Ideal','energy']-exact) < 1e-10\n",
    "raw_angle = frame.loc['Raw','angle']\n",
    "frame['bias_at_raw_angle_mha'] = [1000*(objective(raw_angle,name)-exact) for name in frame.index]\n",
    "display(frame.round({'angle':8,'energy':10,'bias_mha':6,'bias_at_raw_angle_mha':6}))\n",
    "\n",
    "# Independent Aer density matrix simulation of the native pulses.\n",
    "duration = sx['gate_length']*1e-9\n",
    "t1,t2 = qcal['T1']*1e-6,qcal['T2']*1e-6\n",
    "thermal = thermal_relaxation_error(t1,min(t2,2*t1),duration)\n",
    "thermal_survival = (np.exp(-duration/t1)+2*np.exp(-duration/min(t2,2*t1)))/3\n",
    "strength = max(0.,1-(1-2*sx['gate_error'])/thermal_survival)\n",
    "noise = NoiseModel()\n",
    "noise.add_all_qubit_quantum_error(thermal.compose(depolarizing_error(strength,1)),['sx'])\n",
    "aer = AerSimulator(method='density_matrix',noise_model=noise,max_parallel_threads=1)\n",
    "checks = []\n",
    "for key, c in folded.items():\n",
    "    run_circuit = c.assign_parameters({theta:raw_angle})\n",
    "    run_circuit.save_density_matrix()\n",
    "    rho = np.asarray(aer.run(run_circuit,shots=1).result().data(0)['density_matrix'])\n",
    "    z = (rho[0,0]-rho[1,1]).real\n",
    "    checks.append(abs(alpha+beta*z-means(raw_angle,[key[0]])[0,paulis.index(key[1])]))\n",
    "print('Max QCS/Aer difference across six observed Pauli means:',max(checks))\n",
    "assert max(checks)<3e-7  # allow the different treatment of the relaxation/depolarization cross term\n",
    "print('Matched-model inversion (PNA) at raw optimum:',constant+sum(c*mitigation.pna(compiled[1,k],'Z0',values=[raw_angle])['value'] for c,k in zip(coeff,paulis)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "05d57c4b-68f0-4428-b24c-95394a2b1961",
   "metadata": {},
   "source": [
    "The raw minimum misses by **7.339 mHa**. Correcting readout removes **6.804 mHa**, leaving **0.534 mHa** of bias. Linear pulse folding leaves **0.087 mHa**, and the quadratic fit changes that by less than 0.001 mHa. Folding preserves the unitary, but it need not uniformly scale a nonunital channel such as relaxation. The matched-model inversion diagnoses the effect of perfect channel knowledge; it is not a finite-shot hardware estimate. The two simulators agree to $2 \\times 10^{-7}$ in Pauli expectation across the six noisy circuits.\n",
    "\n",
    "The next cell saves the expectation curves used to sample independent shots in the [shot-budget analysis](Shots%20and%20chemical%20accuracy.ipynb). As a check, it also computes an ideal QCS shot budget for the two basis measurements with no bias."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "af337581-c91f-47d4-9d02-b9950c5358fe",
   "metadata": {
    "jupyter": {
     "source_hidden": true
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Ideal QCS budget: {'method': 'commuting', 'precision': 0.0016, 'groups': 2, 'shots': 48772, 'optimal_shots': 48770.962418255454, 'per_group': [{'terms': 1, 'variance': 0.031213415947683454, 'shots': 24386}, {'terms': 1, 'variance': 0.031213415947683534, 'shots': 24386}], 'qwc_shots': 48772, 'saving_vs_qwc': 1.0}\n"
     ]
    }
   ],
   "source": [
    "ideal_budget = measurement.shot_budget(prep, tapered.hamiltonian, .0016,\n",
    "                                      values=[frame.loc['Ideal','angle']])\n",
    "print('Ideal QCS budget:',ideal_budget)\n",
    "calibration = dict(date=cal['last_update_date'], qubit=physical, p01=p01,p10=p10,\n",
    "                   sha256=hashlib.sha256(cal_path.read_bytes()).hexdigest(), device=chip.name)\n",
    "measure_curves = {}\n",
    "for s in (0,1,3,5):\n",
    "    z0,z90,z180 = [means(t,[s])[0] for t in angles_fit]\n",
    "    offset = (z0+z180)/2\n",
    "    measure_curves[s] = np.array([offset,(z0-z180)/2,z90-offset]).tolist()\n",
    "record = dict(exact=exact, constant=constant, coeff=coeff.tolist(), rules=rules, raw_angle=raw_angle,\n",
    "              calibration=calibration, curves=measure_curves, methods=frame.to_dict(orient='index'))\n",
    "Path('results/energies.json').write_text(json.dumps(record,indent=2))\n",
    "frame.to_csv('results/energies.csv',float_format='%.12f')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "098a3de4-1d5a-40c4-bf34-def369b09c71",
   "metadata": {},
   "source": [
    "The ideal budget is a sampling-only reference. The calibrated calculation below does not inherit it: observed outcome variance, residual bias and extra circuits for extrapolation all change the required shots."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  },
  "vicena": {
   "changed_at": 1796000251352,
   "changed_cells": [
    "f02fe96c-89bf-4455-b0f9-c76576b3041a"
   ]
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
