Metadata-Version: 2.4
Name: polypus-quantum
Version: 0.8.0
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Scientific/Engineering :: Physics
Classifier: Programming Language :: Rust
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: MacOS
Classifier: Operating System :: Microsoft :: Windows
Requires-Dist: qiskit>=2.0,<3
Requires-Dist: qiskit-aer>=0.17,<0.18
Requires-Dist: cma>=4.5.0,<5 ; extra == 'cma'
Requires-Dist: nevergrad>=1.0.12,<2 ; extra == 'nevergrad'
Requires-Dist: optuna>=5.0.0,<6 ; extra == 'optuna'
Provides-Extra: cma
Provides-Extra: nevergrad
Provides-Extra: optuna
License-File: LICENSE
License-File: NOTICE
Summary: Distributed quantum computing — Rust core, Python bindings, one API across simulators and real QPUs.
Keywords: quantum,quantum-computing,vqc,qml,qaoa,qiskit,simulator,optimization
Home-Page: https://github.com/Bahia-Software/polypus
Author: Víctor Sóñora Pombo, Sergio Figueiras Gómez, Miguel Boubeta Martínez, Kevin Pérez González, Uxía Sendón Caamaño, Galicia Supercomputing Center (CESGA)
Author-email: Diego Beltrán Fernández Prada <diego.fernandez@bahiasoftware.es>
License-Expression: EUPL-1.2
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Documentation, https://bahia-software.github.io/polypus/
Project-URL: Homepage, https://github.com/Bahia-Software/polypus
Project-URL: Issues, https://github.com/Bahia-Software/polypus/issues
Project-URL: Repository, https://github.com/Bahia-Software/polypus
Project-URL: Rust crate (crates.io), https://crates.io/crates/polypus

<p align="center">
  <img src="https://raw.githubusercontent.com/Bahia-Software/polypus/main/assets/logo.png" alt="Polypus" width="260">
</p>

<h3 align="center">Run and train quantum circuits across many QPUs, simulated or real, with one API.</h3>

<p align="center">
  <a href="https://pypi.org/project/polypus-quantum/"><img src="https://img.shields.io/pypi/v/polypus-quantum.svg?label=PyPI" alt="PyPI"></a>
  <a href="https://crates.io/crates/polypus"><img src="https://img.shields.io/crates/v/polypus.svg?label=crates.io" alt="crates.io"></a>
  <a href="https://github.com/Bahia-Software/polypus/actions/workflows/ci.yml"><img src="https://github.com/Bahia-Software/polypus/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
  <a href="https://pypi.org/project/polypus-quantum/"><img src="https://img.shields.io/pypi/pyversions/polypus-quantum.svg" alt="Python versions"></a>
  <a href="https://github.com/Bahia-Software/polypus/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-EUPL--1.2-blue.svg" alt="License: EUPL-1.2"></a>
  <a href="https://doi.org/10.5281/zenodo.22913065"><img src="https://zenodo.org/badge/DOI/10.5281/zenodo.22913065.svg" alt="DOI"></a>
</p>

<p align="center">
  <a href="#installation">Install</a> |
  <a href="#quickstart">Quickstart</a> |
  <a href="https://github.com/Bahia-Software/polypus/tree/main/docs/guide">User guide</a> |
  <a href="https://github.com/Bahia-Software/polypus-tutorials">Tutorials</a> |
  <a href="https://bahia-software.github.io/polypus/">API reference</a> |
  <a href="https://github.com/Bahia-Software/polypus/blob/main/CHANGELOG.md">Changelog</a> |
  <a href="#citing-polypus">Cite</a>
</p>

---

Polypus is a quantum computing library with a **Rust core** and **Python bindings**. It splits shots and optimizer populations across `n_qpus` and runs them on a local simulator, on CESGA's [CUNQA](https://github.com/CESGA-Quantum-Spain/cunqa) distributed QPUs or on CESGA's QMIO quantum processor. Changing the target means changing one argument, not the algorithm code. Around that core, Polypus builds, draws and exports circuits natively, trains variational circuits and quantum machine learning models, and runs Shor's algorithm end to end.

