diff options
| author | hachem <im@hachem.wtf> | 2026-10-16 19:56:08 +0200 |
|---|---|---|
| committer | hachem <im@hachem.wtf> | 2026-10-16 19:56:08 +0200 |
| commit | 595392c135b2b7dc4cc6414f6891d5e778b7836d (patch) | |
| tree | dfa359851830f887108b3000e965ce548cf0d123 /README.md | |
| parent | a136c80d978841d317a6ad3930b9e608fdba1586 (diff) | |
Diffstat (limited to 'README.md')
| -rw-r--r-- | README.md | 258 |
1 files changed, 127 insertions, 131 deletions
@@ -1,186 +1,182 @@ -# $\psi$: a quantum computational toolkit +# $\psi$ -$\psi$ is a powerful quantum computing toolkit designed for simulating quantum circuits and wavefunction dynamics on classical hardware. +psi is a quantum circuit simulator that runs on your cpu. -## features +## gates -### quantum gates +all the usual clifford gates are there: h, x, y, z and s on one qubit, cnot, cz and swap on two, and toffoli (ccnot) and fredkin (cswap) on three. past the clifford set you get t, the daggered versions of s and t, $\sqrt{X}$ and its inverse, rotations $R_x(\theta)$, $R_y(\theta)$ and $R_z(\theta)$, the phase gate $P(\theta)$, the general unitaries $U_1$, $U_2$ and $U_3$, and controlled versions of the three rotations and the phase gate. each one is a function named after the gate, so `psi_apply_h`, `psi_apply_cnot`, `psi_apply_sdg`, `psi_apply_crz` and so on. -**clifford gates:** -- single-qubit: h, x, y, z, s -- two-qubit: cnot, cz, swap -- three-qubit: ccnot (toffoli), cswap (fredkin) +if what you need isn't in there, you can make your own gate, either straight from a unitary matrix or by chaining some of the built-in gates (h, x, y, z, s, t, cnot, cz, swap, ccnot and cswap) into a composite. -**non-clifford gates:** -- fixed: t, $S^\dagger$, $T^\dagger$, $\sqrt{X}$, $\sqrt{X}^\dagger$ -- parametric rotations: $R_x(\theta)$, $R_y(\theta)$, $R_z(\theta)$, $P(\theta)$ -- general unitaries: $U_1(\lambda)$, $U_2(\phi, \lambda)$, $U_3(\theta, \phi, \lambda)$ -- controlled parametric: $CR_x(\theta)$, $CR_y(\theta)$, $CR_z(\theta)$, $CP(\theta)$ +you can add measurements with `psi_measure` or `psi_measure_all`. they show up when you print or draw the circuit, but the simulator doesn't collapse the state on them yet. -**custom gates:** -- define gates from unitary matrices -- build composite gates from sequences of operations +## running circuits -### composable runtime system +how a circuit gets computed is up to you. a `struct PsiRuntimeConfig` has four switches you can flip in any combination. -build custom execution pipelines by combining optimisation features: +`batched` groups runs of single-qubit gates on the same qubit and multiplies them into one matrix, which usually cuts the number of kernels by 30 to 50 percent. `structure_aware` goes further. it works out which gates are diagonal or controlled, figures out what commutes with what, reorders and fuses until nothing else will merge, and groups what's left into layers that can run side by side. `simd` picks avx-512, avx2 with fma, or neon depending on what your cpu supports, and falls back to plain scalar code if there's nothing. that check happens at runtime. `parallel` splits the state vector across threads, but only once the circuit has at least `parallel_threshold` qubits (8 by default), so small circuits stay on one thread. -| feature | description | -|---------|-------------| -| `.batched()` | kernel batching with gate fusion | -| `.simd()` | simd acceleration (avx-512/avx2/neon) | -| `.structure_aware()` | commutation analysis and advanced fusion | -| `.parallel()` | multi-threaded execution | -| `.with_threshold(n)` | set parallel threshold (default: 8 qubits) | +if you'd rather not set flags by hand, `enum PsiRuntime` has presets. `PSI_RUNTIME_BASIC` does direct simulation, `PSI_RUNTIME_BATCHED` adds batching, `PSI_RUNTIME_SIMD` is batching plus simd, and `PSI_RUNTIME_STRUCTURE_AWARE` is structure-aware plus simd. each one has an `_MT` twin that turns threading on. `psi_optimal_runtime_config()` gives you structure-aware, simd and threads together, and plain `psi_compute_circuit` uses the basic runtime. -**predefined runtimes:** -- `Runtime::BasicRT` / `BasicRTMT` — direct state vector simulation -- `Runtime::BatchedRT` / `BatchedRTMT` — batched kernel execution -- `Runtime::SimdRT` / `SimdRTMT` — batched + simd -- `Runtime::StructureAwareRT` / `StructureAwareMT` — structure-aware + simd -- `Runtime::optimal()` — structure-aware + simd + parallel +threading uses pthreads on macos and linux. windows doesn't have a threading backend yet, so parallel runtimes just run on one thread there. -### simd acceleration +## noise -automatic detection and use of platform-specific simd instructions: -- **avx-512**: modern intel/amd processors -- **avx2+fma**: older x86_64 processors -- **neon**: arm processors (apple silicon, etc.) -- **scalar fallback**: universal compatibility +for noise you move from a state vector to a density matrix and apply kraus channels to it. the built-in channels are depolarising, bit flip, phase flip and bit-phase flip, which each take an error probability, plus amplitude damping for $T_1$ energy loss, generalised amplitude damping for the finite-temperature version of that, and phase damping for $T_2$ dephasing. they're all named `psi_<name>_channel`. if none of those fit, you can put together your own from kraus operators with `psi_new_kraus_operator` and `psi_new_noise_channel`. once noise is applied you can read off the trace, purity, measurement probabilities, and fidelity against a pure state. -### kernel optimisations +## looking at circuits -**batching:** -- groups consecutive single-qubit gates on the same qubit -- fuses gate matrices to reduce operations -- typically achieves 30–50% kernel reduction +`psi_print_circuit` writes out the list of operations and, if the circuit has been computed, its non-zero amplitudes. for an actual picture, `psi_render_circuit_horizontal` and `psi_render_circuit_vertical` draw the circuit in ascii and hand you back a string that you `free()` yourself. matrices and vectors have their own printers too, `psi_print_matrix` and `psi_print_vector`. -**structure-aware:** -- gate type detection (diagonal, non-diagonal, controlled) -- commutation analysis for reordering -- multi-pass fusion until convergence -- execution layer grouping for parallelism +## building -### noise channels (density matrix) +you'll need a c17 compiler (clang or gcc), [premake5](https://premake.github.io/) and make. -realistic quantum noise simulation using kraus operators: +```bash +premake5 gmake +make config=release +``` -| channel | description | -|---------|-------------| -| `depolarising(p)` | random pauli error with probability $p$ | -| `amplitude_damping(γ)` | energy decay ($T_1$ relaxation) | -| `phase_damping(γ)` | phase decoherence ($T_2$ dephasing) | -| `bit_flip(p)` | $X$ error with probability $p$ | -| `phase_flip(p)` | $Z$ error with probability $p$ | -| `bit_phase_flip(p)` | $Y$ error with probability $p$ | +that leaves `libpsi.a` and the `tester` binary in `bin/release-macosx/`, or whichever folder matches your configuration and platform. the configurations are debug, release and dist. on windows, run `premake5 vs2022` to get a visual studio solution instead. `premake5 clean` wipes everything the build produced. -```rust -use psi::{DensityMatrix, NoiseChannel}; +to use psi from your own code, add `include/` to your include path, include `psi.h`, and link against `libpsi.a` and libm (and pthreads on linux): -// Create density matrix from circuit state -let dm = DensityMatrix::from_state_vector(&state_vec); +```bash +cc -std=c17 -Iinclude main.c bin/release-macosx/libpsi.a -lm -o main +``` -// Apply noise -let noise = NoiseChannel::depolarising(0.05); -dm.apply_noise_channel(&noise, 0); // Apply to qubit 0 +## a quick example -// Check properties -println!("Purity: {}", dm.purity()); // 1.0 = pure, <1.0 = mixed -println!("Fidelity: {}", dm.fidelity_with_pure_state(&ideal_state)); -``` +here's a three-qubit ghz state, computed with the fastest settings available: -## project structure +```c +#include <stdio.h> -`psi` is a single crate. the library lives under `src/`: +#include "psi.h" -- **`core`**: quantum gates, circuits, registers, and runtimes -- **`maths`**: complex numbers, vectors, matrices, simd operations -- **`visualizer`**: circuit visualisation (ascii horizontal/vertical) +int main(void) +{ + struct PsiQuantumCircuit circuit = psi_new_quantum_circuit(3); -the comprehensive test suite and benchmarks live in **`examples/tester`**. + // build a ghz state + psi_apply_h(&circuit, 0); + psi_apply_cnot(&circuit, 0, 1); + psi_apply_cnot(&circuit, 0, 2); -## quick start + // execute with optimal settings + psi_compute_circuit_with_config(&circuit, psi_optimal_runtime_config()); -```rust -use psi::{QuantumCircuit, Runtime}; + psi_print_circuit(&circuit, stdout); -fn main() { - let mut circuit = QuantumCircuit::new(3); - - // Build a GHZ state - circuit.h(0).cnot(0, 1).cnot(0, 2); - - // Execute with optimal settings - circuit.compute_with_config(Runtime::optimal()); - - println!("{}", circuit.state()); + psi_free_quantum_circuit(&circuit); + return 0; } ``` -### composable runtimes +which prints -```rust -use psi::{QuantumCircuit, RuntimeConfig}; +``` +QuantumCircuit (3 qubits, 0 classical) +Operations: + 0: H on [0] + 1: CNOT on [0, 1] + 2: CNOT on [0, 2] +State: + |000⟩: ¹⁄√2 + |111⟩: ¹⁄√2 +``` + +## more examples + +picking your own runtime looks like this. you start from an empty config, switch on what you want, and read the probabilities back afterwards: -let mut circuit = QuantumCircuit::new(8); +```c +struct PsiQuantumCircuit circuit = psi_new_quantum_circuit(8); // ... add gates ... -// Combine features as needed -let config = RuntimeConfig::new() - .structure_aware() - .simd() - .parallel(); +// combine features as needed +struct PsiRuntimeConfig config = psi_new_runtime_config(); +config.structure_aware = true; +config.simd = true; +config.parallel = true; + +const struct PsiVector* state = psi_compute_circuit_with_config(&circuit, config); + +// or use a predefined runtime +// psi_compute_circuit_with(&circuit, PSI_RUNTIME_SIMD_MT); -circuit.compute_with_config(config); +double probabilities[1 << 8]; +psi_circuit_probabilities(&circuit, probabilities); ``` -### parametric gates +parametric gates take their angles as extra arguments: -```rust -use std::f64::consts::PI; +```c +const double pi = 3.14159265358979323846; -circuit - .rx(0, PI / 4.0) // Rotation around X - .ry(0, PI / 3.0) // Rotation around Y - .rz(1, PI / 2.0) // Rotation around Z - .crz(0, 1, PI / 4.0); // Controlled-Rz +psi_apply_rx(&circuit, 0, pi / 4.0); // rotation around x +psi_apply_ry(&circuit, 0, pi / 3.0); // rotation around y +psi_apply_rz(&circuit, 1, pi / 2.0); // rotation around z +psi_apply_crz(&circuit, 0, 1, pi / 4.0); // controlled-rz ``` -### custom gates +custom gates come from either a list of operations or a row-major matrix, and get applied to whichever qubits you hand them: -```rust -use psi::{CustomGateBuilder, CustomGate, complex, matrix}; +```c +// from operations +struct PsiCompositeGateOp bell_ops[] = { + { PSI_OP_H, { 0 }, 1 }, + { PSI_OP_CNOT, { 0, 1 }, 2 }, +}; +struct PsiCustomGate bell = psi_new_custom_gate_from_composite("BELL", 2, bell_ops, 2); -// From operations -let bell_gate = CustomGateBuilder::new("BELL", 2) - .h(0) - .cnot(0, 1) - .build(); +// from a unitary matrix +struct PsiCustomGate sqrt_x = psi_new_custom_gate_from_matrix( + "SQRT_X", psi_matrix(2, 2, psi_new_complex(0.5, 0.5), psi_new_complex(0.5, -0.5), + psi_new_complex(0.5, -0.5), psi_new_complex(0.5, 0.5))); -// From a unitary matrix -let sqrt_x_matrix = matrix!( - [complex!(0.5, 0.5), complex!(0.5, -0.5)]; - [complex!(0.5, -0.5), complex!(0.5, 0.5)] -); -let sqrt_x = CustomGate::from_matrix("√X", sqrt_x_matrix); +size_t bell_targets[] = { 0, 1 }; +psi_apply_custom(&circuit, bell, bell_targets, 2); + +size_t sqrt_x_targets[] = { 2 }; +psi_apply_custom(&circuit, sqrt_x, sqrt_x_targets, 1); ``` -## running tests +and for noise, you turn a computed state into a density matrix and work on that: -```bash -cargo run --release --example tester # All tests -cargo run --release --example tester -- clifford -cargo run --release --example tester -- non-clifford -cargo run --release --example tester -- kernels -cargo run --release --example tester -- simd -cargo run --release --example tester -- bench -cargo run --release --example tester -- help +```c +struct PsiQuantumCircuit circuit = psi_new_quantum_circuit(1); +psi_apply_h(&circuit, 0); +const struct PsiVector* state = psi_compute_circuit(&circuit); + +// create a density matrix from the circuit state +struct PsiDensityMatrix dm = psi_new_density_matrix_from_state(state->data, state->size); + +// apply noise to qubit 0 +struct PsiNoiseChannel noise = psi_depolarising_channel(0.05); +psi_apply_noise_channel(&dm, noise, 0); + +// check properties +printf("purity: %f\n", psi_purity_density_matrix(dm)); // 1.0 = pure, < 1.0 = mixed +printf("fidelity: %f\n", psi_fidelity_density_matrix(dm, state->data)); + +psi_free_noise_channel(&noise); +psi_free_density_matrix(&dm); +psi_free_quantum_circuit(&circuit); ``` -## disclaimer +## who frees what + +everything is a plain struct passed around by value, and anything you create with a `psi_new_` function has a `psi_free_` partner that takes a pointer to it. noise channels and density matrices are yours to free. + +the state vector you get back from `psi_compute_circuit` and friends is the exception. it belongs to the circuit, so don't free it. it's cached until you add another gate, and it stays valid until you reset or free the circuit. + +custom gates need a bit of care. `psi_new_custom_gate_from_matrix` takes over the matrix you pass in, and `psi_apply_custom` takes over the gate, which then gets freed along with the circuit. so make a fresh custom gate every time you apply one rather than reusing the same one. + +## caveats -this project is under active development. features and apis may change. +psi is still under active development, so expect the api to keep moving. the avx2 and avx-512 paths also haven't been run on real x86 hardware yet. so far only the neon path has. ## license -this project is made available under the apache license, version 2.0, allowing free use, modification, and distribution with proper attribution. community contributions, improvements, and research collaborations are encouraged. full licensing terms can be found in [license](LICENSE). +psi is licensed under the apache license, version 2.0, so you're free to use, modify and distribute it as long as you keep the attribution. contributions, improvements and research collaborations are all welcome. the full terms are in [LICENSE](LICENSE). |
