Metadata-Version: 2.2
Name: moonlab
Version: 1.2.0
Summary: High-performance quantum computing simulator with GPU acceleration
Author-Email: tsotchke <tsotchke@github.com>
License: MIT License
         
         Copyright (c) 2024-2026 tsotchke
         
         Permission is hereby granted, free of charge, to any person obtaining a copy
         of this software and associated documentation files (the "Software"), to deal
         in the Software without restriction, including without limitation the rights
         to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
         copies of the Software, and to permit persons to whom the Software is
         furnished to do so, subject to the following conditions:
         
         The above copyright notice and this permission notice shall be included in all
         copies or substantial portions of the Software.
         
         THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
         IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
         FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
         AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
         LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
         OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
         SOFTWARE.
         
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Scientific/Engineering :: Physics
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Operating System :: MacOS
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: Microsoft :: Windows
Project-URL: Homepage, https://github.com/tsotchke/moonlab
Project-URL: Documentation, https://github.com/tsotchke/moonlab#readme
Project-URL: Repository, https://github.com/tsotchke/moonlab
Project-URL: Issues, https://github.com/tsotchke/moonlab/issues
Requires-Python: >=3.9
Requires-Dist: numpy>=1.20.0
Provides-Extra: ml
Requires-Dist: torch>=1.9.0; extra == "ml"
Requires-Dist: tensorflow>=2.5.0; extra == "ml"
Provides-Extra: viz
Requires-Dist: matplotlib>=3.3.0; extra == "viz"
Requires-Dist: plotly>=5.0.0; extra == "viz"
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
Requires-Dist: pytest-xdist>=3.0.0; extra == "dev"
Requires-Dist: black>=23.0.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Provides-Extra: all
Requires-Dist: moonlab[dev,ml,viz]; extra == "all"
Description-Content-Type: text/markdown

# Moonlab Python Bindings

**Python interface for the Moonlab Quantum Simulator**

Fast, feature-complete quantum computing in Python with PyTorch integration.

## Quick Start

```python
from moonlab import QuantumState

# Create Bell state (maximal entanglement)
state = QuantumState(2)
state.h(0).cnot(0, 1)

# Measure probabilities
probs = state.probabilities()
print(probs)  # [0.5, 0.0, 0.0, 0.5] - |00⟩ and |11⟩
```

## Installation

### Prerequisites

The published wheel is self-contained: the Python build pins
`QSIM_ENABLE_OPENMP=OFF` (see `bindings/python/pyproject.toml`), so
`pip install moonlab` needs no `libomp` install.

`libomp` is only relevant if you build libquantumsim yourself with
OpenMP turned on (the top-level CMake default), e.g. for a non-Python
build or local development against a custom CMake configuration:

```bash
# macOS with Apple Silicon
brew install libomp

# Linux
sudo apt-get install libomp-dev
```

### Build & Install

```bash
# 1. Build C library
cd /path/to/moonlab
make

# 2. Install Python package
cd bindings/python
pip install -e .

# 3. Test installation
python test_moonlab.py
```

## Features

### Core Quantum Operations

- **32-qubit simulation** (4.3 billion states)
- **Complete universal gate set** (H, X, Y, Z, CNOT, Toffoli, rotations)
- **Bell inequality violation** on explicit Bell states (CHSH ~ 2.87 measured at 10k samples on |Phi+>, vs the Tsirelson bound 2.828).  The CHSH test now correctly honours whatever state you pass in -- the previous release silently overwrote the input with |Phi+>, making every CHSH result read 2.828 by fiat.  Separable inputs now give CHSH ~ 0 as physics requires.
- **SIMD-dispatched C core** (AVX-512 / AVX2 / NEON / SVE) with an optional Metal GPU backend on Apple Silicon; see the reproducible-benchmark harness for host-specific numbers rather than a single multiplier

### Quantum Algorithms

- **VQE** - Variational Quantum Eigensolver for molecular simulation,
  with native reverse-mode autograd (adjoint-method gradient) for the
  hardware-efficient ansatz in noise-free simulation
- **QAOA** - Quantum optimization (MaxCut, Ising models)
- **Grover** - Quantum search algorithm
- **Bell Tests** - CHSH, Mermin (3-qubit GHZ), and Mermin-Klyshko
  N-qubit nonlocality inequalities

### Native Autograd (`moonlab.diff`)