<p align="center">
  <img src="https://raw.githubusercontent.com/Bahia-Software/polypus/main/assets/overview.svg" alt="Circuits enter the Python API; the Rust core plans the work and runs it on local Aer, the native simulator, CUNQA or QMIO" width="820">
</p>

> **New in 0.8.0:** Shor's algorithm, native circuit drawings, OpenQASM 3, adaptive Differential Evolution (SHADE and L-SHADE), CMA-ES, Adam, SPSA, Rotosolve, external ask/tell optimizers and native QML models. The release has breaking changes: read [Upgrading from 0.7](https://github.com/Bahia-Software/polypus/blob/main/CHANGELOG.md#upgrading-from-07) before you upgrade.

## Highlights

| Feature | |
|---|---|
| **Multi-QPU execution** | Shots and populations are split across `n_qpus`; results come back per QPU and merged. |
| **Variational training** | Differential Evolution (classic, SHADE or L-SHADE), Particle Swarm, Quantum Natural Gradient, CMA-ES, Adam (or momentum), SPSA and Rotosolve behind one `train()` call, or an ask/tell optimizer from Optuna, Nevergrad, pycma or your own code through `polypus.External`. A run can start from an earlier result (`initial_point`), re-evaluate its best candidates in a final batch (`final_shots`) and report or stop each iteration (`callback`). |
| **Quantum machine learning** | Your own Qiskit circuits (`qml.train`, `qml.predict`), or native models (`qml.Model`) built from encoders, ansatz layers (QCNN included) and Pauli readouts, with exact gradients, exact simulation, minibatches and save/load. |
| **Native cost observables** | QUBO and Ising costs are evaluated in Rust, without a Python call per bitstring. |
| **Rust circuit engine** | `polypus.Circuit` imports and exports OpenQASM 2 and 3, exports QIR, composes circuits and draws itself as text or SVG, with no plotting library. Parameter binding runs without the GIL, about 3x faster than Qiskit's `assign_parameters`. |
| **Shor's algorithm** | `polypus.shor.factor` factors an integer end to end on any backend, from the classical shortcuts to Beauregard's order-finding circuit, and reports the share of shots on the order's peaks, to compare with an ideal circuit and with random outcomes. The QFT and the order-finding circuit are templates in `polypus.circuits.templates`, built in Rust. |
| **Reproducible runs** | Every simulated run reports the seed it used; pass it back to replay the run. |
| **Safe on shared machines** | Simulations are sized against a memory budget, and a circuit that cannot fit is refused before allocation instead of being killed by the OOM killer. |

## Installation

```bash
pip install polypus-quantum
```

The package imports as `polypus`; pip installs Qiskit 2 and Qiskit Aer 0.17 with it. Wheels are published for CPython 3.10 to 3.13 on Linux (x86_64 and aarch64), macOS on Apple Silicon and Windows (x86_64). On other platforms, Intel Macs included, pip builds the source distribution, which needs a Rust toolchain (1.85 or newer).

