{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'\\nLinear witnesses provide simple measurement schedules to flag entanglement without full tomography.\\n\\nExercises:\\n- Decompose W into Pauli strings and count measurement groups.\\n'"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"\"\"\n",
    "Linear witnesses provide simple measurement schedules to flag entanglement without full tomography.\n",
    "\n",
    "Exercises:\n",
    "- Decompose W into Pauli strings and count measurement groups.\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<W> = -0.5\n"
     ]
    }
   ],
   "source": [
    "from qiskit import QuantumCircuit\n",
    "from qiskit.quantum_info import SparsePauliOp\n",
    "from qiskit_aer import AerSimulator\n",
    "from qiskit_aer.primitives import EstimatorV2 as AerEstimator  \n",
    "from qiskit.transpiler import generate_preset_pass_manager   \n",
    "\n",
    "backend = AerSimulator(method=\"statevector\")\n",
    "pm = generate_preset_pass_manager(backend=backend, optimization_level=1)\n",
    "est = AerEstimator.from_backend(backend) \n",
    "\n",
    "proj = 0.25*SparsePauliOp.from_list([(\"II\",1),(\"XX\",1),(\"YY\",-1),(\"ZZ\",1)]) # = |Φ+><Φ+|\n",
    "prep = QuantumCircuit(2); prep.h(0); prep.cx(0,1) # prepares |Φ+> change to whatever\n",
    "\n",
    "isa_qc = pm.run(prep)\n",
    "isa_obs = proj.apply_layout(isa_qc.layout)\n",
    "pub = [(isa_qc,isa_obs)]\n",
    "exp_proj = AerEstimator().run(pub).result()[0].data.evs\n",
    "\n",
    "W = 0.5 - exp_proj # W = 0.5*I - |Φ+><Φ+| is a 2 qubits entanglement witness\n",
    "print(\"<W> =\", W)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "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.12.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
