=============== LIBRARY RULES =============== From library maintainers: - Choose the backend with the provider= argument of Circuit; the algorithm code does not change. - Backends other than the built-in numpy simulator need their pip extra, e.g. pip install "eigenkit[qiskit]". - CudaQuantumBackend and QiskitRuntimeBackend are opt-in: register them with eigenkit.register() before using their provider name. - On paid hardware, gradients are opt-in (enable_gradients=True in the device config); call dry_run_info() before submitting jobs. - Use interface="torch" to get a torch.nn.Module; the ready-made models follow scikit-learn's fit/predict. - Import the names in eigenkit.__all__ from eigenkit itself (from eigenkit import Circuit), and domain names from their package (eigenkit.optimization, eigenkit.chemistry). ### Setup: Import eigenkit components and create encoding, variational, observables Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/examples/basic-circuit.md Initializes the encoding, variational, and observables used throughout the example. The encoding uses RX rotations on 6 features, the variational block uses RY rotations with depth 2, and observables are all Z on 6 qubits. ```python import numpy as np from eigenkit import Circuit, Encoding, Variational, all_z encoding = Encoding(in_features=6, rotation="RX") variational = Variational(depth=2, rotation="RY") observables = all_z(6) ``` -------------------------------- ### Install CPU-only PyTorch and eigenkit[torch] Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/getting-started.md Install PyTorch from its own CPU index first, then eigenkit uses that PyTorch. For Linux CPU-only builds. ```bash pip install torch --index-url https://download.pytorch.org/whl/cpu ``` ```bash pip install "eigenkit[torch]" ``` -------------------------------- ### Install eigenkit extras (qiskit, braket, qml, torch, all) Source: https://github.com/eigenorbit/eigenkit/blob/main/README.md Installs optional extras for quantum SDK backends and machine learning frameworks. Each extra unlocks specific providers and features; 'all' includes every extra except 'perceval'. ```bash pip install "eigenkit[qiskit,braket]" ``` ```bash pip install "eigenkit[qml]" # torch-free kernel QML (QSVC/QSVR) ``` ```bash pip install "eigenkit[torch]" # differentiable hybrid models (HQNC/HQNR) ``` ```bash pip install "eigenkit[all]" ``` -------------------------------- ### Install eigenkit with Perceval extra Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/photonics.md Install the package with the 'perceval' extra to enable photonic simulation. Perceval is not included in the 'all' extra because it pins protobuf to an exact version; install explicitly, e.g., 'eigenkit[all,perceval]'. Importing eigenkit or eigenkit.photonics does not import Perceval; it is loaded only when creating or running a Perceval executor. ```bash pip install eigenkit[perceval] ``` -------------------------------- ### Report transpiled circuit resources with fake backends Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/qpu.md Use `Circuit.resources()` to get resource estimates for a circuit on its target after transpilation, without submitting anything. The example loops over a Qiskit Runtime config and an IQM config, both using fake backends, and prints key metrics. Set `seed_transpiler` to compare configurations fairly, as routing without a seed varies between runs. ```python from iqm.qiskit_iqm.fake_backends.fake_garnet import IQMFakeGarnet from qiskit_ibm_runtime.fake_provider import FakeFez from eigenkit import Circuit, IQMConfig, QiskitRuntimeConfig for config in ( QiskitRuntimeConfig( backend_instance=FakeFez(), primitive="sampler", optimization_level=3, seed_transpiler=0, ), IQMConfig(backend_instance=IQMFakeGarnet(), optimization_level=3, seed_transpiler=0), ): report = Circuit(blocks=..., provider=config).resources() print( report["n_2q_gates"], report["depth_2q"], report["routing_overhead_2q"], report["estimated_success_probability"], ) ``` -------------------------------- ### Install optional benchmark dependencies Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/benchmark.md Install the optional extra required for plotting, DataFrame export, and significance tests. ```bash pip install eigenkit[benchmark] ``` -------------------------------- ### QuantumKernel usage example Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/kernels.md Shows how to instantiate QuantumKernel with built-in and custom feature maps, and compute kernel matrices. The example uses numpy random data, creates a kernel with 'AngleCNOT' feature map, and demonstrates a custom feature map with a trainable weight. ```python import numpy as np from eigenkit import QuantumKernel rng = np.random.default_rng(0) X_train, X_test = rng.uniform(0, np.pi, (8, 4)), rng.uniform(0, np.pi, (3, 4)) qk = QuantumKernel(n_features=4, feature_map="AngleCNOT", reps=2) K_train = qk.compute_kernel_matrix(X_train) K_test = qk.compute_kernel_matrix(X_test, X_train) # A custom feature map with a trainable weight. def zz_map(qc, x, w): for q in range(len(x)): qc.ry(w[0], q) qc.h(q) qc.rz(x[q], q) qc.pauli_exponential([("Z", 0), ("Z", 1)], x[0]) trainable = QuantumKernel(n_features=2, feature_map=zz_map, n_weights=1) K = trainable.compute_kernel_matrix(X_train[:, :2], weights=[0.3]) ``` -------------------------------- ### Switch backends with provider argument Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/getting-started.md The provider argument accepts three shapes: a registered name string (default 'numpy'), a config dataclass (requires matching extra installed), or a Backend instance. Registering an instance with register() gives it a reusable name. ```python from eigenkit import Circuit, Encoding, Variational, PennyLaneConfig blocks = [Encoding(in_features=2), Variational(depth=1)] # 1. A registered name string ("numpy" is the default). Circuit(blocks=blocks, provider="numpy") # 2. A config dataclass — needs the matching extra installed. Circuit(blocks=blocks, provider=PennyLaneConfig(device_name="lightning.qubit")) # 3. A Backend instance (advanced) — used as it is. from eigenkit import NumpySimulator, register Circuit(blocks=blocks, provider=NumpySimulator()) # Registering an instance gives it a name you can reuse anywhere. register("numpy-copy", NumpySimulator()) Circuit(blocks=blocks, provider="numpy-copy") ``` -------------------------------- ### Add eigenkit to a uv-managed project Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/getting-started.md Add eigenkit as a dependency in a uv-managed project. Requires Python 3.12, 3.13, or 3.14. ```bash uv add eigenkit ``` -------------------------------- ### Choose a provider: PennyLaneConfig Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/examples/basic-circuit.md Creates a PennyLane provider configuration using the lightning.qubit device with no shots. Alternatively, you can pass a registered name string ('pennylane', 'qiskit', 'braket') or a backend instance. ```python from eigenkit import PennyLaneConfig config = PennyLaneConfig(device_name="lightning.qubit", shots=None) ``` -------------------------------- ### Example circuit drawing output Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/circuit-builder.md Example output of circuit.draw() showing RX gates for each qubit with negated angles for the adjoint part. ```text q_0: ──RX(x_0)──RX(-x_3)── q_1: ──RX(x_1)──RX(-x_4)── q_2: ──RX(x_2)──RX(-x_5)── ``` -------------------------------- ### Set GLIBC_TUNABLES for Linux ARM with PyTorch and Qiskit Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/getting-started.md Required before starting Python on Linux ARM when loading PyTorch, scikit-learn, CUDA-Q, and PennyLane Lightning together with Qiskit. Prevents 'cannot allocate memory in static TLS block' error. ```bash export GLIBC_TUNABLES=glibc.rtld.optional_static_tls=262144 ``` -------------------------------- ### Imports for Generic Estimators example Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/examples/generic-estimators.md Imports required for the example, including matplotlib, numpy, sklearn, torch, and eigenkit modules. ```python import matplotlib import matplotlib.pyplot as plt import numpy as np from sklearn.model_selection import train_test_split import torch from torch import nn from eigenkit import GenericClassifier, GenericRegressor from eigenkit.datasets import STYLE_COLORS, load_dataset, rc_params from eigenkit import Basic, Reupload ``` -------------------------------- ### Build the same circuit gate by gate with CircuitBuilder Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/getting-started.md Constructs a circuit manually using CircuitBuilder, adding symbolic weights and inputs, then applying RX, RY, and CNOT gates. The build() method produces a CircuitSpec that can be executed by Circuit. The resulting circuit is equivalent to the predefined-block version, as verified by comparing specs. ```python from eigenkit import CircuitBuilder qc = CircuitBuilder(n_qubits=4) params = qc.add_weights(8) features = qc.add_inputs(4) # Encoding(in_features=4, rotation="RX"): one RX per input. for q in range(4): qc.rx(features[q], qubit=q) # Variational(depth=2, rotation="RY"): per layer, an RY on every qubit, # then a chain of CNOTs. for layer in range(2): for q in range(4): qc.ry(params[layer * 4 + q], qubit=q) for q in range(3): qc.cnot(q, q + 1) by_hand = Circuit(qc.build(), observables=all_z(4)) print(by_hand.spec == circuit.spec) # True - the very same circuit print(by_hand.draw()) ``` ```text q_0: ──RX(x_0)──RY(w_0)──●──RY(w_4)──────────────●─────────── │ │ q_1: ──RX(x_1)──RY(w_1)──X─────●─────RY(w_5)─────X─────●───── │ │ q_2: ──RX(x_2)──RY(w_2)────────X────────●─────RY(w_6)──X──●── │ │ q_3: ──RX(x_3)──RY(w_3)─────────────────X─────RY(w_7)─────X── ``` -------------------------------- ### Prompt Context7 with eigenkit library Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/use-with-ai.md Example prompt for a coding assistant using Context7 to train an HQNC classifier on the moons dataset with eigenkit. ```text Train an HQNC classifier on the moons dataset with eigenkit. use library /eigenorbit/eigenkit ``` -------------------------------- ### Install eigenkit with pip Source: https://github.com/eigenorbit/eigenkit/blob/main/README.md Installs the core eigenkit package with the built-in numpy simulator and framework-free optimization and chemistry domains. Requires Python 3.12, 3.13, or 3.14. ```bash pip install eigenkit ``` -------------------------------- ### Output of moons dataset split Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/examples/generic-estimators.md Expected output showing dataset shapes and class labels. ```text Train: (128, 2), Validation: (32, 2), Test: (40, 2) Classes: [0 1] ``` -------------------------------- ### Build and run a Circuit with Encoding and Variational blocks Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/getting-started.md Creates a circuit from predefined blocks (Encoding and Variational) and measures Z on all qubits. Runs on the numpy interface and simulator by default; weights are passed at call time. The qubit count is inferred from Encoding.in_features, and the output dimension equals the number of observables. ```python import numpy as np from eigenkit import Circuit, Encoding, Variational, all_z # 1. Define blocks. Encoding maps classical features to rotations; # Variational adds depth * n_qubits trainable parameters. # 2. Choose what to measure — all_z(4) measures Z on every qubit. circuit = Circuit( blocks=[Encoding(in_features=4, rotation="RX"), Variational(depth=2, rotation="RY")], observables=all_z(4), ) # 3. Run: pass weights and inputs explicitly. weights = np.zeros(circuit.spec.n_weights) x = np.array([0.1, 0.2, 0.3, 0.4]) y = circuit(weights, x) print(y.shape) # (4,) ``` -------------------------------- ### Load and split moons dataset Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/examples/generic-estimators.md Loads the moons dataset and splits into training, validation, and test sets. Prints shapes and class labels. ```python data = load_dataset("moons") X_train, y_train = data["X_train"], data["y_train"] X_test, y_test = data["X_test"], data["y_test"] X_fit, X_val, y_fit, y_val = train_test_split( X_train, y_train, test_size=0.2, stratify=y_train, random_state=42, ) print(f"Train: {X_fit.shape}, Validation: {X_val.shape}, Test: {X_test.shape}") print(f"Classes: {np.unique(y_train)}") ``` -------------------------------- ### Circuit usage example Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/interfaces.md Shows how to instantiate a Circuit with Encoding and Variational blocks, pass weights at call time, and compute gradients without PyTorch using the jacobian method. ```python import numpy as np from eigenkit import Circuit, Encoding, Variational, all_z circuit = Circuit( blocks=[Encoding(in_features=2), Variational(depth=1)], observables=all_z(2), ) # The circuit stores no weights, so you pass them at every call. weights = np.zeros(circuit.spec.n_weights) values = circuit(weights, np.array([0.1, 0.2])) # Gradients, without PyTorch. grad = circuit.jacobian(weights, np.array([0.1, 0.2])) ``` -------------------------------- ### Save and load GenericRegressor with architecture rebuild Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/examples/generic-estimators.md Call save() after training and pass the architecture again when loading. The bundle stores weights and training metadata but not the architecture, so you must rebuild the model structure before load(). The example verifies predictions match and prints the loaded model's R². ```python reg.save("reg_hybrid.eigenkit") # Rebuild the architecture (same structure, fresh weights) reg_net_fresh = nn.Sequential( nn.Linear(IN_FEATURES_R, N_QUBITS_R), nn.ReLU(), Basic(n_qubits=N_QUBITS_R, depth=3, variational_type="strong"), nn.Linear(N_QUBITS_R, 1), ) reg_loaded = GenericRegressor.load("reg_hybrid.eigenkit", model=reg_net_fresh) np.testing.assert_allclose( reg_loaded.predict(X_test_r), reg.predict(X_test_r), atol=1e-5, ) print(f"Loaded model R²: {reg_loaded.score(X_test_r, y_test_r):.3f}") ``` ```text Loaded model R²: 0.489 ``` -------------------------------- ### Import libraries for HQNR example Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/examples/cement-hqnr.md Imports required libraries including eigenkit's HQNR, dataset utilities, and plotting tools. ```python from pathlib import Path import matplotlib import matplotlib.pyplot as plt import numpy as np from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score from eigenkit import HQNR from eigenkit.datasets import load_dataset, rc_params ``` -------------------------------- ### Example .eigenkit bundle layout for HQNC Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/model-persistence.md Lists the files in a typical HQNC bundle. The state directory contains JSON scalars/lists and a PyTorch weights file. ```text metadata.json params.json state/label_classes.json state/n_classes.json state/train_losses.json state/validation_losses.json state/weights.pt ``` -------------------------------- ### Imperative construction with CircuitBuilder Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/examples/basic-circuit.md Builds a circuit gate-by-gate using CircuitBuilder, adding weights and inputs, then encoding with RY gates, two variational layers with a CNOT ladder. qc.build() returns a CircuitSpec passed directly to Circuit. For a sub-circuit, use qc.to_block() instead. ```python from eigenkit import Circuit, CircuitBuilder, all_z qc = CircuitBuilder(n_qubits=4) weights = qc.add_weights(8) inputs = qc.add_inputs(4) # Encoding. for q in range(4): qc.ry(inputs[q], qubit=q) # Two variational layers + CNOT ladder. for d in range(2): for q in range(4): qc.ry(weights[d * 4 + q], qubit=q) for q in range(3): qc.cnot(q, q + 1) spec = qc.build() circuit = Circuit(blocks=spec, observables=all_z(4)) ``` -------------------------------- ### Example: building and calling a NumPy circuit Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/interfaces.md Builds a NumPy circuit with an encoding and variational layer, then calls it with random input data. The weights are initialized to zeros and the circuit returns measurement values for each qubit. ```python import numpy as np from eigenkit import Circuit, Encoding, Variational, all_z circuit = Circuit( blocks=[Encoding(in_features=4), Variational(depth=2)], observables=all_z(4), ) weights = np.zeros(circuit.spec.n_weights) values = circuit(weights, np.random.uniform(0, np.pi, size=4)) ``` -------------------------------- ### HQNC clone training output Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/examples/algorithms-classification.md Example output from fitting the cloned HQNC model, showing the training log and the model's string representation. ```text HQNC training | Epoch 1/20 | loss=0.543862 | elapsed=0.0s | eta=0.5s ... HQNC training | Epoch 20/20 | loss=0.338438 | elapsed=0.6s | eta=0.0s HQNC(epochs=20, in_features=2, in_quantum=2) ``` -------------------------------- ### CircuitBuilder usage example Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/circuit-builder.md Builds a 3-qubit circuit with 6 trainable weights and 3 input features, applying RY rotations and CNOT gates, then returns an immutable CircuitSpec. ```python qc = CircuitBuilder(n_qubits=3) weights = qc.add_weights(6) inputs = qc.add_inputs(3) for qubit in range(3): qc.ry(inputs[qubit], qubit=qubit) for depth in range(2): for qubit in range(3): qc.ry(weights[depth * 3 + qubit], qubit=qubit) for qubit in range(2): qc.cnot(qubit, qubit + 1) spec = qc.build() ``` -------------------------------- ### Compare multiple models with compare() Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/benchmark.md Trains quantum and classical SVC models on the iris dataset with one seed, returning a BenchmarkResult. The example prints the fitted model names, showing the order matches the input dict. ```python from sklearn.svm import SVC from eigenkit.qml import QSVC from eigenkit.benchmark import compare results = compare( models={ "Quantum SVC": QSVC( feature_map="Angle", reps=1, probability=True ), "Regularized SVC": SVC(C=0.3), "Flexible SVC": SVC(C=3.0), }, dataset="iris", metrics=["accuracy"], n_seeds=1, ) print(list(results.fitted_models)) # ['Quantum SVC', 'Regularized SVC', 'Flexible SVC'] ``` -------------------------------- ### Build hybrid classification model Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/examples/generic-estimators.md Constructs a hybrid quantum-classical model using nn.Sequential with a Basic quantum layer. The linear layers must match the qubit count. ```python N_QUBITS = 5 N_CLASSES = 2 torch.manual_seed(42) quantum_layer = Basic(n_qubits=N_QUBITS, depth=3, variational_type="strong") clf_net = nn.Sequential( nn.Linear(2, N_QUBITS), # expand features to qubit count nn.ReLU(), quantum_layer, # (batch, N_QUBITS) -> (batch, N_QUBITS) expectation values nn.Linear(N_QUBITS, N_CLASSES), ) print(clf_net) ``` -------------------------------- ### Example .eigenkit bundle layout for QSVC Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/model-persistence.md Lists the files in a typical QSVC bundle. The fitted scikit-learn SVC is stored as a uint8 array in state/svc_skops.npy; with probability=True, a calibrated_skops.npy is also present. ```text metadata.json params.json state/X_train.npy state/svc_skops.npy # the fitted sklearn SVC, serialised with skops state/calibrated_skops.npy # only with probability=True: the fitted calibration ``` -------------------------------- ### Train on simulator, deploy on QPU with BraketConfig Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/qpu.md Use this workflow to avoid expensive parameter-shift gradients on QPU calls. Train on a simulator, save weights with torch.save, then build the same circuit with a QPU provider and load the weights for inference. ```python # Train. sim_circuit = Circuit(blocks=blocks, interface="torch") # ... training loop ... torch.save(sim_circuit.state_dict(), "weights.pt") # Deploy. qpu_circuit = Circuit( blocks=blocks, provider=BraketConfig(device_arn=..., shots=1000), interface="torch", ) qpu_circuit.load_state_dict(torch.load("weights.pt")) y = qpu_circuit(x_test) ``` -------------------------------- ### ImportError message for missing provider package Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/providers.md Example error message shown when naming a backend whose package is not installed. The name stays registered, so once the extra is installed, the same process finds it without a restart. ```text ImportError: provider 'pennylane' is registered but its package is not installed (install with `pip install eigenkit[pennylane]`). ``` -------------------------------- ### sample() Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/qpu.md Executes the quantum circuit on the IQM backend and returns measurement samples as bitstrings. This method is fully supported and requires shots > 0. ```APIDOC ## sample() ### Description Executes the quantum circuit on the IQM backend and returns measurement samples as bitstrings. This method is fully supported and requires shots > 0. ### Method sample ### Parameters None explicitly documented. ### Response #### Success Response - **samples** (list of bitstrings) - The measurement outcomes from the circuit execution. ``` -------------------------------- ### Variational ground-state loop with minimize_expectation Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/getting-started.md Plugs a NumPy circuit into the scipy-based variational spine. Variational alone declares a single wire, and minimize_expectation takes exactly one observable (the Hamiltonian). Starts from a random point to avoid the symmetric saddle at all-zeros where gradients vanish. ```python import numpy as np from eigenkit import Circuit, Variational, Z, minimize_expectation # Variational alone declares a single wire, and minimize_expectation takes # exactly one observable — the Hamiltonian. circuit = Circuit([Variational(depth=2, rotation="RY")], observables=Z(0)) # Start from a small random point — an all-zeros init sits on a symmetric # saddle where many gradients vanish, which stalls gradient-based optimizers. rng = np.random.default_rng(0) x0 = rng.uniform(0, 2 * np.pi, size=circuit.spec.n_weights) result = minimize_expectation(circuit, initial_parameters=x0) print(result.optimal_value) ``` -------------------------------- ### Adding trainable feature scaling with Reuploading Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/examples/basic-circuit.md Replaces the separate Encoding and Variational blocks with a Reuploading block that repeats the encoding and can give each pair of layer and feature a trainable scale. Uses depth 3, RY rotations for both encoding and variational, and trainable_scale=True. ```python from eigenkit import Reuploading reuploading = Reuploading( in_features=6, depth=3, encoding_rotation="RY", variational_rotation="RY", trainable_scale=True, ) circuit = Circuit(blocks=[reuploading], observables=all_z(6)) ``` -------------------------------- ### Build Hybrid Regression Model with Basic Quantum Layer Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/examples/generic-estimators.md Constructs a hybrid model: a classical linear encoder, a Basic quantum variational layer, and a linear regression head. The final layer outputs shape (batch,) or (batch, 1) as required by GenericRegressor. ```python N_QUBITS_R = 6 IN_FEATURES_R = X_train_r.shape[1] # 10 torch.manual_seed(42) quantum_layer_r = Basic(n_qubits=N_QUBITS_R, depth=3, variational_type="strong") reg_net = nn.Sequential( nn.Linear(IN_FEATURES_R, N_QUBITS_R), nn.ReLU(), quantum_layer_r, nn.Linear(N_QUBITS_R, 1), ) print(reg_net) ``` ```text Sequential( (0): Linear(in_features=10, out_features=6, bias=True) (1): ReLU() (2): Basic( (circuit): TorchCircuit() ) (3): Linear(in_features=6, out_features=1, bias=True) ) ``` -------------------------------- ### Create pyramid topology and identity matrix with eigenkit.orthogonal Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/orthogonal.md Use pyramid(4) to build a pyramid topology for 4 wires, then orthogonal_matrix with identity_angles to get the 4x4 identity matrix. This example is from the API reference for the framework-free NumPy core. ```python from eigenkit.orthogonal import identity_angles, orthogonal_matrix, pyramid t = pyramid(4) orthogonal_matrix(t, identity_angles(t)) # the 4 x 4 identity ``` -------------------------------- ### Enable hardware gradients with IQMConfig and enable_gradients=True Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/qpu.md Set enable_gradients=True in the device configuration to train or fine-tune on the device. The backend reports gradient_method="parameter_shift", and .backward() runs the parameter-shift rule on hardware, costing at least 2 * n_weights forward calls. Compiling for a paid device issues a second CostWarning. ```python qpu_circuit = Circuit( blocks=blocks, provider=IQMConfig( url="https://resonance.iqm.tech/", shots=2000, enable_gradients=True, ), interface="torch", ) loss = qpu_circuit(x).sum() loss.backward() # 2 * n_weights forward calls on the device ``` -------------------------------- ### Create a differentiable PyTorch circuit with interface='torch' Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/getting-started.md Sets interface='torch' to create a torch.nn.Module with trainable parameters as nn.Parameter objects. Supports batched inputs and backpropagation. Requires optional torch dependencies and runs on the built-in NumPy simulator. ```python import torch from eigenkit import Circuit, Encoding, Variational, all_z circuit = Circuit( blocks=[Encoding(in_features=4, rotation="RX"), Variational(depth=2)], observables=all_z(4), interface="torch", ) y = circuit(torch.randn(3, 4)) # batch=3, features=4 -> torch.Size([3, 4]) ``` -------------------------------- ### Configure QAOA solver with IQM hardware Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/qpu.md Sets up a QAOA solver for hardware execution using IQMConfig and COBYLA optimizer. Hardware backends declare gradient_method="none" unless enable_gradients=True; optimizer="spsa" is also accepted. ```python from eigenkit.optimization import QAOA from eigenkit import IQMConfig solver = QAOA( layers=1, provider=IQMConfig(url="https://resonance.iqm.tech/", shots=4000), optimizer="COBYLA", ) ``` -------------------------------- ### sample() Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/qpu.md Reads the measurement counts of the task. Requires shots > 0 on all devices, and QPUs need a number of shots within the device range. ```APIDOC ## sample() ### Description Reads the measurement counts of the task. Requires shots > 0 on all devices, and QPUs need a number of shots within the device range. ### Method sample ### Parameters #### Query Parameters - **shots** (integer) - Required - Number of shots; must be > 0 on all devices. ### Response #### Success Response - **counts** (dict) - Measurement counts of the task. ### Notes - Qubit 0 is the most significant bit over the whole circuit; a qubit that no gate acts on reads 0. - No limit on the number of qubits. ``` -------------------------------- ### Register and use Qulacs backend Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/providers.md Registers the Qulacs backend and creates a circuit with the 'qulacs' provider. The backend auto-registers when the extra is installed. Supports native adjoint gradients via `ParametricQuantumCircuit.backprop`, with `gradient_method="adjoint"`. Install with `pip install eigenkit[qulacs]`. ```python from eigenkit import Circuit, QulacsConfig, QulacsBackend, register register("qulacs", QulacsBackend()) # auto-registers when the extra is installed Circuit(blocks=..., provider="qulacs") # or provider=QulacsConfig() ``` -------------------------------- ### Run circuit on hardware with device configs Source: https://github.com/eigenorbit/eigenkit/blob/main/README.md Runs the same circuit on IBM Quantum and IQM Resonance hardware using device configs. Requires accounts for those services; compiling for a paid device emits a CostWarning. ```python from eigenkit import IQMConfig, QiskitRuntimeConfig devices = { "IBM Heron": QiskitRuntimeConfig( backend_name="ibm_kingston", shots=8192, primitive="sampler" ), "IQM Emerald": IQMConfig(quantum_computer="emerald", shots=8192), } for name, device in devices.items(): circuit = Circuit(spec, observables=observables, provider=device) print(name, circuit([])) ``` -------------------------------- ### Build and run circuit with weights and inputs Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/examples/basic-circuit.md Builds a circuit from the encoding and variational blocks with the chosen provider, then runs it on a batch of 3 samples. The numpy interface (default) takes weights per call; output has one expectation value per qubit. The printed shape is (3, 6). ```python circuit = Circuit( blocks=[encoding, variational], observables=observables, provider=config, ) # 6 qubits, 6 features. The numpy interface (default) takes weights per call; # output has one expectation value per qubit. weights = np.zeros(circuit.spec.n_weights) # or a trained vector inputs = np.random.uniform(0, np.pi, size=(3, 6)) # batch of 3 samples outputs = circuit(weights, inputs) print(outputs.shape) ``` ```text (3, 6) ``` -------------------------------- ### QiskitRuntimeConfig.make_backend Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/providers.md Builds the backend that this configuration describes. ```APIDOC ## QiskitRuntimeConfig.make_backend ### Description Builds the backend that this configuration describes. ### Method make_backend ### Signature ```python def QiskitRuntimeConfig.make_backend(self) -> 'QiskitRuntimeBackend' ``` ### Returns - **QiskitRuntimeBackend** - The backend instance. ``` -------------------------------- ### Run IQP circuit on multiple simulators Source: https://github.com/eigenorbit/eigenkit/blob/main/README.md Builds an IQP circuit with a helper function and runs it on three simulators: numpy, qulacs, and qiskit-aer. The qulacs and qiskit-aer providers require the corresponding extras. ```python from eigenkit import Circuit, CircuitBuilder, Z def iqp(n, edges, angles): """H on every qubit, a ZZ rotation per edge, H on every qubit.""" qc = CircuitBuilder(n_qubits=n) for q in range(n): qc.h(q) for (i, j), angle in zip(edges, angles): qc.pauli_exponential((("Z", i), ("Z", j)), angle) for q in range(n): qc.h(q) return qc.build() spec = iqp(4, [(0, 1), (1, 2), (2, 3), (3, 0)], [0.7, 1.1, 0.4, 1.9]) observables = [Z(0) * Z(1), Z(1) * Z(2), Z(0) * Z(1) * Z(2) * Z(3)] for provider in ["numpy", "qulacs", "qiskit-aer"]: circuit = Circuit(spec, observables=observables, provider=provider) print(provider, circuit([])) ``` ```text numpy [0.46548538 0.11841725 1. ] qulacs [0.46548538 0.11841725 1. ] qiskit-aer [0.46548538 0.11841725 1. ] ``` -------------------------------- ### Using provider= with string, config, or backend instance Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/providers.md Shows the three accepted forms for the provider= argument: a registered name string, a configuration dataclass, or a backend instance. Also demonstrates registering a backend under a name with register() and then using that name. The same circuit can run on any backend without changes. ```python from eigenkit import Circuit, PennyLaneConfig # String: registered name lookup. Circuit(blocks=..., provider="pennylane") # Config: routes to the matching backend via `make_backend()`. Circuit(blocks=..., provider=PennyLaneConfig(device_name="lightning.qubit")) # Backend instance: used directly. from eigenkit import CudaQuantumBackend, register Circuit(blocks=..., provider=CudaQuantumBackend()) # Or register it once under a name, then use the name anywhere. register("cudaq", CudaQuantumBackend()) Circuit(blocks=..., provider="cudaq") ``` -------------------------------- ### Run circuit on QPU and wait for result Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/qpu.md Circuit(...)(x) works on QPU backends like simulators but blocks until the job finishes. Requires shots > 0 and sets gradient_method="none" unless enable_gradients=True. ```python from eigenkit import Circuit, BraketConfig config = BraketConfig( device_arn="arn:aws:braket:us-east-1::device/qpu/ionq/Aria-1", shots=1000, ) circuit = Circuit(blocks=..., provider=config, interface="torch") y = circuit(x) # blocks until the QPU returns ``` -------------------------------- ### align_kernel usage example Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/kernels.md Example of using align_kernel with a custom feature map and QSVC. Creates a QuantumKernel with one trainable weight, aligns it on synthetic data, then fits a QSVC model. ```python import numpy as np from eigenkit import QSVC, QuantumKernel, align_kernel def my_map(qc, x, w): for q in range(len(x)): qc.ry(w[0], q) qc.rz(x[q], q) rng = np.random.default_rng(0) X_train = rng.uniform(0, np.pi, (8, 2)) y_train = np.array([0, 1] * 4) kernel = QuantumKernel(n_features=2, feature_map=my_map, n_weights=1) result = align_kernel(kernel, X_train, y_train, maxiter=20) model = QSVC(kernel=result.kernel).fit(X_train, y_train) ``` -------------------------------- ### QSVR usage example Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/qml.md Example of using QSVR to fit and predict on synthetic data. It creates a random dataset, fits the model with feature_map='Angle' and reps=1, then predicts on test data. ```python import numpy as np from eigenkit import QSVR rng = np.random.default_rng(0) X_train, X_test = rng.uniform(0, np.pi, (8, 2)), rng.uniform(0, np.pi, (3, 2)) y_train = np.sin(X_train).sum(axis=1) model = QSVR(feature_map="Angle", reps=1) model.fit(X_train, y_train) predictions = model.predict(X_test) ``` -------------------------------- ### IQMConfig.make_backend Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/providers.md Builds the backend that this configuration describes. ```APIDOC ## IQMConfig.make_backend ### Description Builds the backend that this configuration describes. ### Method make_backend ### Signature ```python def IQMConfig.make_backend(self) -> 'IQMBackend' ``` ### Returns - **IQMBackend** - The backend instance. ``` -------------------------------- ### Run circuit on Quandela Cloud with QuandelaCloudBackend Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/photonics.md Use QuandelaCloudBackend to run a photonic circuit on Quandela Cloud (QPU or cloud simulator). Results are sampled counts, so gradients are unavailable. The backend issues a CostWarning on first submission; submit() returns a handle with .result() and .status() without waiting, and dry_run_info() works offline. The access token is read from token=, then $QUANDELA_TOKEN or $PERCEVAL_TOKEN, then Perceval's saved token; it is never written in code. run and result() wait at most poll_timeout_seconds (default 3600) and raise an error if the job fails or if post-selection discards every shot. ```python import numpy as np from eigenkit.photonics import QuandelaCloudBackend backend = QuandelaCloudBackend("qpu:ascella", shots=20000) # token from $QUANDELA_TOKEN compiled = backend.compile(spec) # `spec` and `weights` from the reservoir example above print(compiled.dry_run_info()) # inspect offline, before submitting handle = compiled.submit(weights, np.zeros(spec.n_inputs)) print(handle.status()) dist = handle.result() # blocks until the cloud job completes ``` -------------------------------- ### Import libraries for HQNC circles example Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/examples/circles-hqnc.md Imports NumPy, Matplotlib, scikit-learn metrics, and eigenkit components (STYLE_COLORS, load_dataset, rc_params, HQNC) needed for the circles classification example. ```python import numpy as np import matplotlib import matplotlib.pyplot as plt from sklearn.metrics import accuracy_score, classification_report, f1_score from eigenkit.datasets import STYLE_COLORS, load_dataset, rc_params from eigenkit import HQNC ``` -------------------------------- ### QuantumKernel with default and Pennylane providers Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/kernels.md Shows how to instantiate a QuantumKernel with the default 'numpy' provider (no extra dependencies) and with the 'pennylane' provider. The provider argument defaults to 'numpy', and any registered provider can be used once its extra is installed. Results agree to machine precision across NumPy, PennyLane, Qiskit, and Braket. ```python # The default: no extra dependencies. qk = QuantumKernel(n_features=4, feature_map="Angle", reps=1) # Any other registered provider works the same way, once its extra is # installed: qk = QuantumKernel(n_features=4, feature_map="Angle", reps=1, provider="pennylane") ``` -------------------------------- ### eigenkit.optimization.qaoa_ansatz Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/optimization.md Builds the standard QAOA circuit. ```APIDOC ## `eigenkit.optimization.qaoa_ansatz` ### Description Build the standard QAOA circuit. ### Function `def qaoa_ansatz(hamiltonian: Observable, num_qubits: int, layers: int) -> CircuitSpec` ### Parameters - **hamiltonian** (Observable) - Required - The Hamiltonian observable. - **num_qubits** (int) - Required - The number of qubits. - **layers** (int) - Required - The number of layers. ### Returns - **CircuitSpec** - The circuit specification. ``` -------------------------------- ### Compute Fock-basis observables with FockProbability and PhotonNumber Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/photonics.md Use compiled.expectation with PhotonNumber(mode=0) to get the expected photon number in mode 0, or FockProbability(target=(2,0)) to get the probability of detecting exactly |2,0>. The FockProbability target must hold as many photons as the input state because linear optics conserves photon number. ```python from eigenkit.photonics import FockProbability, PhotonNumber w, x = np.array([]), np.array([]) # the circuit above has no weights and no inputs compiled.expectation(w, x, PhotonNumber(mode=0)) # , expected photons in mode 0 compiled.expectation(w, x, FockProbability(target=(2, 0))) # P(detect exactly |2,0>) ``` -------------------------------- ### Configure IQM backend with IQMConfig Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/qpu.md Creates an IQMConfig for connecting to an IQM quantum computer. The token is resolved from an explicit token, the IQM_TOKEN environment variable, or iqm-client's own discovery; the server address can be overridden with IQM_SERVER_URL. The service returns only counts, so shots must be greater than 0 and expectation values are computed from bitstring histograms. ```python from eigenkit import IQMConfig config = IQMConfig( url="https://resonance.iqm.tech/", quantum_computer="garnet", # omit to take the server's default shots=2048, ) ``` -------------------------------- ### QSVC usage example Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/qml.md Example showing how to instantiate and use QSVC with a feature map and with a custom kernel. The first model uses feature_map="AngleCNOT" and reps=2, then fits and predicts. The second model uses a custom kernel built from Encoding and Variational layers. ```python import numpy as np from eigenkit import QSVC, Encoding, QuantumKernel, Variational rng = np.random.default_rng(0) X_train, X_test = rng.uniform(0, np.pi, (8, 4)), rng.uniform(0, np.pi, (3, 4)) y_train = np.array([0, 1] * 4) model = QSVC(feature_map="AngleCNOT", reps=2) model.fit(X_train, y_train) predictions = model.predict(X_test) # Any kernel works, including custom and trained ones. my_map = [Encoding(in_features=4), Variational(depth=1)] model = QSVC(kernel=QuantumKernel(n_features=4, feature_map=my_map)) ``` -------------------------------- ### eigenkit.core.provider.registered_names Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/providers.md Returns every provider name that `get` accepts, including lazy ones. ```APIDOC ## `eigenkit.core.provider.registered_names` ### Description Returns every provider name that `get` accepts, including lazy ones. ### Signature ```python def registered_names() -> list[str] ``` ### Returns - **list[str]** - List of registered provider names. ``` -------------------------------- ### quick_baselines() function signature Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/benchmark.md Returns a list of common scikit-learn classifiers with sensible defaults. ```python def quick_baselines() -> list[Any] ``` -------------------------------- ### QuantumReservoirRegressor usage example Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/user-guide/qml.md Fits a quantum reservoir regressor on a batch of sequences. X has shape (n_sequences, n_timesteps, n_features) and y has shape (n_sequences, n_timesteps). The reservoir circuit is frozen and only the linear readout is trained. The example uses a leaky state policy with leak=0.5 for fading memory and washout=5. The output shape of predict is (40, 50). ```python import numpy as np from eigenkit import Encoding, Variational from eigenkit import QuantumReservoirRegressor rng = np.random.default_rng(0) X = rng.uniform(-1, 1, size=(40, 50, 3)) y = np.zeros((40, 50)) y[:, 1:] = X[:, :-1, 0] # predict the previous step's first channel reservoir = QuantumReservoirRegressor( blocks=[Encoding(in_features=3, rotation="RY"), Variational(depth=3, rotation="RY")], state_policy="leaky", leak=0.5, # fading memory features="probabilities", washout=5, ) reservoir.fit(X, y) print(reservoir.predict(X).shape) # (40, 50) ``` -------------------------------- ### Output of GenericClassifier training Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/examples/generic-estimators.md Expected output showing training progress and final test accuracy. ```text GenericClassifier training | Epoch 1/150 | loss=0.668630 | val_loss=0.624434 | elapsed=0.2s | eta=32.6s GenericClassifier training | Epoch 2/150 | loss=0.583259 | val_loss=0.552643 | elapsed=0.4s | eta=33.1s GenericClassifier training | Epoch 3/150 | loss=0.512898 | val_loss=0.487117 | elapsed=0.7s | eta=34.2s ... GenericClassifier training | Epoch 149/150 | loss=0.009535 | val_loss=0.067237 | elapsed=56.7s | eta=0.4s GenericClassifier training | Epoch 150/150 | loss=0.009276 | val_loss=0.070270 | elapsed=56.9s | eta=0.0s Test accuracy: 1.000 ``` -------------------------------- ### Output of hybrid model architecture Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/examples/generic-estimators.md Expected output showing the model architecture with the quantum layer. ```text Sequential( (0): Linear(in_features=2, out_features=5, bias=True) (1): ReLU() (2): Basic( (circuit): TorchCircuit() ) (3): Linear(in_features=5, out_features=2, bias=True) ) ``` -------------------------------- ### Register opt-in backends (CUDA-Q and Qiskit Runtime) Source: https://github.com/eigenorbit/eigenkit/blob/main/README.md Registers the CUDA-Q and Qiskit Runtime backends under custom provider names. These backends are opt-in because CUDA-Q sets a process-global target and Qiskit Runtime submits billable jobs to real IBM hardware. ```python from eigenkit import CudaQuantumBackend, QiskitRuntimeBackend, register register("cudaq", CudaQuantumBackend()) register("qiskit-runtime", QiskitRuntimeBackend()) ``` -------------------------------- ### QSVC test accuracy output Source: https://github.com/eigenorbit/eigenkit/blob/main/docs/examples/algorithms-classification.md Example output showing the test accuracy (0.9) for the QSVC model. ```text 0.9 ```