Metadata-Version: 2.4
Name: sia-script
Version: 1.5.3
Summary: SIA: offline quantum simulator (hdqs_engine) with algorithm visuals and live browser players, HDQS server client, SiaNTT and SIA-ELS. One import: from sia import hdqs
Author-email: Sia Software Innovations Private Limited <info@siasoftwareinnovations.com>
License-Expression: LicenseRef-SIA-Proprietary AND MIT
Project-URL: Homepage, https://www.siasoftwareinnovations.com
Project-URL: Documentation, https://www.siasoftwareinnovations.com
Keywords: SIA,HDQS,hdqs-engine,quantum computing,quantum simulator,statevector,density matrix,stabilizer,matrix product state,quantum machine learning,OpenQASM,QKD,Grover,VQE,QAOA,Shor,quantum visualization,Bloch sphere,quantum education,algorithm animation,ABAP,Enterprise Logic Studio,SiaNTT
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
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: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Operating System :: OS Independent
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Education
Classifier: Topic :: Scientific/Engineering :: Physics
Classifier: Topic :: Scientific/Engineering :: Quantum Computing
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Interpreters
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Distributed Computing
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE.md
Requires-Dist: numpy>=1.24.0
Requires-Dist: requests>=2.31.0
Provides-Extra: torch
Requires-Dist: torch>=2.0; extra == "torch"
Provides-Extra: qasm
Requires-Dist: openqasm3[parser]>=1.0; extra == "qasm"
Provides-Extra: plot
Requires-Dist: matplotlib>=3.6; extra == "plot"
Provides-Extra: scipy
Requires-Dist: scipy>=1.10; extra == "scipy"
Provides-Extra: interop
Requires-Dist: qiskit>=1.0; extra == "interop"
Requires-Dist: qiskit-aer>=0.14; extra == "interop"
Requires-Dist: pennylane>=0.35; extra == "interop"
Provides-Extra: full
Requires-Dist: torch>=2.0; extra == "full"
Requires-Dist: openqasm3[parser]>=1.0; extra == "full"
Requires-Dist: matplotlib>=3.6; extra == "full"
Requires-Dist: scipy>=1.10; extra == "full"
Provides-Extra: all
Requires-Dist: torch>=2.0; extra == "all"
Requires-Dist: openqasm3[parser]>=1.0; extra == "all"
Requires-Dist: matplotlib>=3.6; extra == "all"
Requires-Dist: scipy>=1.10; extra == "all"
Requires-Dist: qiskit>=1.0; extra == "all"
Requires-Dist: qiskit-aer>=0.14; extra == "all"
Requires-Dist: pennylane>=0.35; extra == "all"
Provides-Extra: client
Provides-Extra: engine
Dynamic: license-file

# SIA — Simplified Integrated Architecture

