from IPython.display import HTML
HTML("""
<style>
/* Restore standard Google Colab background */
body, .notebook-container {
background-color: #f5f5f5 !important;
}
.colab-df-container {
background: white !important;
}
/* Optional: match Colab's input cell background */
.cell {
background-color: #ffffff !important;
}
</style>
""");
QuSciTech-Labs — Navigation¶
Public Labs · Full Edition Access · Private Repo · QuSciTech.com · The Quantum AI Systems (QAIS) Book ·
Quantum AI Systems: Theory, Architecture, and Applications
© 2025 Dr. Joe Wilson. All rights reserved.
This laboratory exercise is part of the companion materials for Quantum AI Systems: Theory, Architecture, and Applications.
Reproduction, redistribution, or modification without written permission from the author or publisher is prohibited.
E.1 Lab 3 — Angle Encoding & Statevectors — Bloch Sphere and Amplitudes¶
Lab Access and Execution Guide¶
This guide explains how to run and explore the hands-on quantum computing labs that accompany the book
Quantum AI Systems: Theory, Architecture, and Applications (Professional Volume).
The labs are an integral part of the MyQuantumBook project, designed to reinforce key concepts from the chapters through interactive exploration. They are built for execution on Google Colab and IBM Quantum backends using Qiskit, and follow the IEEE-compliant figure, caption, and documentation standards described in the text.
Each lab is cross-referenced to its corresponding chapter and appendix figure (Appendix E), ensuring reproducibility and scholarly traceability.
Getting Started
- Launch the notebook in Google Colab using the provided badge.
- Run the setup cells to install Qiskit:
!pip install qiskit
Using IBM Quantum Systems
- Sign up at https://quantum.ibm.com and create an API token.
- Run the IBMQ setup cell.
- Replace 'MY_API_TOKEN' with your real token (only needed once).
- Select backends using
provider.get_backend('ibmq_qasm_simulator')or others.
Lab Structure Each code section aligns with a chapter from the book.
- Modify and re-run code blocks.
- View circuits with
.draw(). - Apply to custom inputs to deepen your understanding.
Additional Help
- Refer to the Qiskit Documentation: https://qiskit.org/documentation/
- For support, contact your course instructor or visit the IBM Quantum Community forums.
Note for Lab Participants
Each plot generated in this notebook is automatically saved as a .png file under: Beginner_Labs/figures/
The filenames follow the Appendix E figure numbering (e.g., `E1_3_Angle_Encoding_Statevectors.png).
This allows you to both view results inline in Colab and find the corresponding image files for reports, submissions, or cross-references in the book.
Where Figures Are Saved
In Google Colab, the images are created inside the session’s working directory at:
/content/Beginner_Labs/figures/When running locally, they appear next to your notebook files, under the subfolder:
Beginner_Labs/figures/These images are not automatically added to your GitHub repo. They will only appear there if you manually copy, commit, and push them.
Customizing Save Location
If you want the figures saved elsewhere, you can change the subdir default in the save_e_figure() helper or pass a different path each time you call it.
Book Reference: Chapter 3 — Encoding Classical Data in Quantum Systems
Chapter 3 extends the foundational QAIS principles of superposition and entanglement into the realm of data encoding, demonstrating how classical information can be transformed into quantum states for computation and learning. It introduces angle encoding—a rotation-based embedding method—as one of the simplest and most interpretable quantum data-mapping techniques. By associating classical numerical values with rotation angles on the Bloch sphere, QAIS systems represent data not as binary bits, but as amplitudes and phases, enabling continuous, multidimensional learning spaces.
This chapter also emphasizes how statevector representations reveal the geometry of information: every encoding choice reshapes the landscape of quantum inference, determining how separable or entangled a dataset becomes when processed by quantum circuits.
This lab implements practical angle encoding, mapping classical data features into single-qubit rotations and visualizing their statevectors. Learners observe how encoded angles reposition the Bloch vector on the sphere, showing that quantum states can naturally represent continuous classical variables. The experiment bridges abstract QAIS data pipelines and concrete quantum circuit representations, illustrating how encoding defines the structure and capacity of quantum learning systems.
Beginner Lab 3 — Angle Encoding and Statevectors
Lab 3 translates these abstract encoding principles into tangible insight. Participants perform angle-based encoding on single-qubit states, visualize their rotations on the Bloch sphere, and examine how different angles correspond to distinct probability amplitudes. By observing how small angle changes produce continuous yet measurable shifts in quantum statevectors, learners gain intuition for how quantum systems represent data geometrically—a foundation for later labs involving feature maps and variational learning.
Goal: Implement and visualize angle encoding by mapping classical data values to single-qubit rotation angles. Learners prepare circuits using rotation gates (Rx, Ry, or Rz) to encode numerical inputs and simulate their resulting quantum statevectors. Using Bloch-sphere visualizations, participants observe how classical data transforms into distinct orientations within quantum state space.
This lab builds intuition for how data is represented and processed in QAIS, revealing that even a single qubit can encode a continuum of values through rotation. By comparing encoded statevectors and their corresponding measurement probabilities, learners connect the mathematics of rotation to the physical behavior of quantum amplitudes.
Expected Outcome
Through Bloch-sphere visualization, learners confirm that each rotation angle corresponds to a distinct quantum state orientation, confirming that classical data can be embedded as quantum amplitudes.
As the input angle varies, the qubit’s statevector moves smoothly along the Bloch sphere, demonstrating the continuous geometry of quantum information.
Measurement probabilities change predictably with the rotation angle—e.g., an Rx(π/2) or Ry(π/2) rotation yields roughly equal probabilities for |0⟩ and |1⟩—verifying that encoded data directly controls outcome distributions.
Learners observe that even a single qubit encodes a continuum of classical values, forming the foundation for quantum feature maps and variational learning in later QAIS models.
These results confirm that data encoding in QAIS is geometric rather than binary, and that controlled quantum rotations translate classical inputs into structured, measurable information patterns. Cross-reference: Appendix E.1, Figures E.1.3a–c — Angle Encoding and Bloch-Sphere Statevectors.
Task 1 - Figure Helper Utilities
Centralized utilities for Appendix E compliance. No plots generated here.
Description (what it does):
Defines save_e_figure(...) that saves exactly one file per plot with IEEE-style names
Uses a single figures root for all labs: Beginner_Labs/figures/
Enforces Beginner Part 1 naming: P1_BeginLab01_E.1.
.png (e.g., P1_BeginLab01_E.1.1a.png) Provides label_subplots(...) for (a)–(d) subfigure tags
# ---- Figure helper (robust; use in every coded lab) ----
import os, matplotlib.pyplot as plt
def save_e_figure(fig_label: str,
fname: str,
subdir: str = "Beginner_Labs/figures",
fig=None, ax=None):
"""Save the current/explicit figure with a prefixed label and consistent path."""
os.makedirs(subdir, exist_ok=True)
if fig is None:
fig = plt.gcf()
if ax is None:
ax = fig.axes[0] if fig.axes else None
if ax is None:
print("⚠️ No axes found. Draw a plot first, or pass fig/ax explicitly.")
return
title = ax.get_title() or ""
if not title.startswith(fig_label):
ax.set_title((fig_label + " — " + title).strip(" —"))
outpath = os.path.join(subdir, fname)
fig.tight_layout()
fig.savefig(outpath, dpi=160)
print("Saved", outpath)
Methodology Analysis
The helper centralizes Appendix-compliant naming with E_PART="E.1", LAB_STEM="P1_BeginLab01", and an output root Beginner_Labs/figures".
Each save_e_figure(fig_index, sub) writes an image uniquely keyed to its E.1 label.
Ensure you execute Task 1 before saving figures — successful saves print confirmations such as:
Saved figure → Beginner_Labs/figures/P1_BeginLab01_E.1.1a.png.
Participant Feedback
You won’t see a chart in this cell. Later, after plotting cells, look for a “Saved figure → …/Beginner_Labs/figures/…” line confirming correct filenames and destinations.
Task 2 — Environment Setup
This cell ensures the notebook has the required packages and imports for Qiskit + plotting. It does not create any figures.
Description (what it does):
Installs missing packages if needed (quietly)
Imports Qiskit (with Aer simulator), NumPy, and Matplotlib
Prints versions for reproducibility
# === Environment Setup ===
import sys, subprocess, pkgutil
def ensure(pkg):
if pkg not in {m.name for m in pkgutil.iter_modules()}:
subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-q', pkg])
for p in ['qiskit','qiskit-aer','matplotlib','numpy','scikit-learn']:
ensure(p)
import qiskit, numpy as np, matplotlib.pyplot as plt
print('Python:', sys.version.split()[0])
print('Qiskit:', qiskit.__version__)
Python: 3.12.11 Qiskit: 2.2.1
Methodology Analysis
Ensures simulator availability (e.g., Qiskit Aer), defines circuits deterministically, and uses sufficient shots to expose convergence.
Participant Feedback
If package installs occur, re-run the next cells. If imports fail, use “Restart and run all” to restore a clean state.
Task 3 — Angle Encoding as a Quantum Feature Mapping
Angle encoding is the simplest quantum method for transforming classical information into a qubit state. A single classical feature x in [0, 1] is mapped to a rotation angle θ = π · x about the Y-axis of the Bloch sphere.
This rotation positions the Bloch vector at a latitude proportional to the encoded value, creating a continuous geometric representation of the data. Unlike binary bit storage, this encoding embeds numerical features directly into quantum amplitudes and phases—forming the foundation of data-driven QAIS circuits.
Methodology Analysis
A single scalar feature x in [0, 1] is converted to a rotation angle θ = π·x and applied to a qubit with an Rᵧ(θ) gate.
The circuit begins in state ∣0⟩, performs this rotation, and the resulting statevector ∣ψ(θ)⟩ is extracted and plotted on the Bloch sphere. The visualization shows how the encoded angle positions the qubit at a latitude proportional to θ, forming a geometric representation of the data. One save call stores the figure as Beginner_Labs/figures/P1_BeginLab03_E.1.3a.png.
Challenge: Visualizing Angle Encoding on the Bloch Sphere
Write code that encodes a single classical feature θ as a Y-rotation on a qubit. Plot the resulting Bloch vector trajectory to show how the qubit moves along a latitude whose angle is proportional to θ. This exercise demonstrates how classical data values are mapped directly into quantum state geometry—making the relationship between feature magnitude and quantum state position visually apparent.
# === E.1.3a — Angle-encoded Bloch vector (single qubit) ===
# ✅ Displays inline in Colab AND saves figure correctly
# Handle Qiskit import differences
# --- Step 1: Encode feature as rotation angle ---
# --- Step 2: Generate plot (robust to Qiskit version) ---
# --- Step 3: Force inline render before saving ---
# --- Step 4: Save figure (one save call) ---
Saved Beginner_Labs/figures/P1_BeginLab03_E.1.3a.png
Figure E.1.3a. Angle-encoded Bloch vector.
The Bloch vector traces a latitude proportional to the encoded angle θ, illustrating how classical features can be mapped into quantum state amplitudes.
Expected Results
As θ increases from 0 to π, the Bloch vector moves smoothly from the north pole (∣0⟩) through the equatorial plane to the south pole (∣1⟩). Intermediate angles correspond to superposed states where the probabilities p(∣0⟩) = cos²(θ ⁄ 2) and p(∣1⟩) = sin²(θ ⁄ 2) evolve continuously. On the plot, this motion appears as a vector tracing a latitude arc whose height on the z-axis decreases monotonically with θ.
Technical Spotlight
For a single-qubit state prepared as
∣ψ(θ)⟩ = cos(θ ⁄ 2) ∣0⟩ + sin(θ ⁄ 2) ∣1⟩,
the statevector components (α, β) define a unit sphere in ℂ² with ∣α∣² + ∣β∣² = 1. The Bloch coordinates (x, y, z) = ( sin θ, 0, cos θ ) reveal how rotation angle directly determines probability amplitudes and measurement bias. This analytic relationship validates that the graphical Bloch representation precisely mirrors the mathematical encoding formula.
Intuition Sidebar
Think of the qubit as a compass needle pointing on a sphere. Each data value x gently tilts the needle away from the north pole by θ = π · x. A small x keeps the needle nearly upright (∣0⟩-like), while a large x rotates it toward the south pole (∣1⟩-like). Thus, angle encoding acts like a “quantum dial,” mapping continuous features into the geometry of state space and enabling QAIS to process numerical patterns through rotation instead of bits.
Participant Feedback
Confirm that the Bloch vector’s position matches the encoded rotation angle. As θ increases, the vector should tilt smoothly from the north pole (∣0⟩) toward the south pole (∣1⟩). Observe that the z-component of the vector corresponds to cos θ and the x-component to sin θ, confirming that the geometric motion on the Bloch sphere correctly represents the angle-encoded feature value.
Task 4 — Decomposing Quantum Amplitudes into Real and Imaginary Parts
After encoding a classical feature as a qubit rotation, the resulting statevector ∣ψ⟩ = α∣0⟩ + β∣1⟩ contains complex coefficients α and β.
Each coefficient has a real and imaginary component that together describe the magnitude and phase of the quantum state.
Plotting these four values—Re(α), Im(α), Re(β), Im(β)—reveals how information is distributed between the computational basis states.
This representation makes the invisible geometry of complex amplitudes visible, helping learners see that quantum information encodes both probability and phase, not just binary outcomes.
Methodology Analysis
The encoded qubit state ∣ψ⟩ = α∣0⟩ + β∣1⟩ is decomposed into its real and imaginary amplitude components to reveal how information is stored in magnitude and phase. The statevector values α and β are extracted, and their four parts — Re(α), Im(α), Re(β), and Im(β) — are plotted as bars to visualize the distribution of quantum information. This shows that amplitude and phase jointly define a qubit’s state while maintaining normalization ∣α∣² + ∣β∣² = 1. The resulting figure is saved as Beginner_Labs/figures/P1_BeginLab03_E.1.3b.png.
Challenge: Decoding Amplitude and Phase Information
Write code to decode the encoded quantum state |ψ⟩ = α|0⟩ + β|1⟩ into its real and imaginary components, showing how amplitude and phase jointly carry information. Visualize both parts to demonstrate that normalization enforces |α|² + |β|² = 1 for any rotation angle θ, ensuring the state remains physically valid on the Bloch sphere.
# === E.1.3b — Real and imaginary amplitude components (single qubit) ===
# reuse sv1 from the previous cell (single-qubit statevector)
# save (Beginner tier, E.1.3b)
Saved Beginner_Labs/figures/P1_BeginLab03_E.1.3b.png
Figure E.1.3b. Real and imaginary amplitude components.
Normalized bar heights show the relative magnitude and phase of each state amplitude, confirming amplitude normalization ∣ψ⟩ = α∣0⟩ + β∣1⟩.
Expected Results
The bar chart displays four bars of comparable scale whose squared magnitudes satisfy the normalization rule ∣α∣² + ∣β∣² = 1.
For small rotation angles θ, Re(α) ≈ 1 and Re(β) ≈ 0, corresponding mostly to ∣0⟩. As θ approaches π⁄2, both components become balanced; for larger θ, β dominates as the qubit approaches ∣1⟩.
Imaginary parts remain near 0 for pure Y-rotations but would vary under more general phase encodings.
Technical Spotlight
For a rotation Rᵧ(θ) applied to ∣0⟩, the statevector is
∣ψ(θ)⟩ = cos(θ ⁄ 2) ∣0⟩ + sin(θ ⁄ 2) ∣1⟩.
Here, α = cos(θ ⁄ 2) and β = sin(θ ⁄ 2).
Plotting Re(α), Im(α), Re(β), Im(β) confirms that imaginary parts vanish for pure real rotations, while the squared moduli follow the trigonometric relationships p(∣0⟩)=cos²(θ ⁄ 2) and p(∣1⟩)=sin²(θ ⁄ 2). This verifies that the Bloch-sphere description and the amplitude-component view are mathematically equivalent.
Intuition Sidebar
Imagine the quantum state as a pair of spinning arrows: one for ∣0⟩ and one for ∣1⟩. Each arrow’s length shows how likely that basis outcome is, while its direction in the complex plane shows how it interferes with others.
When you plot the real and imaginary parts, you are freezing the arrows in time—seeing both their reach and orientation.
This visualization demystifies the complex nature of quantum information and reinforces that probability and phase together define the qubit’s expressive power.
Participant Feedback
Confirm that the normalization condition holds numerically:
∣α∣² + ∣β∣² ≈ 1 within rounding tolerance.
Minor deviations arise only from finite-precision arithmetic.
This quantitative check verifies that the statevector is physically valid and that encoding has preserved unitarity.
Conclusion — Linking Quantum Geometry to Data Encoding
This lab demonstrated how classical features can be expressed as qubit rotations, transforming data into the geometry of the Bloch sphere. Through angle encoding, learners visualized how each feature value corresponds to a rotation angle that repositions the Bloch vector—and therefore changes the probabilities associated with ∣0⟩ and ∣1⟩ measurements.
By decomposing the resulting statevector into real and imaginary amplitude components, the experiment made clear that every qubit holds both magnitude and phase information, allowing quantum states to encode continuous data with high expressive capacity.
Together, the Bloch and amplitude visualizations revealed the dual nature of quantum representation: geometrical and algebraic.
This duality is what enables Quantum AI Systems (QAIS) to perform reasoning, classification, and inference using rotation and interference rather than fixed binary logic.
Key Take-aways
Angle encoding bridges classical and quantum data. * Each feature x ∈ [0,1] is mapped to a rotation θ = π·x, turning data points into measurable quantum geometries.
The Bloch sphere represents the geometry of learning. * Feature changes correspond to predictable rotations in 3D space, visualizing how QAIS manipulates encoded information.
Statevectors capture both probability and phase. * The real and imaginary components of ∣ψ⟩ = α∣0⟩ + β∣1⟩ encode richer information than classical bits, forming the basis for quantum feature spaces.
Normalization maintains physical validity. * The constraint ∣α∣² + ∣β∣² = 1 ensures encoded data correspond to valid quantum states on the Bloch sphere.
QAIS inference depends on encoding choice. * The way data are mapped—angle, amplitude, or phase encoding—determines how separable or entangled features become during learning.
Congratulations
Congratulations on completing E.1 Lab 3 — Angle Encoding & Statevectors. You have moved beyond quantum superposition and entanglement into the quantum representation of data itself—the essential foundation for all machine learning tasks in QAIS. By successfully visualizing angle-based feature mappings and amplitude decompositions, you’ve taken a crucial step toward understanding how quantum circuits act as geometric data transformers.
Your progress now positions you to explore multi-qubit encoding schemes in the intermediate labs (E.2 tier), where you’ll learn how rotations combine and interact through entanglement and interference to perform meaningful computations. Keep this insight: in quantum AI, geometry is information.
Appendix E → Appendix B Cross-Reference
See Appendix B — Quick Self-Check, Chapter 3 — Encoding Classical Data in Quantum Systems:
- Questions 2–3 (encoding methods and Bloch representation).
These review how classical features map onto quantum states as explored in E.1 Lab 3a-b.
📌 How to save or submit your work
If you are a student (graded/evaluated):
- Export your key plots or the entire notebook to PDF (File → Print/Save as PDF).
- Save the notebook (
.ipynb). - Bundle any extra files (CSVs/images) if used.
- Upload to your LMS or repository as instructed (include your name and lab number).
- Repro checklist: set a random seed where applicable, note backend and shots, and list package versions.
- If you are a professional/self‑learner (non‑graded exercise):
- Save the notebook (
File → Download .ipynb) to your computer for personal reference. - Optionally export to PDF for archiving.
- Keep any generated plots or data locally.
- Use version control (GitHub, GitLab) if you wish to track your personal progress.
- Save the notebook (
Official DOI: 10.5281/zenodo.17212825
Companion Repository: quscitech-labs
Publisher: QuSciTech Press
DOI + © + QuSciTech