### Install Pre-commit Hooks Source: https://github.com/qiskit/samplomatic/blob/main/CONTRIBUTING.md Install the pre-commit hooks defined in the .pre-commit-config.yaml file. ```bash pre-commit install ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/qiskit/samplomatic/blob/main/CONTRIBUTING.md Install the project in editable mode with development and visualization requirements. ```bash pip install -e ".[dev,vis]" ``` -------------------------------- ### Install Samplomatic Source: https://github.com/qiskit/samplomatic/blob/main/README.md Install the Samplomatic library using pip. Include visualization dependencies if needed. ```bash pip install samplomatic ``` ```bash pip install samplomatic[vis] ``` -------------------------------- ### Build Sphinx Documentation Source: https://github.com/qiskit/samplomatic/blob/main/CONTRIBUTING.md Commands to clean and build the HTML documentation using Sphinx. Ensure samplomatic is installed with development requirements first. ```bash docs$ make clean docs$ make html ``` -------------------------------- ### Build a Samplex and Template from a Boxed Circuit Source: https://github.com/qiskit/samplomatic/blob/main/docs/guides/samplex_io.ipynb Constructs a `template` and `samplex` pair from a `QuantumCircuit` that has been 'boxed' with operations like `Twirl` and `InjectNoise`. This setup is used for generating parametric probability distributions and preparing circuits for sampling. ```python import matplotlib.pyplot as plt import numpy as np from qiskit.circuit import ClassicalRegister, Parameter, QuantumCircuit, QuantumRegister from qiskit.quantum_info import Operator, Pauli, PauliLindbladMap from samplomatic import ChangeBasis, InjectNoise, Twirl, build # our circuit has two classical registers named alpha and beta circuit = QuantumCircuit( QuantumRegister(4), alpha := ClassicalRegister(3, "alpha"), beta := ClassicalRegister(1, "beta") ) # the first box is only twirled with circuit.box([Twirl()]): for idx in range(4): circuit.rx(Parameter(f"a{idx}"), idx) circuit.cz(0, 1) circuit.cz(1, 2) # the second box is twirled, and has noise injected with circuit.box([Twirl(), InjectNoise(ref="ref1", modifier_ref="mod_ref1")]) : circuit.h(1) circuit.cz(1, 2) # the third box is twirled, and has different noise injected with circuit.box([Twirl(), InjectNoise(ref="ref2", modifier_ref="mod_ref2")]) : circuit.rx(0.1, range(4)) circuit.cz(0, 1) circuit.cz(1, 2) # the fourth box is the same as the second, but with a different modifer ref with circuit.box([Twirl(), InjectNoise(ref="ref1", modifier_ref="mod_ref3")]) : circuit.h(1) circuit.cz(1, 2) circuit.barrier() # the final two boxes twirl, and add a basis change in one case with circuit.box([Twirl(), ChangeBasis(ref="conclude")]) : circuit.measure(range(3), alpha) with circuit.box([Twirl()]) : circuit.measure([3], beta) circuit.draw("mpl") ``` ```python template, samplex = build(circuit) template.draw("mpl", fold=100) ``` -------------------------------- ### Simulating Expectation Values with StatevectorEstimator and StatevectorSampler Source: https://github.com/qiskit/samplomatic/blob/main/docs/guides/samplex_io.ipynb This example demonstrates simulating expectation values from a base circuit using StatevectorEstimator and then comparing them with results from a sampler that includes measurement twirling and bitflip correction. It requires importing StatevectorEstimator and StatevectorSampler. ```python from qiskit.primitives import StatevectorEstimator as Estimator from qiskit.primitives import StatevectorSampler as Sampler from qiskit.primitives.containers import BitArray # simulate some expectation values direction from the base circuit estimator_job = Estimator().run([(unboxed, ["IZII", "IIZI", "IIIZ"])] ) ev s = estimator_job.result()[0].data["evs"] # get the sampler data from each randomization, and do bitflip correction sampler_job = Sampler().run([(template, outputs["parameter_values"])], shots=10_000) alpha_data = sampler_job.result()[0].data["alpha"] alpha_data ^= BitArray.from_bool_array(outputs["measurement_flips.alpha"], "little") # compare the results print(" EVs from base circuit:", evs) print("EVs from randomizations:", alpha_data.expectation_values(["ZII", "IZI", "IIZ"]))) ``` -------------------------------- ### Create a Sample Quantum Circuit Source: https://github.com/qiskit/samplomatic/blob/main/docs/guides/transpiler.ipynb This code defines a sample quantum circuit with Hadamard, CZ, CX, RZ, and RX gates, along with measurements. This circuit is used throughout the guide to demonstrate the effects of the transpiler. ```python from qiskit.circuit import Parameter, QuantumCircuit circuit = QuantumCircuit(4, 7) circuit.h(1) circuit.h(2) circuit.cz(1, 2) circuit.h(1) circuit.cx(1, 0) circuit.cx(2, 3) circuit.measure(range(1, 4), range(3)) circuit.cx(0, 1) circuit.cx(1, 2) circuit.cx(2, 3) for qubit in range(4): circuit.rz(Parameter(f"th_{qubit}"), qubit) circuit.rx(Parameter(f"phi_{qubit}"), qubit) circuit.rz(Parameter(f"lam_{qubit}"), qubit) circuit.measure(range(4), range(3, 7)) circuit.draw("mpl", scale=0.8) ``` -------------------------------- ### Build Quantum Circuit with Twirl Annotations Source: https://github.com/qiskit/samplomatic/blob/main/README.md Construct a Qiskit quantum circuit with twirl annotations using `samplomatic.Twirl`. This example demonstrates twirling single-qubit gates and measurements. ```python from samplomatic import build, Twirl from qiskit.circuit import QuantumCircuit, Parameter import numpy as np circuit = QuantumCircuit(5) with circuit.box([Twirl()]): # twirled boxes are always "dressed": putting your single-qubit gates into # the boxes will result in them being composed into the "dressing" layer # that also includes random (in this case) Paulis circuit.sx(0) circuit.t(0) # notice that twirl-annotated circuits can themselves be parametric circuit.rx(Parameter("x"), 3) circuit.rx(Parameter("y"), 4) circuit.x(2) circuit.cx(1, 0) circuit.cz(3, 4) with circuit.box([Twirl(decomposition="rzrx")]): # this box Pauli-twirls measurement, folding hadamards into the dressing circuit.h(range(5)) circuit.measure_all() circuit.draw("mpl", scale=0.5) ``` -------------------------------- ### Print Samplex Summary Source: https://github.com/qiskit/samplomatic/blob/main/docs/guides/debug_tracing.ipynb Use `print(samplex)` to get a text summary of the node count, required inputs, and promised outputs of a samplex object. This is useful for a quick overview before diving into visualizations or detailed inspection. ```python template, samplex = build(circuit) print(samplex) ``` -------------------------------- ### Combine Preset Pass Managers with Boxing for Heisenberg Circuit Source: https://github.com/qiskit/samplomatic/blob/main/docs/guides/transpiler.ipynb Applies a preset pass manager that includes Samplomatic's boxing pass manager as a post-scheduling step to the Heisenberg circuit. This results in a transpiled circuit with boxes guided by the original barriers. ```python preset_pm = generate_preset_pass_manager( basis_gates=["rz", "sx", "cx"], coupling_map=[[0, 1], [1, 2], [2, 3], [3, 4], [4, 0]], optimization_level=1, ) preset_pm.post_scheduling = generate_boxing_pass_manager() boxed_heisenberg = preset_pm.run(heisenberg) boxed_heisenberg.draw("mpl", scale=0.5, fold=100) ``` -------------------------------- ### Transpile circuit with unboxed measurements and collect virtual gates Source: https://github.com/qiskit/samplomatic/blob/main/docs/guides/transpiler.ipynb Transpiles a circuit with unmeasured qubits, disabling measurement boxing. This example shows how a right-dressed box is added to collect virtual gates when measurements are not boxed. ```python boxing_pass_manager = generate_boxing_pass_manager( enable_gates=True, enable_measures=False, ) transpiled_circuit = boxing_pass_manager.run(circuit_with_unmeasured_qubit) transpiled_circuit.draw("mpl", scale=0.8) ``` -------------------------------- ### Compare Past Benchmarks with Histograms Source: https://github.com/qiskit/samplomatic/blob/main/CONTRIBUTING.md Generate SVG files to compare past plots. Requires 'pip install pygal pygaljs'. Group comparisons by name. ```bash pytest-benchmark compare PATH --histogram --group-by=name ``` -------------------------------- ### Bind Basis Changes with Qubit Ordering Source: https://github.com/qiskit/samplomatic/blob/main/docs/guides/samplex_io.ipynb Binds basis changes to a Samplex, utilizing the qubit ordering convention. This example demonstrates how to specify rotations for qubits 0, 1, and 2 using their respective operator eigenstates (X, Y, Z) and the symplectic convention. ```python samplex.inputs().bind(basis_changes={"conclude": (basis_change := [2, 3, 1])}) basis_change ``` -------------------------------- ### Bind Pauli Lindblad Map with Qubit Ordering Source: https://github.com/qiskit/samplomatic/blob/main/docs/guides/samplex_io.ipynb Binds a Pauli Lindblad map to a Samplex, using the determined qubit ordering convention. This example shows how to specify noise for a specific qubit (index 1 in this case) within a 2-qubit noise model. ```python samplex.inputs().bind( pauli_lindblad_maps={ "ref1": (noise1 := PauliLindbladMap.from_sparse_list([("X", [1], 0.12)], num_qubits=2)) } ) noise1 ``` -------------------------------- ### Build Samplex and Template from Circuit Source: https://github.com/qiskit/samplomatic/blob/main/docs/api/auto/samplomatic.samplex.Samplex.md Builds a samplex and its corresponding template circuit from a base circuit with annotated box instructions. This is the typical way to generate a samplex instance. The resulting samplex can be visualized using its `draw()` method. ```python from samplomatic import build, Twirl from qiskit import QuantumCircuit circuit = QuantumCircuit(2) with circuit.box([Twirl()]): circuit.cz(0, 1) with circuit.box([Twirl()]): circuit.measure_all() template, samplex = build(circuit) samplex.draw() ``` -------------------------------- ### samplomatic.graph_utils.find_unreachable_nodes Source: https://github.com/qiskit/samplomatic/blob/main/docs/api/auto/samplomatic.graph_utils.find_unreachable_nodes.md Finds all nodes in a graph that are not reachable from a given set of starting nodes. ```APIDOC ## samplomatic.graph_utils.find_unreachable_nodes ### Description Finds all nodes from the graph that are not reachable from the start nodes. ### Method Signature samplomatic.graph_utils.find_unreachable_nodes(graph: PyDiGraph, start_idxs: Sequence[int]) -> set[int] ### Parameters #### Path Parameters * **graph** (PyDiGraph) - The graph to search. * **start_idxs** (Sequence[int]) - The node indices to start from. ### Returns #### Success Response * **set[int]** - A set of the unreachable node indices. ``` -------------------------------- ### FrozenDict Class Methods Source: https://github.com/qiskit/samplomatic/blob/main/docs/api/auto/samplomatic.utils.FrozenDict.md Documentation for the methods available on the FrozenDict class, including copy, get, items, keys, and values. ```APIDOC ## FrozenDict ### Description An immutable and hashable dictionary-like mapping. Keys and values must be hashable. Views onto keys, items, and values are read-only and preserve insertion order. Standard operands like `|` are supported, but return copies when necessary. ### Methods #### copy() **Description:** Return `self`, since this instance is immutable. #### get(k[,d]) **Description:** Returns the value for key `k` if `k` is in the dictionary, otherwise returns `d`. `d` defaults to `None`. #### items() **Description:** Returns a set-like object providing a view on the dictionary's items. #### keys() **Description:** Returns a set-like object providing a view on the dictionary's keys. #### values() **Description:** Returns an object providing a view on the dictionary's values. ``` -------------------------------- ### Specification Class Methods Source: https://github.com/qiskit/samplomatic/blob/main/docs/api/auto/samplomatic.tensor_interface.Specification.md This section details the methods available for the Specification class, including how to get a human-readable description and how to validate and coerce input values. ```APIDOC ## describe() ### Description Return a human-readable description of this specification. ### Method `describe()` ### Returns - `str`: A human-readable description of the specification. ``` ```APIDOC ## validate_and_coerce(value) ### Description Coerce a value into a correct type if valid. ### Method `validate_and_coerce(value: Any)` ### Parameters #### Parameters - **value** (Any) - A value to validate and coerce with respect to this specification. ### Raises - **TypeError**: If the value cannot be coerced into a valid type. ### Returns - `tuple[T, dict[str, int]]`: The coerced value, and a dictionary mapping each member of `free_dimensions` to a size implied by the `value`. ``` -------------------------------- ### SamplexOutput Constructor Source: https://github.com/qiskit/samplomatic/blob/main/docs/api/auto/samplomatic.samplex.SamplexOutput.md Initializes a SamplexOutput object. This class represents the output of a single call to the sample() method. ```APIDOC ## SamplexOutput Constructor ### Description Initializes a SamplexOutput object, which encapsulates the results of a sampling operation. It holds specifications for the output tensors and associated metadata. ### Method __init__ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **specs** (Iterable[TensorSpecification]) - Required - An iterable of specifications for the allowed data in this interface. * **metadata** (dict[str, Any] | None) - Optional - Information relating to the process of sampling. ### Request Example ```python # Example usage (conceptual) from samplomatic.tensor_interface import TensorSpecification specs = [TensorSpecification(name='q', shape=(1,), dtype='int32'), TensorSpecification(name='p', shape=(1,), dtype='float64')] metadata = {'shots': 100} output = SamplexOutput(specs=specs, metadata=metadata) ``` ### Response #### Success Response (200) N/A (This is a constructor) #### Response Example N/A (This is a constructor) ``` -------------------------------- ### samplomatic.build Source: https://github.com/qiskit/samplomatic/blob/main/docs/api/index.md Build a circuit template and samplex for the given boxed-up circuit. ```APIDOC ## Function: samplomatic.build ### Description Build a circuit template and samplex for the given boxed-up circuit. ### Parameters * **circuit** - The boxed-up circuit to process. * **debug** - Optional. If true, enables debug mode. ``` -------------------------------- ### Configure Plotly for Sphinx Gallery Source: https://github.com/qiskit/samplomatic/blob/main/docs/guides/debug_tracing.ipynb Ensures Plotly outputs are rendered correctly within Sphinx Gallery documentation. This setup is necessary for visualizing Plotly-based figures in the documentation. ```python import plotly.io as pio pio.renderers.default = "sphinx_gallery" ``` -------------------------------- ### build Source: https://github.com/qiskit/samplomatic/blob/main/docs/api/samplomatic.builders.md Builds a circuit template and samplex for a given boxed-up circuit. This function is promoted to the parent namespace. ```APIDOC ## build ### Description Build a circuit template and samplex for the given boxed-up circuit. ### Method Not specified (likely a Python function call) ### Parameters - **circuit** (type not specified) - Required - The boxed-up circuit to process. - **debug** (type not specified) - Optional - Debugging flag. ``` -------------------------------- ### Generate PassManager with Only Measurements Grouped Source: https://github.com/qiskit/samplomatic/blob/main/docs/guides/transpiler.ipynb This example demonstrates creating a PassManager where only measurements are grouped into boxes, disabling the grouping of two-qubit gates. This is useful when only measurement layers need specific annotation or processing. ```python boxing_pass_manager = generate_boxing_pass_manager( enable_gates=False, enable_measures=True, ) transpiled_circuit = boxing_pass_manager.run(circuit) transpiled_circuit.draw("mpl", scale=0.8) ``` -------------------------------- ### Bind Minimum Required Inputs and Sample Source: https://github.com/qiskit/samplomatic/blob/main/docs/guides/samplex_io.ipynb Bind the bare minimum required inputs for a Samplex object and draw randomizations. This includes Pauli Lindblad maps, basis change arrays, and parameter values. ```python inputs = samplex.inputs().bind( # bind() concatenates nested dicts with a '.' so that we can # set 'pauli_lindblad_maps.noise0/1' as follows. note that the # names 'ref1' and 'ref2' derive from the names in the InjectNoise # annotation. pauli_lindblad_maps={ "ref1": PauliLindbladMap.identity(2), "ref2": PauliLindbladMap.identity(4), }, # likewise, we can set all basis changes as follows, where # the name 'conclude' comes from our basis change annotation basis_changes={"conclude": [0, 1, 2]}, # we must provide values for all parameters in the original circuit parameter_values=np.linspace(0, 1, 4), ) outputs = samplex.sample(inputs, num_randomizations=3) print(outputs) ``` -------------------------------- ### Run Ruff Linter and Formatter Source: https://github.com/qiskit/samplomatic/blob/main/CONTRIBUTING.md Manually apply linting and formatting checks using ruff. ```bash ruff check . ``` -------------------------------- ### Sample Using Dictionary Input Source: https://github.com/qiskit/samplomatic/blob/main/docs/guides/samplex_io.ipynb Provide inputs to the Samplex.sample method as a standard dictionary. The method internally binds and validates the dictionary items against the input interface. ```python inputs = { "pauli_lindblad_maps": { "ref1": PauliLindbladMap.identity(2), "ref2": PauliLindbladMap.identity(4), }, "basis_changes": {"conclude": [0, 1, 2]}, "parameter_values": np.linspace(0, 1, 4), } outputs = samplex.sample(inputs, num_randomizations=3) ``` -------------------------------- ### Apply Boxing Pass Manager to ISA Circuit Source: https://github.com/qiskit/samplomatic/blob/main/docs/guides/transpiler.ipynb Applies Samplomatic's boxing pass manager to the transpiled ISA circuit. This process groups the circuit layers, guided by the preserved barriers, into separate boxes. ```python boxing_pm = generate_boxing_pass_manager() boxed_isa = boxing_pm.run(isa_circuit) boxed_isa.draw("mpl", scale=0.5, fold=100) ``` -------------------------------- ### samplomatic.builders.pre_build Source: https://github.com/qiskit/samplomatic/blob/main/docs/api/auto/samplomatic.builders.pre_build.md Builds a template state and a pre-samplex for the given boxed-up circuit. This is a helper method to `build()` and is not intended to be useful in standard workflows. ```APIDOC ## samplomatic.builders.pre_build(circuit: QuantumCircuit, debug: bool = False) -> tuple[TemplateState, [PreSamplex](samplomatic.pre_samplex.PreSamplex.md#samplomatic.pre_samplex.PreSamplex)] ### Description Build a template state and a pre-samplex for the given boxed-up circuit. This is a helper method to `build()` and is not intended to be useful in standard workflows. ### Parameters #### Parameters - **circuit** (QuantumCircuit) - Required - The circuit to build. - **debug** (bool) - Optional - Whether to populate pre-nodes with information that traces them back to the boxes that generated them. Tracing information is based on `ref` attributes of box annotations. ### Returns The built template state and the corresponding pre-samplex. ``` -------------------------------- ### Create Base Circuit for Twirling Strategy Demonstration Source: https://github.com/qiskit/samplomatic/blob/main/docs/guides/transpiler.ipynb Defines a sample `QuantumCircuit` with Hadamard gates, CNOTs, a barrier, and measurements to demonstrate different twirling strategies. ```python circuit = QuantumCircuit(5, 2) circuit.h(range(4)) circuit.cx(0, 1) circuit.cx(1, 2) circuit.cx(2, 3) circuit.cx(0, 1) circuit.cx(1, 2) circuit.cx(2, 3) circuit.barrier() circuit.h(range(4)) circuit.measure([1, 2], [0, 1]) circuit.draw("mpl", scale=0.6) ``` -------------------------------- ### Create a Circuit with a Barrier Source: https://github.com/qiskit/samplomatic/blob/main/docs/guides/transpiler.ipynb This snippet demonstrates how to construct a Qiskit `QuantumCircuit` that includes a barrier instruction. ```python circuit_with_barrier = QuantumCircuit(4) circuit_with_barrier.h(range(4)) circuit_with_barrier.cz(0, 1) circuit_with_barrier.barrier() circuit_with_barrier.cz(2, 3) circuit_with_barrier.measure_all() circuit_with_barrier.draw("mpl", scale=0.8) ``` -------------------------------- ### Run Pre-commit Hooks on All Files Source: https://github.com/qiskit/samplomatic/blob/main/CONTRIBUTING.md Optionally, test the pre-commit hooks on all files in the repository. ```bash pre-commit run --all-files ``` -------------------------------- ### Binding Pauli Lindblad Maps and Local Scales Source: https://github.com/qiskit/samplomatic/blob/main/docs/guides/samplex_io.ipynb Illustrates binding a Pauli Lindblad map and associated local scales to Samplex inputs. This example shows how shared free dimensions, like 'num_terms', are satisfied by consistent term counts in both specifications. ```python # both the PauliLindbladMap and the local scales imply 2 terms, so that the free dimension # 'num_terms_noise2' is satisfied inputs = samplex.inputs().bind( pauli_lindblad_maps={"ref2": PauliLindbladMap.from_list([("XXYZ", 0.1), ("IIXX", 0.2)])}, local_scales={"mod_ref2": [1, 2]}, ) print("All free dimensions:", inputs.free_dimensions) print("Current constraints:", inputs.bound_dimensions) ``` -------------------------------- ### Apply 'unique_instance' Tagging to Circuit Source: https://github.com/qiskit/samplomatic/blob/main/docs/guides/debug_tracing.ipynb Demonstrates how to apply 'unique_instance' tagging to a circuit, where each box receives a distinct tag reference. This is useful for differentiating boxes based on their position in the circuit. ```python from samplomatic.transpiler import generate_boxing_pass_manager base_circuit = QuantumCircuit(3) base_circuit.cx(0, 1) base_circuit.cx(1, 2) base_circuit.measure_all() # unique_instance: every box gets a distinct tag ref pm = generate_boxing_pass_manager(add_tags="unique_instance") boxed = pm.run(base_circuit) template, _ = build(boxed) print("unique_instance barrier labels:") for instr in template: if instr.operation.name == "barrier" and instr.operation.label: print(f" {instr.operation.label}") ``` -------------------------------- ### sample() Source: https://github.com/qiskit/samplomatic/blob/main/docs/api/auto/samplomatic.samplex.nodes.ChangeBasisNode.md Samples this node, drawing a specified number of randomizations. ```APIDOC ## sample(registers, rng, inputs, num_randomizations) ### Description Sample this node. ### Parameters * **registers** - Where to sample into. * **rng** - A randomness generator. * **inputs** - Inputs of the sampling program. * **num_randomizations** (int) - How many randomizations to draw. ### Method This is a method of the ChangeBasisNode class. ``` -------------------------------- ### pre_build Source: https://github.com/qiskit/samplomatic/blob/main/docs/api/samplomatic.builders.md Builds a template state and a pre-samplex for a given boxed-up circuit. This function is part of the builders module. ```APIDOC ## pre_build ### Description Build a template state and a pre-samplex for the given boxed-up circuit. ### Method Not specified (likely a Python function call) ### Parameters - **circuit** (type not specified) - Required - The boxed-up circuit to process. - **debug** (type not specified) - Optional - Debugging flag. ``` -------------------------------- ### sample Source: https://github.com/qiskit/samplomatic/blob/main/docs/api/auto/samplomatic.samplex.Samplex.md Samples a circuit by creating randomizations and evaluating nodes. It requires input values to be bound according to the circuit's input specifications. ```APIDOC ## sample ### Description Samples a circuit by creating randomizations and evaluating nodes. It requires input values to be bound according to the circuit's input specifications. ### Method N/A (This is a Python method call, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response Returns a SamplexOutput object containing the sampling results. #### Response Example N/A ``` -------------------------------- ### Local Testing with Samplex and Template Circuit Source: https://github.com/qiskit/samplomatic/blob/main/docs/guides/samplex_io.ipynb Binds input parameters to a Samplex and samples from it, then assigns the sampled parameter values to a template circuit for local inspection. This helps verify that the Samplex outputs are compatible with the template circuit. ```python inputs = samplex.inputs().bind( pauli_lindblad_maps={ "ref1": PauliLindbladMap.identity(2), "ref2": PauliLindbladMap.identity(4), }, basis_changes={"conclude": [0, 0, 0]}, parameter_values=np.linspace(0, 1, 4), ) outputs = samplex.sample(inputs, num_randomizations=3) bound_template = template.assign_parameters(outputs["parameter_values"][2]) bound_template.draw("mpl", fold=1000) ``` -------------------------------- ### instantiates() Source: https://github.com/qiskit/samplomatic/blob/main/docs/api/auto/samplomatic.samplex.nodes.ChangeBasisNode.md Returns a manifest of new virtual registers that this node instantiates. ```APIDOC ## instantiates() ### Description Return a manifest of new virtual registers that this node instantiates. ### NOTE * To change the type or size of a register, both instantiate and remove it. * Do not specify `reads_from()` or `writes_to()` for an instantiated register, these powers are implicit. ### Method This is a method of the ChangeBasisNode class. ``` -------------------------------- ### inputs Source: https://github.com/qiskit/samplomatic/blob/main/docs/api/auto/samplomatic.samplex.Samplex.md Returns an object that specifies and helps build the required inputs for the sample() method. ```APIDOC ## inputs() -> TensorInterface ### Description Return an object that specifies and helps build the required inputs of [`sample()`](#samplomatic.samplex.Samplex.sample). ### Method inputs ### Returns - **TensorInterface** - The input interface for this samplex. ``` -------------------------------- ### SamplexBuildError Source: https://github.com/qiskit/samplomatic/blob/main/docs/api/samplomatic.exceptions.md Error raised when building a samplex. ```APIDOC ## SamplexBuildError ### Description Error raised when building a samplex. ### Class `samplomatic.exceptions.SamplexBuildError` ``` -------------------------------- ### Generate Template Circuit with Barrier Labels Source: https://github.com/qiskit/samplomatic/blob/main/docs/guides/debug_tracing.ipynb Builds a template circuit from a tagged QuantumCircuit using Samplomatic's `build` function. The resulting template circuit's barriers will contain labels indicating their origin. ```python template, samplex = build(circuit) template.draw("mpl", fold=100) ``` -------------------------------- ### Inspect Samplex Outputs with Operator and Plotting Source: https://github.com/qiskit/samplomatic/blob/main/docs/guides/samplex_io.ipynb Unboxes a circuit, assigns sampled parameters, removes final measurements, converts it to an Operator, and plots the magnitudes of its unitary matrix representation. This allows for visual inspection of the circuit's behavior. ```python from samplomatic.utils import unbox # Operator requires that we unpack all of the boxes first unboxed = unbox(circuit).assign_parameters(inputs["parameter_values"]) # We want to plot unitary matrix amplitudes, so we need to remove the non-unitary measurements unboxed.remove_final_measurements() unboxed_unitary = Operator(unboxed) # Plot magnitudes of the unitary matrix represenation of the circuit plt.subplot(1, 4, 1) plt.imshow(np.abs(unboxed_unitary)) plt.title("Base Circuit") ``` -------------------------------- ### samplomatic.build Source: https://github.com/qiskit/samplomatic/blob/main/docs/api/auto/samplomatic.build.md Builds a circuit template and samplex for a given QuantumCircuit. This function is useful for preparing circuits for sampling and analysis. ```APIDOC ## samplomatic.build ### Description Build a circuit template and samplex for the given boxed-up circuit. ### Method `build` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **circuit** (QuantumCircuit) - The circuit to build. * **debug** (bool) - Optional - Whether to populate samplex nodes with information that traces them back to the boxes that generated them. Tracing information is based on `ref` attributes of box annotations. ### Returns * **tuple[QuantumCircuit, Samplex]** - The built template circuit and the corresponding samplex. ### Request Example ```python from qiskit import QuantumCircuit from samplomatic import build # Assuming 'qc' is a pre-defined QuantumCircuit object # qc = QuantumCircuit(...) template_circuit, samplex = build(qc, debug=True) ``` ### Response #### Success Response * **template_circuit** (QuantumCircuit) - The built template circuit. * **samplex** (Samplex) - The corresponding samplex object. #### Response Example ```json { "template_circuit": "", "samplex": "" } ``` ``` -------------------------------- ### outputs Source: https://github.com/qiskit/samplomatic/blob/main/docs/api/auto/samplomatic.samplex.Samplex.md Returns an object that specifies the promised outputs of the sample() method. ```APIDOC ## outputs() -> TensorInterface ### Description Return an object that specifies the promised outputs of [`sample()`](#samplomatic.samplex.Samplex.sample). ### Method outputs ### Returns - **TensorInterface** - The output interface for this samplex. ``` -------------------------------- ### instantiates Source: https://github.com/qiskit/samplomatic/blob/main/docs/api/auto/samplomatic.samplex.nodes.InjectNoiseNode.md Returns a manifest of new virtual registers that this node instantiates. This allows for dynamic creation of registers based on the node's requirements. ```APIDOC ## instantiates() ### Description Return a manifest of new virtual registers that this node instantiates. ### Returns dict[str, tuple[int, VirtualType]] - A dictionary mapping register names to their size and virtual type. ### NOTE * To change the type or size of a register, both instantiate and remove it. * Do not specify `reads_from()` or `writes_to()` for an instantiated register, these powers are implicit. ``` -------------------------------- ### Apply and Visualize Twirling Strategies Source: https://github.com/qiskit/samplomatic/blob/main/docs/guides/transpiler.ipynb Iterates through different `twirling_strategy` options ('active', 'active_accum', 'active_circuit', 'all'), applies the boxing pass manager, and draws the resulting transpiled circuits to visualize the effect on box qubit extension. ```python import matplotlib.pyplot as plt plt.figure(figsize=(9, 6)) for idx, strategy in enumerate(["active", "active_accum", "active_circuit", "all"]): ax = plt.subplot(2, 2, idx + 1) pm = generate_boxing_pass_manager(twirling_strategy=strategy, remove_barriers="never") transpiled_circuit = pm.run(circuit) fig = transpiled_circuit.draw("mpl", scale=0.8, ax=ax) ax.set_title(f"twirling_strategy='{strategy}'") plt.tight_layout() ``` -------------------------------- ### List Saved Benchmarks Source: https://github.com/qiskit/samplomatic/blob/main/CONTRIBUTING.md List all saved benchmark runs. ```bash pytest-benchmark list ``` -------------------------------- ### sample Method Source: https://github.com/qiskit/samplomatic/blob/main/docs/api/auto/samplomatic.distributions.UniformLocalC1.md Samples a specified number of elements from the UniformLocalC1 distribution using a provided random number generator. ```APIDOC ## sample(size, rng) ### Description Sample the distribution. ### Parameters * **size** (int) - Required - The number elements to sample. * **rng** (object) - Required - A randomness generator. ### Returns * **ndarray** - The samples. ``` -------------------------------- ### Integrate Boxing Pass Manager into Preset Pass Managers Source: https://github.com/qiskit/samplomatic/blob/main/docs/guides/transpiler.ipynb Demonstrates how to incorporate Samplomatic's `generate_boxing_pass_manager` into Qiskit's preset pass managers. The boxing manager is added as a post-scheduling step, ensuring it operates on the ISA circuit after barriers have been preserved. ```python from qiskit.transpiler import generate_preset_pass_manager preset_pass_manager = generate_preset_pass_manager( basis_gates=["rz", "sx", "cx"], coupling_map=[[0, 1], [1, 2]], optimization_level=0, ) boxing_pass_manager = generate_boxing_pass_manager() # Run the boxing pass manager after the scheduling stage preset_pass_manager.post_scheduling = boxing_pass_manager circuit = QuantumCircuit(3) circuit.h(0) circuit.cx(0, 1) circuit.cx(0, 2) circuit.measure_all() transpiled_circuit = preset_pass_manager.run(circuit) transpiled_circuit.draw("mpl", scale=0.8) ``` -------------------------------- ### Generate Template Circuit and Samplex Source: https://github.com/qiskit/samplomatic/blob/main/README.md Use the `build()` function from samplomatic to interpret annotated circuits and generate a template circuit and a samplex object. The samplex encodes randomization information. ```python template, samplex = build(circuit) template.draw("mpl", scale=0.5) ``` ```python samplex.draw() ``` -------------------------------- ### Build circuit from transpiled output Source: https://github.com/qiskit/samplomatic/blob/main/docs/guides/transpiler.ipynb Builds a template and samplex pair from a transpiled circuit. This function is used after applying boxing pass managers to prepare circuits for sampling. ```python from samplomatic import build boxing_pass_manager = generate_boxing_pass_manager( enable_gates=True, enable_measures=True, ) transpiled_circuit = boxing_pass_manager.run(circuit) template, samplex = build(transpiled_circuit) ``` -------------------------------- ### Sample Randomizations from Samplex Source: https://github.com/qiskit/samplomatic/blob/main/README.md Generate randomizations by calling `samplex.sample()`. Provide concrete values for circuit parameters and specify the number of randomizations. The output includes measurement bitflips if applicable. ```python # sample 15 randomizations valid against the template circuit, setting x=0.1 and y=0.2 samples = samplex.sample({"parameter_values": [0.1, 0.2]}, num_randomizations=15) # measurement bitflips are available samples["measurement_flips.meas"] # boolean array # one can, for example, bind the template circuit against the 7th randomization. template.assign_parameters(samples["parameter_values"][7]) ``` -------------------------------- ### RzSxSynth.make_template Source: https://github.com/qiskit/samplomatic/blob/main/docs/api/auto/samplomatic.synths.RzSxSynth.md Creates a parametric template that can be used to synthesize gates for the specified qubits and parameters. It yields instructions that implement the template. ```APIDOC ## RzSxSynth.make_template(qubits, params) ### Description Return a parametric template that can synthesize gates. ### Method N/A (Class Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **qubits** (object) - The qubits for which to make the template. * **params** (object) - The ordered parameters to use while making the template. ### Yields Instructions that implement the template. ### Raises * **SynthError** - When there is a problem synthesizing. ``` -------------------------------- ### UniformPauliSubset Constructor Source: https://github.com/qiskit/samplomatic/blob/main/docs/api/auto/samplomatic.distributions.UniformPauliSubset.md Initializes a UniformPauliSubset distribution. This distribution samples uniformly from a given subset of Paulis across a specified number of subsystems. The number of subsystems must be divisible by the length of each Pauli in the subset. ```APIDOC ## class samplomatic.distributions.UniformPauliSubset ### Description The uniform distribution over a subset of virtual Pauli gates. `paulis` is an array with elements corresponding to Paulis. The length of an individual Pauli should be a divisor of `num_subsystems`. The output `PauliRegister` is partitioned contiguously such that each part samples independently from `paulis`. ### Parameters * **num_subsystems** (int) - The number of subsystems this distribution samples. * **paulis** (ndarray) - The subset of Paulis to sample from. ### Raises * **ValueError** - If the number of subsystems is not divisible by the length of an element of `paulis`. ``` -------------------------------- ### Inspecting Free and Bound Dimensions Source: https://github.com/qiskit/samplomatic/blob/main/docs/guides/samplex_io.ipynb Shows how to inspect the free and currently bound dimensions of Samplex outputs after binding data. This is useful for understanding constraints on dynamic dimensions. ```python print("All free dimensions:", outputs.free_dimensions) print("Current constraints:", outputs.bound_dimensions) ``` -------------------------------- ### PreChangeBasis Constructor Source: https://github.com/qiskit/samplomatic/blob/main/docs/api/auto/samplomatic.pre_samplex.PreChangeBasis.md Initializes a PreChangeBasis object. This class is part of the samplex building process and defines how basis changes are handled. ```APIDOC ## Class: PreChangeBasis ### Description The basis emit node type used during samplex building. This class defines the configuration for basis changes. ### Parameters * **subsystems** ([Partition](samplomatic.partition.Partition.md#samplomatic.partition.Partition)[int]) - The subsystems that virtual gates act on. * **direction** ([Direction](samplomatic.constants.Direction.md#samplomatic.constants.Direction)) - The direction of virtual gates that can interact with this node. * **register_type** ([VirtualType](samplomatic.virtual_registers.VirtualType.md#samplomatic.virtual_registers.VirtualType)) - The virtual register type of the basis change. * **basis_ref** (str) - Unique identifier of this basis change. * **basis_change** (Literal['local_clifford', 'pauli_prepare', 'pauli_measure']) - What kind of basis change to use. * **trace_info** (TraceInfo | None, optional) - Debug trace information, populated when building with `debug=True`. Defaults to None. * **twirl_gate** (str | None, optional) - The gate name used for gate-dependent sampling, or `None`. Defaults to None. ``` -------------------------------- ### instantiates Source: https://github.com/qiskit/samplomatic/blob/main/docs/api/auto/samplomatic.samplex.nodes.ConversionNode.md Returns a manifest of new virtual registers that this ConversionNode instantiates. This is used to declare the output registers of the node. ```APIDOC ## instantiates() -> dict[str, tuple[int, VirtualType]] ### Description Return a manifest of new virtual registers that this node instantiates. ### NOTE * To change the type or size of a register, both instantiate and remove it. * Do not specify `reads_from()` or `writes_to()` for an instantiated register, these powers are implicit. ``` -------------------------------- ### CollectZ2ToOutputNode Constructor Source: https://github.com/qiskit/samplomatic/blob/main/docs/api/auto/samplomatic.samplex.nodes.CollectZ2ToOutputNode.md Initializes a CollectZ2ToOutputNode. This node reads from Z2Register and writes to SamplexOutput. ```APIDOC ## class samplomatic.samplex.nodes.CollectZ2ToOutputNode(register_name: str, subsystem_idxs: Sequence[int], output_name: str, output_idxs: Sequence[str]) ### Description Reads from [`Z2Register`](samplomatic.virtual_registers.Z2Register.md#samplomatic.virtual_registers.Z2Register)s and writes to [`SamplexOutput`](samplomatic.samplex.SamplexOutput.md#samplomatic.samplex.SamplexOutput). ### Parameters * **register_name** (str) - Required - The name of the register to read from. * **subsystem_idxs** (Sequence[int]) - Required - The subsystems to read from. * **output_name** (str) - Required - The name of the output to write to. * **output_idxs** (Sequence[str]) - Required - The indices of the output to write to. ``` -------------------------------- ### Samplex Methods Source: https://github.com/qiskit/samplomatic/blob/main/docs/api/auto/samplomatic.samplex.Samplex.md This section details the methods available for the Samplex class, allowing users to manipulate and sample from a graph. ```APIDOC ## add_edge ### Description Add an edge to the samplex graph. ### Method Not specified (assumed to be a method call within a Python context). ### Parameters - **a**: Type not specified - Description not specified. - **b**: Type not specified - Description not specified. ## add_input ### Description Add a sampling input to this samplex. ### Method Not specified (assumed to be a method call within a Python context). ### Parameters - **specification**: Type not specified - Description not specified. ## add_node ### Description Add a node to the samplex graph. ### Method Not specified (assumed to be a method call within a Python context). ### Parameters - **node**: Type not specified - Description not specified. ## add_output ### Description Add a sampling output to this samplex. ### Method Not specified (assumed to be a method call within a Python context). ### Parameters - **specification**: Type not specified - Description not specified. ## append_parameter_expression ### Description Add a parameter expression to the samplex. ### Method Not specified (assumed to be a method call within a Python context). ### Parameters - **expression**: Type not specified - Description not specified. ## draw ### Description Draw the graph in this samplex using the `plot_graph()` method. ### Method Not specified (assumed to be a method call within a Python context). ### Parameters - **cols**: Optional - Type not specified - Description not specified. - **subgraph_idxs**: Optional - Type not specified - Description not specified. - **layout_method**: Optional - Type not specified - Description not specified. ## finalize ### Description Signal that all nodes and edges have been added, and determine node traversal order. ### Method Not specified (assumed to be a method call within a Python context). ### Parameters None. ## inputs ### Description Return an object that specifies and helps build the required inputs of `sample()`. ### Method Not specified (assumed to be a method call within a Python context). ### Parameters None. ## outputs ### Description Return an object that specifies the promised outputs of `sample()`. ### Method Not specified (assumed to be a method call within a Python context). ### Parameters None. ## sample ### Description Sample. ### Method Not specified (assumed to be a method call within a Python context). ### Parameters - **samplex_input**: Optional - Type not specified - Description not specified. - **num_randomizations**: Optional - Type not specified - Description not specified. - **...**: Optional - Type not specified - Description not specified. ## set_passthrough_params ### Description Set the mapping for passthrough parameters. ### Method Not specified (assumed to be a method call within a Python context). ### Parameters - **passthrough_params**: Type not specified - Description not specified. ``` -------------------------------- ### Serialize and Deserialize Samplex Objects Source: https://github.com/qiskit/samplomatic/blob/main/docs/api/samplomatic.serialization.md Demonstrates saving a Samplex object to a JSON file or string, and loading it back. Requires importing `samplex_to_json` and `samplex_from_json`. ```python from samplomatic.serialization import samplex_to_json, samplex_from_json # save to a file samplex_to_json(samplex, filename="my_samplex.json") # or get a string json_str = samplex_to_json(samplex) # load from a string samplex = samplex_from_json(json_str) ``` -------------------------------- ### sample Source: https://github.com/qiskit/samplomatic/blob/main/docs/api/auto/samplomatic.samplex.nodes.InjectNoiseNode.md Samples this node, generating data based on the configured noise model and inputs. This is the core method for producing noise-infused samples. ```APIDOC ## sample(registers, rng, inputs, num_randomizations) ### Description Sample this node. ### Parameters * **registers** - Where to sample into. * **rng** - A randomness generator. * **inputs** - Inputs of the sampling program. * **num_randomizations** - How many randomizations to draw. ``` -------------------------------- ### sample Source: https://github.com/qiskit/samplomatic/blob/main/docs/api/auto/samplomatic.distributions.BalancedUniformPauli.md Samples the distribution a specified number of times using a provided random number generator. ```APIDOC ## BalancedUniformPauli.sample(size, rng) ### Description Sample the distribution. ### Parameters * **size** - Required - The number elements to sample. * **rng** - Required - A randomness generator. ### Returns The samples. ``` -------------------------------- ### SamplingNode.sample Source: https://github.com/qiskit/samplomatic/blob/main/docs/api/auto/samplomatic.samplex.nodes.SamplingNode.md Executes the sampling process for the node. This method takes registers, a random number generator, inputs, and the number of randomizations as arguments to produce samples. ```APIDOC ## sample ### Description Sample this node. ### Method POST ### Endpoint /sample ### Parameters #### Request Body - **registers** (dict[str, VirtualRegister]) - Required - Where to sample into. - **rng** (Generator) - Required - A randomness generator. - **inputs** (TensorInterface) - Required - Inputs of the sampling program. - **num_randomizations** (int) - Required - How many randomizations to draw. ``` -------------------------------- ### Transpile to ISA Circuit with Barriers Source: https://github.com/qiskit/samplomatic/blob/main/docs/guides/transpiler.ipynb Transpiles the logical Heisenberg circuit to an Intermediate Stage (ISA) form using a preset pass manager. This step assumes CX as the native entangler and demonstrates that barriers are preserved through the transpilation process. ```python from qiskit.transpiler import generate_preset_pass_manager preset_pm = generate_preset_pass_manager( basis_gates=["rz", "sx", "cx"], coupling_map=[[0, 1], [1, 2], [2, 3], [3, 4], [4, 0]], optimization_level=1, ) isa_circuit = preset_pm.run(heisenberg) isa_circuit.draw("mpl", scale=0.5, fold=200) ``` -------------------------------- ### Map Samplex Nodes to Template Parameters Source: https://github.com/qiskit/samplomatic/blob/main/docs/guides/debug_tracing.ipynb Iterate through samplex nodes to identify `CollectTemplateValues` nodes. These nodes link virtual registers to template parameters by storing index information, showing which virtual-gate subsystems drive which template parameters. ```python from samplomatic.samplex.nodes import CollectTemplateValues template, samplex = build(circuit, debug=True) for node in samplex.graph.nodes(): if isinstance(node, CollectTemplateValues): tags = node.trace_info.trace_refs.get("tag", set()) if node.trace_info else set() print(f"tags={tags} → template param indices: {node.template_idxs.tolist()}") ``` -------------------------------- ### AddNoopsAll.run Source: https://github.com/qiskit/samplomatic/blob/main/docs/api/auto/samplomatic.transpiler.passes.insert_noops.AddNoopsAll.md Runs the AddNoopsAll transpiler pass on a given DAGCircuit. This pass modifies boxes to span all qubits. ```APIDOC ## AddNoopsAll.run ### Description Runs the AddNoopsAll transpiler pass on a given DAGCircuit. This pass modifies boxes to span all qubits. ### Method `run` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response None #### Response Example None ``` -------------------------------- ### Enable Debug Tracing during Samplex Build Source: https://github.com/qiskit/samplomatic/blob/main/docs/guides/debug_tracing.ipynb Pass `debug=True` to the `build` function to attach trace information to every samplex node. This allows for detailed inspection of the build process. ```python template, samplex = build(circuit, debug=True) samplex.draw() ``` -------------------------------- ### UniformPauli Class Source: https://github.com/qiskit/samplomatic/blob/main/docs/api/auto/samplomatic.distributions.UniformPauli.md Initializes a UniformPauli distribution. This distribution samples virtual Pauli gates uniformly across the specified number of subsystems. ```APIDOC ## class samplomatic.distributions.UniformPauli(num_subsystems: int) ### Description The uniform distribution over virtual Pauli gates. ### Parameters * **num_subsystems** (int) - Required - The number of subsystems this distribution samples. ### Attributes * **register_type**: The virtual gate type being sampled. ### Methods * **sample(size, rng)**: Sample the distribution. * **Parameters**: * **size** (int) - Required - The number elements to sample. * **rng** (object) - Required - A randomness generator. * **Returns**: The samples. ```