# Circuit Optimization **Circuit optimization** reduces gate count, depth, and two-qubit gate count without changing the circuit's computation. Optimized circuits run faster, accumulate less error on noisy hardware, and consume fewer quantum resources. Qiskit's transpiler includes optimization passes (e.g., `commutative_cancellation`, `optimize_1q_gates`); you can also manually optimize by inspecting circuits and applying rewrites. ## Built-In Optimization Passes Transpilation already optimizes: set `optimization_level` to control aggressiveness. ```python from qiskit import transpile, QuantumCircuit from qiskit_aer import AerSimulator qc = QuantumCircuit(2, 2) qc.h(0) qc.x(0) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) backend = AerSimulator() optimized = transpile(qc, backend, optimization_level=3) print(f"Original depth: {qc.depth()}") print(f"Optimized depth: {optimized.depth()}") ``` Level 3 applies aggressive rewrites: - Commute gates to find cancellations (X followed by X cancel) - Merge consecutive single-qubit gates on the same qubit - Eliminate redundant gates - Reorder gates to reduce circuit depth ## Manual Optimization For custom optimizations, inspect and rewrite: ```python # Remove identity gates def remove_identities(qc): new_qc = QuantumCircuit(*qc.qregs, *qc.cregs) for instr, qargs, cargs in qc.data: if instr.name not in ['id', 'reset']: new_qc.append(instr, qargs, cargs) return new_qc optimized_qc = remove_identities(qc) ``` On noisy hardware, circuit depth dominates error—optimizing for depth (not just gate count) is often better.