Reverse-mode gradients for parameterised circuits, without a PyTorch
dependency:

```python
from moonlab import QuantumState
from moonlab.diff import DiffCircuit, PauliTerm, OBS_Z, OBS_X

circ = DiffCircuit(num_qubits=2).ry(0, 0.3).ry(1, -0.4).cnot(0, 1)
H = [PauliTerm(1.0, [0], [OBS_Z]),
     PauliTerm(0.5, [0, 1], [OBS_Z, OBS_Z])]

state = QuantumState(2)
circ.forward(state)
cost = DiffCircuit.expect_pauli_sum(state, H)
grad = circ.backward_pauli_sum(state, H)   # ndarray, shape (n_params,)
```

Supported gates: RX / RY / RZ / H / X / Y / Z / CNOT / CZ / CRX / CRY / CRZ.

### Post-Quantum Cryptography (`moonlab.crypto`)

FIPS 202 SHA-3 / SHAKE and FIPS 203 ML-KEM (512 / 768 / 1024), with
health-tested, Bell-gated, SHAKE256-conditioned RNG convenience wrappers:

```python
from moonlab.crypto import sha3, mlkem

digest = sha3.sha3_256(b"quantum randomness")        # 32 bytes
stream = sha3.shake256(b"seed", outlen=1024)          # XOF

# Alice keygens with Moonlab's conditioned hybrid RNG
ek, dk = mlkem.keygen768_qrng()                       # 1184-byte pk, 2400-byte sk
# Bob encapsulates a shared secret
ct, K_bob = mlkem.encaps768_qrng(ek)                  # 1088-byte ciphertext
# Alice decapsulates
K_alice = mlkem.decaps768(ct, dk)
assert K_alice == K_bob                               # same 32-byte shared secret
```

All NIST SHA-3 / SHAKE known-answer vectors pass; ML-KEM is validated
against the pq-crystals reference via AES-256-CTR_DRBG-derived NIST
count=0 seed (see `docs/security/pqc.md` for the full threat model).

### Quantum Machine Learning

- **Feature Maps**: Angle, Amplitude, IQP encoding
- **Quantum Kernels**: Exponential feature spaces
- **QSVM**: Quantum Support Vector Machine
- **Quantum PCA**: Principal component analysis
- **PyTorch Integration**: QuantumLayer with autograd

## Examples

### Basic Quantum Circuit

```python
from moonlab import QuantumState, Gates

# Create 3-qubit GHZ state
state = QuantumState(3)
Gates.H(state, 0)
Gates.CNOT(state, 0, 1)
Gates.CNOT(state, 1, 2)

# Get state vector
sv = state.get_statevector()
print(f"|GHZ⟩ = {sv}")
```

### Quantum Machine Learning

```python
from moonlab.ml import QSVM, IQPEncoding
import numpy as np

# Prepare data
X_train = np.random.randn(50, 4)
y_train = np.random.choice([-1, 1], 50)

# Train Quantum SVM
qsvm = QSVM(num_qubits=4, feature_map='iqp')
qsvm.fit(X_train, y_train)

# Predict
y_pred = qsvm.predict(X_test)
accuracy = qsvm.score(X_test, y_test)
print(f"Accuracy: {accuracy:.1%}")
```

### PyTorch Integration

```python
import torch
import torch.nn as nn
from moonlab.torch_layer import QuantumLayer

# Build hybrid quantum-classical network
model = nn.Sequential(
    nn.Linear(28*28, 16),
    nn.Tanh(),
    QuantumLayer(num_qubits=16, depth=3),
    nn.Linear(16, 10)
)

# Train with standard PyTorch
optimizer = torch.optim.Adam(model.parameters())
for epoch in range(10):
    outputs = model(train_data)
    loss = criterion(outputs, labels)
    loss.backward()  # Quantum gradients via parameter shift!
    optimizer.step()
```

### Quantum PCA

```python
from moonlab.ml import QuantumPCA

# Dimensionality reduction with quantum advantage
qpca = QuantumPCA(num_components=2, num_qubits=3)
qpca.fit(X_highdim)
X_reduced = qpca.transform(X_highdim)

print(f"Explained variance: {qpca.explained_variance_}")
```

## Advanced Usage

### Custom Feature Maps

