liveBook · Manning

Q# operation

As explained in Quantum Programming in Depth

A Q# operation is a callable Q# construct that can accept parameters, act on qubits, and return a value.

A Q# operation is a callable construct that accepts parameters, acts on qubits, and returns a value. Quantum gates are represented as operations; gates that change qubit states return Unit. Built-in gates live in the Std.Intrinsic namespace, while custom gates can be defined and called similarly. section 2.3.4

Operations can encode state preparation directly from equations. For example, PrepOneQubit computes theta = 2.0 * ArcTan2(beta, alpha) and applies Ry(theta, q) to prepare a qubit from coefficients alpha and beta.

Quantum-gate operations support specialized invocation forms:

  • Declare adjoint and controlled capabilities with is Adj + Ctl; the compiler can generate these specializations for suitable Unit-returning operations acting on qubits. section 2.3.4
  • Use Adjoint and Controlled to obtain the corresponding operation variants, or use ApplyControlledOnInt for integer-controlled application. section 2.3.4
  • Fix selected arguments with partial application; supplied arguments become fixed, while underscores remain parameters of the resulting operation. section 3.2.2

Preparing and inspecting a two-qubit state

PrepTwoQubits derives intermediate coefficients, prepares one qubit, and applies controlled instances of PrepOneQubit. RunPrepTwoQubitsDemo supplies [0.36, 0.48, 0.64, -0.48], then DumpMachine reports amplitudes and probabilities for |00>, |01>, |10>, and |11>.

Listing 3.5 Python code to get the matrix of a Q# operation
import qsharp
from qsharp.utils import dump_operation

coef = [[0.6, -0.8], [0.8, 0.6]]

qsharp.init(project_root='.')
print(dump_operation(f"UnitaryImplementation.ApplyOneQubit(_, \{coef\})", 1))

Inspect a Q# operation's matrix from Python with qsharp.utils.dump_operation after partially applying its coefficient argument. section 3.2.2

How Quantum Programming in Depth covers it

How deep it goes
Explains signatures, Unit returns, adjoint and controlled specializations, partial application, and matrix inspection through Python.
Examples
Uses PrepOneQubit, PrepTwoQubits, DumpMachine, and Python dump_operation to demonstrate execution, state inspection, and matrix extraction.
What it assumes
Assumes working Q# code and introduces Python-based quantum-state and operation-matrix inspection when direct Q# testing is insufficient.
What you can do after
Build it from scratch as custom Q# gates, invoke specialized variants, partially apply parameters, and inspect implemented matrices.
How it connects
Connects quantum gates, state preparation, controlled operations, adjoint operations, partial application, and unitary matrices.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Quantum Programming in Depth. The section links point to the parts of the book it draws on.