[![PyPI](https://img.shields.io/pypi/v/sia-script.svg)](https://pypi.org/project/sia-script/)
[![Python](https://img.shields.io/pypi/pyversions/sia-script.svg)](https://pypi.org/project/sia-script/)
[![License](https://img.shields.io/badge/license-Proprietary%20%2B%20MIT%20engine-blue.svg)](LICENSE.md)

**sia-script** is the Python library of Sia Software Innovations Private Limited.
It provides an offline quantum simulator, a client for the HDQS quantum server,
a declarative entity module, and an ABAP-style enterprise logic interpreter,
all behind short, chainable APIs.

```python
from sia import hdqs

q = hdqs(2).h(0).cx(0, 1)
print(q.sample(1000))          # {'00': ~500, '11': ~500}
```

One import is all a program needs.

---

## Contents

- [Installation](#installation)
- [Components](#components)
- [Quantum simulation: `hdqs`](#quantum-simulation-hdqs)
- [HDQS server client](#hdqs-server-client)
- [Entities: `ntt`](#entities-ntt)
- [Enterprise logic: `els`](#enterprise-logic-els)
- [Optional dependencies](#optional-dependencies)
- [Conventions](#conventions)
- [Licensing](#licensing)
- [Citation](#citation)
- [Support](#support)

---

## Installation

```bash
pip install sia-script
```

Requires Python 3.9 or newer. The base install needs only NumPy and Requests.
Optional features are installed as extras:

```bash
pip install "sia-script[torch]"     # trainable quantum layers, CUDA acceleration
pip install "sia-script[qasm]"      # OpenQASM 3 import and export
pip install "sia-script[plot]"      # circuit diagrams and state plots
pip install "sia-script[full]"      # all of the above, plus SciPy
pip install "sia-script[all]"       # everything, including Qiskit/Aer/PennyLane adapters
```

## Components

| Import | What it is | Needs network |
|---|---|---|
| `from sia import hdqs` | Offline quantum simulator (`hdqs(n)`), plus the server client through the same name | No (simulator) |
| `from sia import ntt` | SiaNTT declarative entities with safe, AST-checked expressions | No |
| `from sia import els` | SIA Enterprise Logic Studio, an ABAP-style interpreter | No |

The simulator runs entirely on your machine. Importing `sia` makes no network
call; only the server client contacts the HDQS server, and only when you create
a client.

## Quantum simulation: `hdqs`

### Chainable circuits

Every gate returns the register, so programs stay short:

```python
from sia import hdqs

q = hdqs(3).h(0).cx(0, 1).cx(1, 2)          # GHZ state
q.show_state()                                    # amplitude table
print(q.sample(1000))                             # measurement counts
print(q.estimator("ZZI")["value"])                # <ZZI> = 1.0
print(q.resources()["depth"])                     # 3
```

Gates: `h x y z s sdg t tdg rx ry rz p u3 cx cy cz cp crx cry crz swap ccx
cswap mcx` (`cnot` and `toffoli` are aliases), the `cx_chain()` ladder, plus
`barrier`, `reset_qubit`, `measure` and custom `unitary`.

### Noise

Density-matrix mode supports CPTP-verified channels:

```python
from sia import hdqs

q = hdqs.dm(2).h(0).cx(0, 1).depolarizing(0, 0.05).amplitude_damping(1, 0.1)
print(q.purity(), q.concurrence())

noisy = hdqs(2).h(0).cx(0, 1).with_noise("depolarizing", 0.01)   # replay with noise
```

Channels: bit flip, phase flip, depolarizing, amplitude damping, phase damping,
generalized amplitude damping, thermal relaxation, coherent over-rotation,
amplitude–phase coupling, correlated two-qubit noise, and classical readout error.

### Programs: replay, feed-forward, undo

The register remembers its own program, so the same object can be rerun,
drawn, optimized, exported or undone:

```python
from sia import hdqs

q = hdqs(3).h(0).cx(0, 1).ry(2, 0.4)
print(q.run(500).counts)                               # rerun as a program
print(q.copy().compose(q.inverse()).probability_of("000"))   # undo: 1.0

ff = hdqs(2).h(0).measure(0, key="m").if_x("m", 1)    # mid-circuit feed-forward
print(ff.records, ff.run(1000).counts)
```

`measure(qubit, key="m")` keeps the chain going and stores the outcome in
`q.records["m"]`; `if_x`, `if_z` and `if_gate` record their condition, so
`run()`, `draw()` and `to_qasm3()` reproduce the program exactly. Branch with
these, not with a Python `if`. Plain `measure(qubit)` still returns the outcome
as a string.

### Large registers and simulation modes

A register too large for a full state (above the 1 GiB default budget) records
its program instead of failing, and can run on the stabilizer or MPS simulator:

```python
from sia import hdqs

print(hdqs(200).h(0).cx_chain().stabilizer().sample(5))       # 200-qubit GHZ
print(hdqs(40).h(0).cx_chain().mps().summary()["max_bond_dimension"])   # 2
```

| Mode | Call | Use for |
|---|---|---|
| statevector | `hdqs(n)` (default) | Exact pure-state simulation |
| density matrix | `hdqs.dm(n)` | Exact mixed states and noise |
| trajectory | `q.run(mode="trajectory", noise=...)` | Sampled noise at statevector memory cost |
| stabilizer | `q.stabilizer()` | Large Clifford-only circuits |
| MPS | `q.mps(max_bond_dim=...)` | Low-entanglement circuits |

For parameterized templates reused with different values, use
`hdqs.Circuit` with `hdqs.Parameter` and `run(bindings=...)` or `sweep(...)`.

### Algorithms and protocols

```python
from sia import hdqs

print(hdqs.grover(3, ["101"])["best"])          # '101'
print(hdqs.simon("110")["recovered"])           # '110'
print(sorted(hdqs.shor_demo(15)["factors"]))    # [3, 5]
print(hdqs.teleport()["fidelity"])              # 1.0
print(hdqs.bb84(256, eavesdrop=True)["eavesdropping_suspected"])   # True
```

Included: Deutsch, Deutsch–Jozsa, Bernstein–Vazirani, Grover, Simon, QFT (`qft_demo`),
phase estimation, order finding and a small Shor demonstration, teleportation,
superdense coding, VQE, QAOA, a repetition code, and the BB84, E91 and QSS
protocols (educational simulations, not production key distribution). Every
result can animate itself with `.draw()` (see Algorithm visuals).

### Analysis and mitigation

Observables and Pauli sums, sampled estimates with standard errors, Trotter
evolution, entropy, concurrence, negativity, mutual information, state
tomography, readout-error mitigation, zero-noise extrapolation, and CRIA
interference accessibility (`interference_report`, `interference_profile`,
`recover_interference`).

### Machine learning (requires `[torch]`)

```python
import torch
from sia import hdqs

layer = hdqs.quantum_layer(4, layers=2)                 # an ordinary torch.nn.Module
out = layer(torch.rand(8, 4, dtype=torch.float64))     # (8, 4) Pauli-Z expectations
```

`hdqs.quantum_layer(..., diff="parameter_shift")` gives hardware-style
gradients instead. The underlying classes are `BackpropQuantumLayer`,
`QuantumLayer`, `MidCircuitQuantumLayer`, `QASMQuantumLayer`, and
`CircuitQuantumLayer` (any `Circuit`, including exact gradients through
mid-circuit measurement).

### Visuals: one call, letter codes

```python
from sia import hdqs

q = hdqs(3).h(0).cx(0, 1).ry(2, 0.7).cx(1, 2)
q.draw("b")                          # Bloch spheres, shown inline or in a window
q.draw("b,a,e", "state.png")         # several views in one figure
q.draw("all", "lesson.html")         # offline interactive page with a gate-by-gate slider
q.draw("a,b", "steps.gif")           # animation over the gates
q.draw("b,q,d", "model.glb")         # 3D for Blender
q.draw("b", "bloch.stl")             # 3D printing
```

| Code | View |
|---|---|
| `c` | Circuit diagram (controls, targets, angles, measurements, conditions) |
| `p` | Exact probabilities |
| `h` | Measured counts (`shots=`), with ±1σ error bars and the exact values |
| `a` | Amplitudes & phase: bar height = magnitude, colour and a clock hand = phase |
| `b` | Bloch sphere for every qubit, with coordinates and purity |
| `q` | Q-sphere: basis states by number of 1s, coloured by phase |
| `d` | Density matrix, real and imaginary parts (up to 5 qubits, or `qubits=[...]`) |
| `e` | Entanglement map: mutual information and concurrence for every qubit pair |
| `i` | CRIA interference profile with the best helper sets |
| `s` | Step-through: the state after every gate |
| `all` | Every 2D view (`c p h a b q d e i`) |

Codes combine with commas (`"b,a,e"`), and several outputs can be written at
once (`"x.png,x.html,x.glb"`). The file extension picks the output:

| Extension | Output | Needs |
|---|---|---|
| `.png .jpg .svg .pdf .webp` | Combined figure, light or dark (`theme="dark"`) | `[plot]` |
| `.gif` | Animation over the gates | `[plot]` |
| `.html` | Interactive page: step slider, rotatable spheres, exact values on hover, table view, data download. One file, works offline and on phones | nothing |
| `.json` `.csv` | The numbers behind every view | nothing |
| `.glb` `.obj` | 3D scene for Blender, Maya, Unity or web viewers, with every part a named object | nothing |
| `.stl` | Watertight, print-ready model in millimetres (`scale=` to resize) | nothing |

3D files are produced only when a 3D extension is named, so `"all"` never
writes one by accident. The 3D views are `b`, `q` and `d`. `q.draw("bell.png")`
still draws the circuit, and `q.plot(...)` still returns a Matplotlib figure.

### Algorithm visuals: how it works, not just the circuit

Every algorithm returns its usual result dictionary, which now also has
`.draw()`, `.code()` and `.circuit`. The animation explains the idea behind the
algorithm using the states recorded during that very run, so every picture
matches the returned numbers, and it changes with whatever inputs you give it.

```python
from sia import hdqs

r = hdqs.grover(3, ["101"])
r.draw("grover.gif")              # the circuit, then inversion about the mean and the rotation picture
r.draw("grover.html")             # live player: change the inputs and re-run, right in the browser
r.draw("grover.png", summary=True)   # one slide with the answer
r.code()                          # the hdqs chain that builds this run's circuit
```

Each animation opens with **the circuit built for your input**, with the oracle
and other parts labelled. Grover, Deutsch–Jozsa and Simon use real gate-level
oracles (X gates around a multi-controlled Z; one Z per bit when f is linear;
CNOT copies for Simon). `r.code()` prints that circuit as a runnable
one-import chain (repeated Grover iterations become a loop), and `r.circuit`
is the program itself.

The last frame carries a **result banner** (`FOUND 101`, `15 = 3 × 5`,
`ABORT · QBER 25%`) and every panel says **where its numbers come from**:
EXACT (from the state), SAMPLED (measurement shots), CLASSICAL (ordinary
computation) or THEORY (a formula).

| Algorithm | What the animation shows |
|---|---|
| `grover` | Amplitudes reflected about the mean, the 2D rotation picture with its mirrors, success probability |
| `deutsch`, `deutsch_jozsa` | Phase kickback turning f(x) into signs, then interference deciding constant vs balanced |
| `bernstein_vazirani` | Each oracle CNOT flipping one qubit to \|−⟩; Hadamards turning the phases into the hidden bits |
| `simon` | Equations y·s = 0 accumulating while the candidate secrets are crossed out |
| `qft_demo` | Output qubits turning at ½, ¼, ⅛ … turn per +1, and the output phasors |
| `phase_estimation` | Kickback onto each counting qubit, the outcome distribution sharpening with precision |
| `order_finding`, `shor_demo` | The period of aˣ mod N, QPE peaks at s/r, continued fractions, gcd to the factors |
| `teleport` | Three Bloch spheres, entanglement links, two classical bits travelling, Bob's correction |
| `superdense` | Alice's operation choosing one of four Bell states, Bob decoding two bits |
| `vqe` | Energy converging towards the exact ground energy, the path over the energy landscape |
| `qaoa_maxcut` | The (γ, β) landscape search, sampled cut sizes, the best cut drawn on the graph |
| `bb84`, `e91`, `qss` | Bases and photons, sifting and the QBER alarm; the CHSH value passing 2; GHZ parity |
| `repetition_code_demo` | Encoding, a bit flip, the syndrome lighting up, correction and decoding |
| `interference_report` (CRIA) | Interference recovered as more helper qubits are read |

| Extension | Output | Needs |
|---|---|---|
| `.html` | **Live player**: plays the run; the reader can change the inputs and re-run the algorithm in the browser (a built-in simulator, no internet, no Python); Code tab with the hdqs chain; light/dark; SVG and JSON download | nothing |
| `.gif` | Animation (`speed=`, `tween=` for in-between frames) | `[plot]` |
| `.png .jpg .webp` | Storyboard of every stage, one stage with `scene=k`, or one slide with `summary=True` | `[plot]` |
| `.pdf` | One page per stage | `[plot]` |
| `.json` | The recorded stages as data | nothing |
| `.mp4` | Video, when ffmpeg is installed | `[plot]` |

The recording costs only a few numbers per stage; the pictures are made when
`.draw()` is called. In the browser player, a seed gives a repeatable run, but
sampled results use the browser's own random numbers, not Python's.

### Interoperability

OpenQASM 3 via `hdqs.from_qasm3(source)` and `q.to_qasm3()` (requires `[qasm]`).
Optional adapters: `hdqs.to_qiskit`, `hdqs.run_aer`, `hdqs.to_pennylane`.

## HDQS server client

The same `hdqs` name reaches the HDQS quantum server. A whole number builds the
local simulator; any other call connects to the server:

```python
from sia import hdqs

client = hdqs(api_key="YOUR_TOKEN")
client.qbt_create(num_qubits=2)
client.qbt_run(["h 0", "cnot 0 1"])
print(client.qbt_measure([0, 1]))
```

An API token is issued by Sia Software Innovations. The server address can be
changed without reinstalling, using the `SIA_HDQS_HOST` and `SIA_HDQS_PORT`
environment variables. If the server is unreachable, client calls raise
`hdqs.HDQSError`; the offline simulator is unaffected.

## Entities: `ntt`

```python
from sia import ntt

Person = ntt("name", "age").computed("group", "if (1) > 17: adult | else: minor")
p = Person("Ravi", 20)
print(p.name, p.group)          # Ravi adult
```

Templates refer to attributes by position, `(0)`, `(1)`, and so on. Conditions
and validators are evaluated through a restricted expression checker, never
`eval`.

## Enterprise logic: `els`

```python
from sia import els

program = """
*sia
  DATA total TYPE I.
  total = 40 + 2.
  WRITE total.
sia*
"""
print(els(program))             # 42
```

For multi-block programs, share state with `env = els.make_env()` and call
`els(block, env)`. An interactive prompt is available through `els.repl()`.

## Optional dependencies

| Extra | Installs | Enables |
|---|---|---|
| `torch` | PyTorch | Trainable layers, CUDA acceleration |
| `qasm` | openqasm3[parser] | OpenQASM 3 import and export |
| `plot` | Matplotlib | Image and GIF output of `draw()`, algorithm GIF/PNG/PDF/MP4; `plot()` |
| `scipy` | SciPy | Sparse observable matrices |
| `interop` | Qiskit, Qiskit Aer, PennyLane | Adapters |
| `full` | torch, qasm, plot, scipy | Everything except the adapters |
| `all` | Everything above | Everything |

A feature whose dependency is missing raises an `ImportError` naming the
package to install. `hdqs.capabilities()` reports what is available.

## Conventions

- Qubit 0 is the most significant bit: in `'01'`, qubit 0 is `0`.
  Qiskit uses the opposite order; the adapters convert automatically.
- `measure()` collapses the state; `sample()` and `probabilities()` do not.
- Memory grows exponentially with qubit count in the statevector and
  density-matrix modes. Above the 1 GiB default budget a register becomes
  program-only (`q.is_lazy`): use `q.stabilizer()` or `q.mps()`, or pass
  `max_memory_mb=` to allow a larger full state.

## Licensing

sia-script is proprietary software of Sia Software Innovations Private Limited,
with one exception: the quantum simulator, `sia/hdqs_engine.py`, is released
under the MIT License. See [LICENSE.md](LICENSE.md) for the full terms of both.

## Citation

If you use the CRIA interference-accessibility tools in research, please cite:

> Seshabattara Venkata, N. S. D. N. *Cardinality-Resolved Interference
> Accessibility in Multipartite Quantum Systems.* Zenodo (2026).
> https://doi.org/10.5281/zenodo.23180889

## Support

Sia Software Innovations Private Limited  
Email: info@siasoftwareinnovations.com  
Website: https://www.siasoftwareinnovations.com