```python
from moonlab.ml import QuantumFeatureMap
from moonlab import QuantumState

class CustomEncoding(QuantumFeatureMap):
    def encode(self, x, state):
        state.reset()
        for i, val in enumerate(x):
            state.ry(i, val)
            state.rz(i, val**2)
        # Add entanglement
        for i in range(state.num_qubits - 1):
            state.cnot(i, i+1)
```

### Variational Quantum Circuits

```python
from moonlab.ml import VariationalCircuit
from moonlab import QuantumState

circuit = VariationalCircuit(num_qubits=8, num_layers=4)
state = QuantumState(8)
circuit(state)  # Apply parameterized circuit
```

### Quantum Kernels

```python
from moonlab.ml import QuantumKernel, IQPEncoding

# Create quantum kernel
encoder = IQPEncoding(num_qubits=4, num_layers=2)
kernel = QuantumKernel(encoder)

# Compute kernel matrix
K = kernel.compute_matrix(X_train)

# Use in any kernel method (SVM, Ridge, etc.)
from sklearn.svm import SVC
svm = SVC(kernel='precomputed')
svm.fit(K, y_train)
```

## Applications

### Drug Discovery (VQE)

```python
from moonlab.algorithms import VQE

# Simulate H₂ molecule
vqe = VQE(num_qubits=4, num_layers=3)
result = vqe.solve_h2(bond_distance=0.74)
print(f"Ground state energy: {result['energy']:.6f} Ha")
print(f"Converged: {result['converged']}")
```

### Graph Optimization (QAOA)

```python
from moonlab.algorithms import QAOA

# Solve MaxCut problem on a 5-vertex graph
qaoa = QAOA(num_qubits=5, num_layers=3)
result = qaoa.solve_maxcut(
    edges=[(0,1), (1,2), (2,3), (3,4), (4,0), (0,2)]
)
print(f"Best cut: {bin(result['best_bitstring'])}")
print(f"Cut value: {result['best_cost']}")
```

### Few-Shot Learning

```python
from moonlab.torch_layer import QuantumClassifier

# Quantum classifier for small datasets
model = QuantumClassifier(
    num_features=16,
    num_qubits=8,
    num_classes=5,
    depth=3
)

# Train on small dataset (quantum advantage!)
train_with_few_samples(model, X_train_small, y_train_small)
```

## Performance

| Operation | Speed | Notes |
|-----------|-------|-------|
| 20-qubit circuit | <1ms | SIMD + parallel optimized |
| VQE H₂ molecule | 2-5s | Chemical accuracy |
| QAOA 10-vertex MaxCut | 10-30s | Near-optimal solutions |
| Quantum kernel (n=100) | 5-15s | Exponential feature space |

### vs Other Frameworks

| Framework | Speed (rel.) | Features | Apple Silicon |
|-----------|--------------|----------|---------------|
| **Moonlab** | **1.0×** (fastest) | Complete | ✅ Optimized |
| Qiskit | 10-50× slower | Excellent | ⚠️ Not optimized |
| Cirq | 15-40× slower | Good | ⚠️ Not optimized |

## Testing

```bash
# Run test suite
python test_moonlab.py

# Tests include:
# - Core quantum operations
# - Quantum ML algorithms
# - PyTorch integration
# - End-to-end workflows
```

## API Reference

### moonlab.core

- **QuantumState(num_qubits)** - Quantum state vector
  - Methods: `h()`, `x()`, `y()`, `z()`, `cnot()`, `rx()`, `ry()`, `rz()`
  - Properties: `probabilities()`, `get_statevector()`

- **Gates** - Static gate interface
  - `Gates.H(state, qubit)`, `Gates.CNOT(state, c, t)`, etc.

### moonlab.ml

- **AngleEncoding** - Simple rotation-based encoding
- **AmplitudeEncoding** - Exponential data compression
- **IQPEncoding** - Quantum kernel feature map
- **QuantumKernel** - Kernel computation K(x,x') = |⟨φ(x)|φ(x')⟩|²
- **QSVM** - Quantum Support Vector Machine
- **QuantumPCA** - Quantum Principal Component Analysis

### moonlab.torch_layer

- **QuantumLayer** - Parameterized quantum circuit as nn.Module
- **QuantumClassifier** - Complete quantum classifier
- **HybridQNN** - Hybrid quantum-classical network
- **VariationalCircuit** - General variational ansatz

### moonlab.algorithms

- **VQE** - Variational Quantum Eigensolver
- **QAOA** - Quantum Approximate Optimization
- **Grover** - Quantum search
- **BellTest** - CHSH inequality verification

