qsharp Module

Q# interpreter public API.

This module is the public surface for Q# interpreter functionality within the qdk package.

Key exports:

Classes

BitFlipNoise

The bit flip noise to use in simulation.

Creates a new BitFlipNoise instance.

The bit flip channel applies a Pauli-X error with probability p.

CircuitGenerationMethod
DepolarizingNoise

The depolarizing noise to use in simulation.

Creates a new DepolarizingNoise instance.

The depolarizing channel applies Pauli-X, Pauli-Y, or Pauli-Z errors each with probability p / 3.

Pauli

A Q# Pauli operator.

PauliNoise

The Pauli noise to use in simulation represented as probabilities of Pauli-X, Pauli-Y, and Pauli-Z errors

Creates a new PauliNoise instance with the given error probabilities.

PhaseFlipNoise

The phase flip noise to use in simulation.

Creates a new PhaseFlipNoise instance.

The phase flip channel applies a Pauli-Z error with probability p.

QSharpError

An error returned from the Q# interpreter.

Result

A Q# measurement result.

ShotResult

A single result of a shot.

StateDump

A state dump returned from the Q# interpreter.

TargetProfile

A Q# target profile.

A target profile describes the capabilities of the hardware or simulator which will be used to run the Q# program.

Functions

circuit

Synthesizes a circuit for a Q# program. Either an entry expression or an operation must be provided.

circuit(entry_expr: str | Callable | GlobalCallable | Closure | None = None, *args, operation: str | None = None, generation_method: CircuitGenerationMethod | None = None, max_operations: int | None = None, source_locations: bool = False, group_by_scope: bool = True, prune_classical_qubits: bool = False) -> Circuit

Parameters

Name Description
entry_expr

An entry expression. Alternatively, a callable can be provided, which must be a Q# callable.

Default value: None
*args
Required

The arguments to pass to the callable, if one is provided.

Keyword-Only Parameters

Name Description
operation
str

The operation to synthesize. This can be a name of an operation or a lambda expression. The operation must take only qubits or arrays of qubits as parameters.

Default value: None
generation_method

The method to use for circuit generation. ClassicalEval evaluates classical control flow at circuit generation time. Simulate runs a full simulation to trace the circuit. Static uses partial evaluation and requires a non-Unrestricted target profile. Defaults to None which auto-selects the generation method.

Default value: None
max_operations
int

The maximum number of operations to include in the circuit. Defaults to None which means no limit.

Default value: None
source_locations

If True, annotates each gate with its source location.

Default value: False
group_by_scope

If True, groups operations by their containing scope, such as function declarations or loop blocks.

Default value: True
prune_classical_qubits

If True, removes qubits that are never used in a quantum gate (e.g. qubits only used as classical controls).

Default value: False

Returns

Type Description
<xref:Circuit>

The synthesized circuit.

Exceptions

Type Description

If there is an error synthesizing the circuit.

compile

Compiles the Q# source code into a program that can be submitted to a target. Either an entry expression or a callable with arguments must be provided.

Example:

compile(entry_expr: str | Callable | GlobalCallable | Closure, *args) -> QirInputData

Parameters

Name Description
entry_expr
Required

The Q# expression that will be used as the entrypoint for the program. Alternatively, a callable can be provided, which must be a Q# callable.

*args
Required

The arguments to pass to the callable, if one is provided.

Returns

Type Description
<xref:QirInputData>

The compiled program. Use str() to get the QIR string.

dump_circuit

Dumps a circuit showing the current state of the simulator.

This circuit will contain the gates that have been applied in the simulator up to the current point.

Requires the interpreter to be initialized with trace_circuit=True.

dump_circuit() -> Circuit

Returns

Type Description
<xref:Circuit>

The current circuit trace.

Exceptions

Type Description

If the interpreter was not initialized with trace_circuit=True

dump_machine

Returns the sparse state vector of the simulator as a StateDump object.

dump_machine() -> StateDump

Returns

Type Description

The state of the simulator.

dump_operation

Returns a square matrix of complex numbers representing the operation performed.

dump_operation(operation: str, num_qubits: int) -> List[List[complex]]

Parameters

Name Description
operation
Required

The operation to be performed, which must operate on a list of qubits.

num_qubits
Required

The number of qubits to be used.

Returns

Type Description

The matrix representing the operation.

estimate

Estimates resources for Q# source code. Either an entry expression or a callable with arguments must be provided.

Deprecated since version This: function uses the legacy Resource Estimator API. Use qdk.qre instead.

estimate(entry_expr: str | Callable | GlobalCallable | Closure, params: Dict[str, Any] | List | EstimatorParams | None = None, *args) -> EstimatorResult

Parameters

Name Description
entry_expr
Required

The entry expression. Alternatively, a callable can be provided, which must be a Q# callable.

params

The parameters to configure physical estimation.

Default value: None
*args
Required

The arguments to pass to the callable, if one is provided.

Returns

Type Description

The estimated resources.

estimate_custom

