Context Class
An isolated Q# interpreter environment.
A Context provides a self-contained Q# execution environment where code is evaluated, compiled, and executed in isolation from other Context instances. Each Context maintains its own code namespace.
A context has a code attribute which is a Python module containing all Q# operations and types defined in this context. This allows you to call Q# operations from Python.
Example:
ctx = qdk.Context()
ctx.eval("operation Main() : Result { use q = Qubit(); X(q); MResetZ(q) }")
assert ctx.run("Main()", 2) == [qdk.Result.One, qdk.Result.One]
assert ctx.code.Main() == qdk.Result.One
Initializes a new isolated Q# context.
Constructor
Context(*, 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, _is_global_context: bool = False)
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:
the scoped qubit allocation block form ( Default value: None
|
|
_trace_circuit
|
Default value: None
|
|
_is_global_context
|
Default value: False
|
Methods
| circuit |
Synthesizes a circuit for a Q# program. Either an entry expression or an operation must be provided. |
| 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: |
| dump_machine |
Returns the sparse state vector of the simulator as a StateDump object. |
| eval |
Evaluates Q# source code. Output is printed to console. |
| get_target_profile |
Returns target profile for this Context. |
| import_openqasm |
Imports OpenQASM source code into this context's interpreter. |
| logical_counts |
Extracts logical resource counts from Q# source code. Either an entry expression or a callable with arguments must be provided. |
| run |
Runs the given Q# expression for the given number of shots. Each shot uses an independent instance of the simulator. |
| 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 in this Context. |
| 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 in this Context. |
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
|
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- Default value: None
|
|
max_operations
|
The maximum number of operations to include in the
circuit. Defaults to Default value: None
|
|
source_locations
|
If Default value: False
|
|
group_by_scope
|
If Default value: True
|
|
prune_classical_qubits
|
If 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 |
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. |
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 |
|---|---|
|
The value returned by the last statement in the source code, or the
saved output if |
Exceptions
| Type | Description |
|---|---|
|
If there is an error evaluating the source code. |
get_target_profile
Returns target profile for this Context.
get_target_profile() -> TargetProfile
import_openqasm
Imports OpenQASM source code into this context's interpreter.
import_openqasm(source: str, **kwargs: Any) -> Any
Parameters
| Name | Description |
|---|---|
|
source
Required
|
An OpenQASM program or fragment. |
|
**kwargs
Required
|
Additional keyword arguments. Common options:
|
Returns
| Type | Description |
|---|---|
|
The value returned by the last statement in the source code. |
Exceptions
| Type | Description |
|---|---|
|
If there is an error generating, parsing, or analyzing the OpenQASM source. |
|
|
If there is an error compiling the program. |
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 |
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 in this Context.
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 in this Context.
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. |
Attributes
code
code: Any