{ "cells": [ { "cell_type": "markdown", "id": "a3efd224", "metadata": {}, "source": [ "# 20 - OpenQASM Interoperability\n", "\n", "Export and import circuits in OpenQASM 2.0 format.\n", "\n", "**Concepts:** OpenQASM, to_openqasm, from_openqasm, cross-platform" ] }, { "cell_type": "code", "execution_count": null, "id": "0452efc4", "metadata": {}, "outputs": [], "source": [ "import quantsdk as qs" ] }, { "cell_type": "markdown", "id": "dc2ac7f6", "metadata": {}, "source": [ "## Export to OpenQASM" ] }, { "cell_type": "code", "execution_count": null, "id": "5103de4e", "metadata": {}, "outputs": [], "source": [ "# Build a Bell state circuit\n", "circuit = qs.Circuit(2, name=\"bell\")\n", "circuit.h(0).cx(0, 1).measure_all()\n", "\n", "# Export to OpenQASM\n", "qasm = circuit.to_openqasm()\n", "print(\"OpenQASM 2.0 output:\")\n", "print(qasm)" ] }, { "cell_type": "code", "execution_count": null, "id": "555d30a3", "metadata": {}, "outputs": [], "source": [ "# More complex circuit\n", "circuit = qs.Circuit(3, name=\"complex\")\n", "circuit.h(0).cx(0, 1).ry(2, 1.5708).cz(1, 2)\n", "circuit.rx(0, 0.7854).t(1).s(2)\n", "circuit.measure_all()\n", "\n", "qasm = circuit.to_openqasm()\n", "print(qasm)" ] }, { "cell_type": "markdown", "id": "14ec93f2", "metadata": {}, "source": [ "## Import from OpenQASM" ] }, { "cell_type": "code", "execution_count": null, "id": "5f44e5fb", "metadata": {}, "outputs": [], "source": [ "# Parse OpenQASM string into a QuantSDK circuit\n", "qasm_str = \"\"\"OPENQASM 2.0;\n", "include \"qelib1.inc\";\n", "qreg q[2];\n", "creg c[2];\n", "h q[0];\n", "cx q[0],q[1];\n", "measure q[0] -> c[0];\n", "measure q[1] -> c[1];\n", "\"\"\"\n", "\n", "imported = qs.Circuit.from_openqasm(qasm_str)\n", "print(f\"Imported circuit: {imported.num_qubits} qubits, {imported.gate_count} gates\")\n", "print(f\"Ops: {imported.count_ops()}\")\n", "\n", "# Run the imported circuit\n", "result = qs.run(imported, shots=1000, seed=42)\n", "print(f\"Result: {result.counts}\")" ] }, { "cell_type": "markdown", "id": "7ad55ad2", "metadata": {}, "source": [ "## Round-Trip" ] }, { "cell_type": "code", "execution_count": null, "id": "eb2acd39", "metadata": {}, "outputs": [], "source": [ "# Build -> QASM -> Parse -> Run\n", "original = qs.Circuit(2)\n", "original.h(0).cx(0, 1).measure_all()\n", "\n", "# Round trip\n", "qasm = original.to_openqasm()\n", "roundtrip = qs.Circuit.from_openqasm(qasm)\n", "\n", "# Compare\n", "r1 = qs.run(original, shots=2000, seed=42)\n", "r2 = qs.run(roundtrip, shots=2000, seed=42)\n", "\n", "print(\"Round-trip validation:\")\n", "print(f\" Original: {r1.counts}\")\n", "print(f\" Roundtrip: {r2.counts}\")\n", "print(f\" Match: {r1.counts == r2.counts}\")" ] } ], "metadata": { "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 5 }