estimate_custom(algorithm, qubit, qec, factories=Ellipsis, *, error_budget=0.01, max_factories=None, logical_depth_factor=None, max_physical_qubits=None, max_duration=None, error_budget_pruning=False)

Parameters

Name Description
algorithm
Required
qubit
Required
qec
Required
factories
Default value: Ellipsis

Keyword-Only Parameters

Name Description
error_budget
Default value: 0.01
max_factories
Default value: None
logical_depth_factor
Default value: None
max_physical_qubits
Default value: None
max_duration
Default value: None
error_budget_pruning
Default value: False

eval

Evaluates Q# source code.

Output is printed to console.

eval(source: str, *, save_events: bool = False) -> Any

Parameters

Name Description
source
Required

The Q# source code to evaluate.

Keyword-Only Parameters

Name Description
save_events

If true, all output will be saved and returned. If false, they will be printed.

Default value: False

Returns

Type Description
Any

The value returned by the last statement in the source code, or the saved output if save_events is true.

Exceptions

Type Description

If there is an error evaluating the source code.

init

Initializes the Q# interpreter.

init(*, target_profile: TargetProfile = TargetProfile.Unrestricted, target_name: str | None = None, project_root: str | None = None, language_features: List[str] | None = None, trace_circuit: bool | None = None) -> Config

Keyword-Only Parameters

Name Description
target_profile

Setting the target profile allows the Q# interpreter to generate programs that are compatible with a specific target. See TargetProfile.

Default value: Unrestricted
target_name

An optional name of the target machine to use for inferring the compatible target_profile setting.

Default value: None
project_root

An optional path to a root directory with a Q# project to include. It must contain a qsharp.json project manifest.

Default value: None
language_features

An optional list of language feature flags to enable. These correspond to experimental or preview Q# language features. Valid values are:

  • "v2-preview-syntax": Enables Q# v2 preview syntax. This removes support for the scoped qubit allocation block form (use q = Qubit() { ... }), requiring the statement form instead (use q = Qubit();). It also removes the requirement to use the set keyword for mutable variable assignments.
Default value: None
trace_circuit

Enables tracing of circuit during execution. Passing True is required for the dump_circuit function to return a circuit. The circuit function is NOT affected by this parameter and will always generate a circuit.

Default value: None

Returns

Type Description
<xref:Config>

The Q# interpreter configuration.

logical_counts

Extracts logical resource counts from Q# source code. Either an entry expression or a callable with arguments must be provided.

logical_counts(entry_expr: str | Callable | GlobalCallable | Closure, *args) -> LogicalCounts

Parameters

Name Description
entry_expr
Required

The entry expression. Alternatively, a callable can be provided, which must be a Q# callable.

Returns

Type Description

Program resources in terms of logical gate counts.

run

Runs the given Q# expression for the given number of shots. Each shot uses an independent instance of the simulator.

run(entry_expr: str | Callable | GlobalCallable | Closure, shots: int, *args, on_result: Callable[[ShotResult], None] | None = None, save_events: bool = False, noise: Tuple[float, float, float] | PauliNoise | BitFlipNoise | PhaseFlipNoise | DepolarizingNoise | NoiseConfig | None = None, qubit_loss: float | None = None, seed: int | None = None, type: Literal['sparse', 'clifford'] | None = None, num_qubits: int | None = None) -> List[Any]

Parameters

Name Description
entry_expr
Required

The entry expression. Alternatively, a callable can be provided, which must be a Q# callable.

shots
Required

The number of shots to run.

*args
Required

The arguments to pass to the callable, if one is provided.

on_result
Required

A callback function that will be called with each result.

save_events
Required

If true, the output of each shot will be saved. If false, they will be printed.

noise
Required

The noise to use in simulation.

qubit_loss
Required

The probability of qubit loss in simulation.

seed
Required

The seed to use for the random number generator in simulation, if any.

type
Required

The type of simulator to use. If not specified, the default sparse state vector simulation will be used.

num_qubits
Required

The number of qubits to use for the simulation type "clifford". If not specified, the Clifford simulator assumes a default of 1000 qubits.

Keyword-Only Parameters

Name Description
on_result
Default value: None
save_events
Default value: False
noise
Default value: None
qubit_loss
Default value: None
seed
Default value: None
type
Default value: None
num_qubits
Default value: None

Returns

Type Description

A list of results or runtime errors. If save_events is true, a list of ShotResult is returned.

Exceptions

Type Description

If there is an error interpreting the input.

If the number of shots is less than 1.

set_classical_seed

Sets the seed for the random number generator used for standard library classical random number operations. This applies to all Q# code executed, compiled, or estimated.

set_classical_seed(seed: int | None) -> None

Parameters

Name Description
seed
Required

The seed to use for the classical random number generator. If None, the seed will be generated from entropy.

set_quantum_seed

Sets the seed for the random number generator used for quantum measurements. This applies to all Q# code executed, compiled, or estimated.

set_quantum_seed(seed: int | None) -> None

Parameters

Name Description
seed
Required

The seed to use for the quantum random number generator. If None, the seed will be generated from entropy.