## Contributing

See [`CONTRIBUTING.md`](../../CONTRIBUTING.md) for development guidelines.

## License

MIT License - See [`LICENSE`](../../LICENSE) file.

## Links

- **Documentation**: https://github.com/tsotchke/moonlab
- **GitHub**: https://github.com/tsotchke/moonlab
- **Issues**: https://github.com/tsotchke/moonlab/issues

## Citation

If you use Moonlab in research, please cite:

```bibtex
@software{moonlab2026,
  title={Moonlab: High-Performance Quantum Computing for Apple Silicon},
  author={Tsotchke},
  year={2026},
  url={https://github.com/tsotchke/moonlab}
}
```

## Support

- **Issues**: https://github.com/tsotchke/moonlab/issues
- **Email**: support@tsotchke.ai

## References

This library implements algorithms from the following foundational works:

**Quantum Computing:**
- Nielsen, M. A. & Chuang, I. L. (2010). *Quantum Computation and Quantum Information*. Cambridge University Press.

**Variational Algorithms:**
- Peruzzo, A. et al. (2014). "A variational eigenvalue solver on a photonic quantum processor." *Nat. Commun.* 5, 4213.
- Farhi, E., Goldstone, J., & Gutmann, S. (2014). "A quantum approximate optimization algorithm." arXiv:1411.4028.

**Quantum Machine Learning:**
- Schuld, M. & Petruccione, F. (2021). *Machine Learning with Quantum Computers*. Springer.
- Benedetti, M. et al. (2019). "Parameterized quantum circuits as machine learning models." *Quantum Sci. Technol.* 4, 043001.

---

## Historical: what shipped in v0.3.0

This package is currently at **v1.2.0** (stable ABI **0.6.0**); see
`CHANGELOG.md` at the repo root and `docs/PARITY_MATRIX.md` for the
full v0.4-v1.1 history, including the v1.1 GPU (CUDA) state API,
control-plane job scheduling, and QRNG status surface added since the
notes below. The v0.3 highlights are kept here because the
module-level docs they reference (`docs/reference/qgt-api.md`,
`docs/reference/mpdo-api.md`) are unchanged since:

**Quantum geometric tensor and topology** (`moonlab.topology`):
- `chern_qwz_proj(m, N)`, `chern_qwz_parallel_transport(m, N)` —
  gauge-invariant projector-trace and parallel-transport-gauge
  Chern integrators on the Qi-Wu-Zhang model.
- `kane_mele_z2(t, lambda_so, lambda_r, lambda_v, N)` — 4-band Z_2
  invariant via Fukui-Hatsugai (2007).
- `bhz_z2(A, B, M, N)` — HgTe quantum-well topological insulator
  (Bernevig-Hughes-Zhang 2006).
- `kitaev_chain_z2(t, mu, delta)` — 1D BdG Z_2 from Pfaffian-sign
  product at the time-reversal-invariant momenta (Kitaev 2001).
- `hofstadter_chern(p, q, n_occupied, t, N)` — magnetic-Bloch
  sub-band Chern numbers (Hofstadter 1976).

**Matrix-product density operator noise simulator**
(`moonlab.mpdo.Mpdo`):
- Polynomial-cost noisy-circuit simulation per Verstraete, Garcia-
  Ripoll, and Cirac (Phys. Rev. Lett. 93, 207204, 2004).
- Six named single-qubit Kraus channels (depolarising, amplitude
  damping, phase damping, bit / phase / bit-phase flip).
- User-supplied Kraus operators via NumPy complex arrays.
- Pauli expectation values (string or integer Pauli code).

**Other v0.3 additions**:
- `moonlab.var_d_run`, `moonlab.var_d_run_v2` — CA-MPS variational-D
  with `convergence_eps`.
- All v0.2 noise channels and Bell-variants harness remain available.

`MOONLAB_LIB_PATH` and `MOONLAB_LIB_DIR` environment variables now
override the dylib search path (parity with the Rust binding's
`MOONLAB_LIB_DIR`).  See `docs/reference/qgt-api.md` and
`docs/reference/mpdo-api.md` for the corresponding C ABI contracts,
and `docs/tutorials/{topological_band_structure,mpdo_noise}.md` for
worked examples.

---

*Current release: v1.2.0 (ABI 0.6.0)*