| To use | Install |
|---|---|
| Local simulators (Aer and native) | `pip install polypus-quantum` |
| Optuna, Nevergrad or pycma through `polypus.External` | `pip install "polypus-quantum[optuna]"` (`[nevergrad]`, `[cma]`) |
| CUNQA | Polypus, plus [CUNQA](https://github.com/CESGA-Quantum-Spain/cunqa) `>=2.4,<4` on the cluster. **CUNQA 2.3 is not supported** (it names the `qraise` argument `cores`, not `cores_per_qpu`) |
| QMIO | Polypus built from source with the `qmio` feature: `bash install.sh --qmio` |
| The Rust crates | `cargo add polypus-circuit`, or any crate under [Architecture](#architecture); all but three are pure Rust |

<details>
<summary>Building from source</summary>

```bash
git clone https://github.com/Bahia-Software/polypus.git
cd polypus
bash install.sh            # interactive; --yes takes the defaults, --no-tests skips the test suite
```

Or by hand:

```bash
pip install -r requirements-dev.txt
maturin build --release --out dist
pip install dist/polypus_quantum-*.whl
```

For development, `maturin develop --release` installs both packages in editable mode instead: edits to Python files take effect at once, and only a Rust change needs the command run again.
</details>

> The name `polypus` on PyPI belongs to an unrelated project, so the distribution is `polypus-quantum`. The import name and the Rust crate are `polypus`.

`import polypus` does no work and writes nothing. The first native simulation of a process (`polypus.statevector`, or `backend="polypus"`) measures once per machine, in under a second, the qubit count at which the simulator's gate kernels go parallel, and caches it in `$XDG_CACHE_HOME/polypus/` (or `~/.cache/polypus/`). Set `POLYPUS_NO_AUTOCALIBRATE=1` to skip it (CI, containers); see [Performance](https://github.com/Bahia-Software/polypus/blob/main/docs/guide/performance.md).

## Quickstart

**Run a circuit on 4 QPUs**

```python
import polypus

bell = polypus.Circuit(2).h(0).cx(0, 1).measure_all()
result = polypus.run_quantum_circuit(
    bell, shots=1000, infrastructure="local", backend="polypus", n_qpus=4
)

result.counts  # one counts dict per QPU
result.merged_counts  # e.g. {'00': 487, '11': 513}
```

`backend="polypus"` is the native Rust simulator, which does not load Qiskit Aer. OpenQASM 2.0 strings are accepted the same way.

**Run it on Qiskit Aer**

```python
result = polypus.run_quantum_circuit(
    bell, shots=1000, infrastructure="local", backend="aer"
)
```

Aer is the default `backend`. It also runs Qiskit `QuantumCircuit` objects and noise models; see [Choosing a local backend](https://github.com/Bahia-Software/polypus/blob/main/docs/guide/running.md#choosing-a-local-backend). If `import qiskit_aer` fails with `cannot allocate memory in static TLS block`, see [Troubleshooting](https://github.com/Bahia-Software/polypus/blob/main/docs/guide/running.md#troubleshooting).

**Draw it**

```python
print(bell)
```

```text
     ┌───┐       ┌─┐
q0: ─┤ H ├───■───┤M├─────
     └───┘   │   └╥┘
           ┌─┴─┐  ║  ┌─┐
q1: ───────┤ X ├──╫──┤M├─
           └───┘  ║  └╥┘
                  ║   ║
c2: ══════════════╩═══╩══
                  0   1
```

The drawing is native, with no plotting library. `bell.draw(ascii=True)` draws it in plain ASCII, `bell.draw("svg")` returns an SVG document, and a Jupyter notebook displays the SVG by itself; see [Drawing](https://github.com/Bahia-Software/polypus/blob/main/docs/guide/circuits.md#drawing).

**Train a QAOA circuit for MaxCut**

```python
import polypus

edges = [(0, 1), (1, 2), (2, 3), (3, 0)]
gamma, beta = polypus.Param(0), polypus.Param(1)

qaoa = polypus.Circuit(4)
for q in range(4):
    qaoa.h(q)
for i, j in edges:
    qaoa.rzz(i, j, gamma)
for q in range(4):
    qaoa.rx(q, beta)
qaoa.measure_all()

# Cut size as a QUBO, evaluated natively. Optimizers maximise.
cut = polypus.Qubo(
    4,
    linear=[(q, 2.0) for q in range(4)],
    quadratic=[(i, j, -2.0) for i, j in edges],
)

result = polypus.train(
    qaoa,
    polypus.DE(generations=100, population_size=50, seed=42),
    shots=1024,
    n_qpus=1,
    dimensions=2,
    expectation_function=cut,
    infrastructure="local",
    backend="polypus",
    nodes=1,
    cores_per_qpu=1,
    id="maxcut",
)
result.best_params, result.best_fitness
```

To try another optimizer, replace `polypus.DE` with `polypus.PSO`, `polypus.QNG`, `polypus.CMAES`, `polypus.Adam`, `polypus.SPSA` or `polypus.Rotosolve` (for circuits whose every parameter is one single-Pauli rotation), switch DE to SHADE or L-SHADE with `strategy="shade"` or `strategy="lshade"`, or run an optimizer from another library with `polypus.External`; to run on CUNQA, set `infrastructure="cunqa"` and remove `backend="polypus"`, since CUNQA's QPUs run Aer. The rest of the code stays the same.

[Choosing an optimizer](https://github.com/Bahia-Software/polypus/blob/main/docs/guide/training.md#choosing-an-optimizer) compares them on MaxCut at the same evaluation budget; in that benchmark, the best mean result came from giving half of the budget to L-SHADE and the other half to Adam, started from L-SHADE's `best_params` with `initial_point=`. Since `best_fitness` is the best of many noisy estimates, `final_shots=` re-evaluates the best candidates in one more batch once the optimizer stops, with that many shots per circuit; `callback=` reports or stops each iteration.

**Factor 15 with Shor's algorithm**

```python
from polypus.shor import factor

result = factor(15, a=7, infrastructure="local", backend="polypus", seed=1)
result.factors, result.method, result.order  # ((3, 5), 'quantum', 4)
result.peak_share, result.uniform_peak_share  # (0.734375, 0.03515625)
```

`factor` builds Beauregard's order-finding circuit (`polypus.circuits.templates.shor_order_finding`, 18 qubits for 15) and runs it with `run_quantum_circuit`, so it takes the same `infrastructure` and `backend`. `method="quantum"` says that the order was read off the counts, not that the circuit worked: for that, compare `peak_share`, the share of shots on the order's peaks, with the 3/4 that an ideal circuit puts there for order 4 and with `uniform_peak_share`, the share that random outcomes would give. The local simulators hold 30 qubits, numbers below 128 with the default counting register, and each qubit more doubles a run's time and memory; see [Factoring with Shor](https://github.com/Bahia-Software/polypus/blob/main/docs/guide/circuits.md#factoring-with-shor).

The [tutorials](https://github.com/Bahia-Software/polypus-tutorials), in English and Spanish, go step by step from a first circuit to a native classifier, covering gates, Qiskit and OpenQASM interoperability, local and cluster execution, teleportation, the QFT, Shor's algorithm, Deutsch-Jozsa, Grover and variational training; [`examples/`](https://github.com/Bahia-Software/polypus/tree/main/examples) has complete scripts.

## Backends

| `infrastructure` | `backend` | Runs on | Seeded | Notes |
|---|---|---|---|---|
| `"local"` | `"aer"` (default) | Qiskit Aer | Yes | Full Qiskit circuit support |
| `"local"` | `"polypus"` | Native Rust statevector | Yes | Terminal measurements only ([ADR 0001](https://github.com/Bahia-Software/polypus/blob/main/docs/adr/0001-terminal-measurements.md)) |
| `"cunqa"` | | CUNQA QPUs over SLURM | Yes | `nodes`, `cores_per_qpu` and `walltime` (`HH:MM:SS`) size the allocation |
| `"qmio"` | | QMIO quantum processor | No | Pure-Rust ZeroMQ client; build with the `qmio` feature. The endpoint comes from `ZMQ_SERVER` or `options={"endpoint": ...}` |

`polypus.backend_compatibility(qc)` lists, for each backend (Aer, native, CUNQA, QMIO), why it would reject a circuit, without running it; `resources=True` also checks the native qubit ceiling and memory budget. Third-party backends plug in through a Rust trait or a Python worker; see [Writing a backend](https://github.com/Bahia-Software/polypus/blob/main/docs/backends.md).

## User guide

| Topic | Covers |
|---|---|
| [Running circuits](https://github.com/Bahia-Software/polypus/blob/main/docs/guide/running.md) | `RunResult`, multi-QPU runs, seeds, choosing a local backend, errors, troubleshooting |
| [Variational training](https://github.com/Bahia-Software/polypus/blob/main/docs/guide/training.md) | `train` parameters, `TrainResult`, cost functions, DE (classic, SHADE, L-SHADE), PSO, QNG, CMA-ES, Adam, SPSA, Rotosolve and external optimizers; starting points, final re-evaluation, callbacks, and a benchmark for choosing an optimizer |
| [Quantum machine learning](https://github.com/Bahia-Software/polypus/blob/main/docs/guide/qml.md) | `qml.train` with Qiskit circuits, labels, `SampleCost` and `qml.predict`; native models with `qml.Model`: layers, readout, losses, `fit`, prediction, saving |
| [Circuits and interchange](https://github.com/Bahia-Software/polypus/blob/main/docs/guide/circuits.md) | `polypus.Circuit`, the Rust builder, angle expressions, composing, templates (QFT, Shor's order finding), factoring with Shor, drawing, OpenQASM 2 and 3, QIR |
| [Memory budget](https://github.com/Bahia-Software/polypus/blob/main/docs/guide/memory.md) | `POLYPUS_MEM_BUDGET`, cgroup detection, `InsufficientMemoryError` |
| [Performance](https://github.com/Bahia-Software/polypus/blob/main/docs/guide/performance.md) | Batched simulation, GIL-free binding, gate-parallel auto-calibration |

The [API reference](https://bahia-software.github.io/polypus/) is the rustdoc of the workspace crates. The Python API is documented in the [user guide](https://github.com/Bahia-Software/polypus/tree/main/docs/guide) and in the type stubs and docstrings of [`python/polypus/`](https://github.com/Bahia-Software/polypus/tree/main/python/polypus).

## Architecture

Polypus is a Cargo workspace. Only the three crates marked PyO3 link against Python; the others can be used from any Rust project. Every crate is published on [crates.io](https://crates.io/crates/polypus) with each release; `polypus-backend`, `polypus-backend-conformance`, `polypus-subprocess-backend` and `polypus-qml` from 0.8.0.

<p align="center">
  <img src="https://raw.githubusercontent.com/Bahia-Software/polypus/main/assets/architecture.svg" alt="Crate graph: polypus depends on polypus-evaluation, then polypus-orchestration, which uses polypus-infrastructure and polypus-optimizers; polypus-infrastructure uses polypus-backend, polypus-sim and polypus-observable; polypus-sim uses polypus-circuit" width="760">
</p>

<details>
<summary>All crates</summary>

| Crate | Role |
|---|---|
| [`polypus`](https://github.com/Bahia-Software/polypus/tree/main/crates/polypus) | Python extension, exception hierarchy, re-exports |
| [`polypus-circuit`](https://github.com/Bahia-Software/polypus/tree/main/crates/polypus-circuit) | Circuit representation, composition, templates (QFT, Shor's order finding), text and SVG drawings, OpenQASM 2 and 3, QIR |
| [`polypus-sim`](https://github.com/Bahia-Software/polypus/tree/main/crates/polypus-sim) | Statevector simulator |
| [`polypus-optimizers`](https://github.com/Bahia-Software/polypus/tree/main/crates/polypus-optimizers) | DE (classic, SHADE, L-SHADE), PSO, QNG, CMA-ES, Adam (or momentum), SPSA and Rotosolve, and a bridge to ask/tell optimizers |
| [`polypus-observable`](https://github.com/Bahia-Software/polypus/tree/main/crates/polypus-observable) | QUBO and Ising cost observables |
| [`polypus-qml`](https://github.com/Bahia-Software/polypus/tree/main/crates/polypus-qml) | Quantum machine learning models: datasets, layers, readout and losses |
| [`polypus-physics`](https://github.com/Bahia-Software/polypus/tree/main/crates/polypus-physics) | Monte Carlo transport and Pauli-sum Hamiltonians |
| [`polypus-backend`](https://github.com/Bahia-Software/polypus/tree/main/crates/polypus-backend) | The `QuantumBackend` trait that backends implement and the `Planner` that sizes circuit waves |
| [`polypus-backend-conformance`](https://github.com/Bahia-Software/polypus/tree/main/crates/polypus-backend-conformance) | Conformance tests for backends |
| [`polypus-subprocess-backend`](https://github.com/Bahia-Software/polypus/tree/main/crates/polypus-subprocess-backend) | Bridge for backends written in Python |
| [`polypus-infrastructure`](https://github.com/Bahia-Software/polypus/tree/main/crates/polypus-infrastructure) | Built-in backends (Aer, CUNQA, QMIO, native) |
| [`polypus-orchestration`](https://github.com/Bahia-Software/polypus/tree/main/crates/polypus-orchestration) | `Flow`, `Scheduler` and `Resources`; optimizer dispatch |
| [`polypus-evaluation`](https://github.com/Bahia-Software/polypus/tree/main/crates/polypus-evaluation) | Oracles and objective assembly |
| [`polypus-logger`](https://github.com/Bahia-Software/polypus/tree/main/crates/polypus-logger) | Shared log sink |
| [`polypus_python`](https://github.com/Bahia-Software/polypus/tree/main/python/polypus_python) | Python-side backend glue, bundled in the wheel |

</details>

Design notes: [contracts](https://github.com/Bahia-Software/polypus/blob/main/docs/CONTRACTS.md), [engineering rules](https://github.com/Bahia-Software/polypus/blob/main/docs/ENGINEERING.md), [architecture decisions](https://github.com/Bahia-Software/polypus/tree/main/docs/adr). To contribute, see [CONTRIBUTING](https://github.com/Bahia-Software/polypus/blob/main/docs/CONTRIBUTING.md). Release history: [CHANGELOG](https://github.com/Bahia-Software/polypus/blob/main/CHANGELOG.md). To report a vulnerability, see [SECURITY](https://github.com/Bahia-Software/polypus/blob/main/SECURITY.md); community rules are in the [Code of Conduct](https://github.com/Bahia-Software/polypus/blob/main/CODE_OF_CONDUCT.md).

## Citing Polypus

If Polypus is useful in your research, please cite it:

```bibtex
@software{polypus,
  author  = {Fernández Prada, Diego Beltrán and Sóñora Pombo, Víctor and Figueiras Gómez, Sergio and Boubeta Martínez, Miguel and Pérez González, Kevin and Sendón Caamaño, Uxía and {Galicia Supercomputing Center (CESGA)}},
  title   = {{Polypus: A Distributed Quantum Computing Library}},
  year    = {2026},
  url     = {https://github.com/Bahia-Software/polypus},
  doi     = {10.5281/zenodo.22913065},
  version = {0.8.0}
}
```

The same metadata is in [`CITATION.cff`](https://github.com/Bahia-Software/polypus/blob/main/CITATION.cff), which GitHub shows as *Cite this repository*.

## License

Polypus is developed by Bahía Software with the Galicia Supercomputing Center (CESGA) and is licensed under the [European Union Public Licence 1.2](https://github.com/Bahia-Software/polypus/blob/main/LICENSE). Bundled third-party data (IAEA EPDL photon interaction files) is not covered by the EUPL; see [NOTICE](https://github.com/Bahia-Software/polypus/blob/main/NOTICE).

