A high-performance Python library for Computational Surgery Theory.
Project description
pySurgery
pySurgery is a Python library for computational algebraic topology and computational surgery theory: it turns discrete data (CW/simplicial complexes, meshes, TDA pipelines) into integer invariants strong enough to go beyond Betti numbers—e.g. torsion, cup products, intersection forms, and (in key cases) homeomorphism classification signals.
If you’ve ever felt “persistent homology is informative, but not decisive,” pySurgery is aimed at the next layer of structure.
Why this exists
Most numerical linear-algebra approaches over $\mathbb{R}$ lose information that lives over $\mathbb{Z}$ (especially torsion). pySurgery focuses on exact and structure-aware invariants:
- Homology & cohomology over $\mathbb{Z}$ via Smith Normal Form (SNF) (captures torsion)
- Coefficient support for
Z,Q, andZ/pZ(including composite moduli via UCT decomposition) - Cup product (Alexander–Whitney) to extract intersection information
- Intersection forms for 4-manifolds (rank/signature/parity)
- Hooks for surgery-theoretic obstructions and higher-dimensional classification workflows
Quickstart
Install
Requires Python >= 3.10+.
Project metadata (including version and Python requirement) is defined in pyproject.toml.
Install from PyPI (recommended)
pip install pysurgery
PyPI package: https://pypi.org/project/pysurgery/
Install from source (development)
git clone https://github.com/gabe-rbo/pySurgery.git
cd pySurgery
pip install -e .
Optional dependency groups:
# Topological Data Analysis integration
pip install "pysurgery[tda]"
# Mesh integration
pip install "pysurgery[mesh]"
# ML-oriented integrations
pip install "pysurgery[ml]"
# Everything optional
pip install "pysurgery[all]"
Julia backend (optional, for large-scale exact integer computations)
pySurgery can offload some exact integer workloads to Julia (recommended for very large sparse exact-$\mathbb{Z}$ computations).
- Ensure
juliais on yourPATH - Install required Julia backend packages in your Julia environment:
import Pkg
Pkg.add("AbstractAlgebra")
Pkg.add("PrecompileTools")
Pkg.add("Graphs")
Pkg.add("SimpleWeightedGraphs")
Pkg.add("DelaunayTriangulation")
Pkg.add("Combinatorics")
For notebooks and benchmark scripts, you can eagerly warm up Julia-backed kernels once per process:
from pysurgery.bridge.julia_bridge import julia_engine
if julia_engine.available:
report = julia_engine.warmup()
print("Julia warm-up workloads:", len(report.get("completed", [])))
Examples and tutorials
A step-by-step interactive curriculum is provided in examples/ (Jupyter notebooks), covering topics from algebraic topology basics to surgery-theoretic workflows:
01_basic_homology_and_cohomology.ipynb— CW complexes, SNF, UCT02_intersection_forms.ipynb— 4D classification concepts, spin checks03_algebraic_surgery.ipynb— isotropic classes and algebraic surgery mechanics04_advanced_tda_and_surgery_theory.ipynb— raw data → GUDHI → cup product → intersection form05_omni_dimensional_homeomorphisms.ipynb— how classification behavior changes by dimension06_kirby_calculus_and_characteristic_classes.ipynb— characteristic classes & Kirby-style ideas07_fundamental_group_and_structure_set.ipynb— $\pi_1$ extraction, Whitehead data, and typed structure-set workflows08_certificate_workflows.ipynb— explicit homeomorphism witnesses, obstruction interference, and surgery planning09_branch_matrix_and_failure_modes.ipynb— success/impediment/inconclusive/surgery-required branch matrix10_witness_builder_reference.ipynb— witness-builder API reference and dispatcher coverage11_capstone_end_to_end_workflow.ipynb— one full problem-solving pipeline using the library end-to-end12_cube_surgery.ipynb— cube triangulation, homology extraction, and surgery-style 2D witness diagnostics13_homology_generators_small_figures.ipynb— five tiny complexes showing howH_0,H_1, andH_2generators are found and visualized
Mathematical basis
pySurgery bridges discrete geometry to topological classification using several key concepts.
1) Homology & cohomology via Smith Normal Form (over $\mathbb{Z}$)
When computing homology,
$$ H_n(X)=\ker(d_n)/\mathrm{im}(d_{n+1}) $$
floating-point linear algebra misses torsion. pySurgery implements Smith Normal Form over $\mathbb{Z}$ to recover:
- Betti ranks (free part)
- torsion coefficients (e.g. $\mathbb{Z}_k$ factors)
Cohomology is computed via the Universal Coefficient Theorem.
2) Alexander–Whitney cup product
To classify 4-manifolds, surfaces intersect—cup products encode that intersection.
Given cocycles $\alpha, \beta$:
$$ (\alpha \smile \beta)([v_0,\dots,v_4])=\alpha([v_0,v_1,v_2])\cdot\beta([v_2,v_3,v_4]). $$
Summing over a fundamental class yields intersection form entries.
pySurgery also provides simplicial cup-$i$ operations (i >= 0) for higher-order cochain interactions.
3) Intersection forms & 4D classification signals
For 4-manifolds, pySurgery constructs the intersection form $Q$, computes rank/signature/parity, and supports workflows inspired by Freedman-style classification (with attention to needed hypotheses/invariants).
4) Algebraic surgery
Given a class $x$ representing a “hole,” pySurgery supports algorithmic manipulations that mirror algebraic surgery operations—checking isotropy $Q(x,x)=0$, finding dual classes, and updating lattice data.
5) Characteristic classes & spin structures
pySurgery extracts characteristic-class information from intersection-form data; using Wu’s formula, it computes $w_2$ (mod 2) to test spin conditions.
6) High-dimensional structure signals
In dimensions $n \ge 5$, classification interacts with $\pi_1$, Whitehead torsion, and Wall’s surgery groups $L_n(\pi_1)$. pySurgery includes tooling aimed at discrete extraction of group presentations and surgery-sequence-adjacent invariants (where computationally feasible).
7) Fundamental-group generators: raw vs optimized
For source complexes with a 1-skeleton and 2-cells, extract_pi_1_with_traces(...) returns a typed presentation plus edge-path traces for the surviving generators.
You can choose the generator mode explicitly:
generator_mode="raw"— keep the full spanning-forest generator setgenerator_mode="optimized"— simplify the presentation and keep a reduced trace set
The result object records mode_used, backend_used, raw_generator_count, and optimized_generator_count so notebooks and benchmarks can compare the two modes directly.
Quick benchmark helper:
python scripts/benchmark_pi1_modes.py
python scripts/benchmark_pi1_modes.py --force-python
8) Dimension-aware behavior
- 2D: orientability/genus signals via low-dimensional homology
- 3D: homology-sphere style signals and 3-manifold context
- 4D: intersection forms + parity/signature style invariants
- 5D+: surgery-theoretic invariants and $\pi_1$-sensitive obstructions
8) Data-grounded optimal homology generators
For discrete simplicial data, pySurgery includes data-grounded generator extraction for $H_1$ (cycle representatives as edge-level elements of the input complex), with Julia-accelerated and Python fallback paths.
The generator/optimality pipeline follows the "Generators and Optimality" framework in:
- Tamal K. Dey and Yusu Wang, Computational Topology for Data Analysis.
Computational optimizations
Discrete topology can blow up combinatorially (e.g., large point clouds). pySurgery includes:
- Sparse fallbacks when exact dense integer work is too large
- NumPy/Numba acceleration for inner loops (e.g., cup product sweeps)
- Julia bridge for large exact-$\mathbb{Z}$ workloads when Python becomes the bottleneck
Approximate (floating-point) fallbacks exist in selected large/sparse workflows, but are opt-in where mathematically sensitive and emit explicit warnings when exact integer guarantees are weakened.
Exactness policy
pySurgery defaults to exact integer-topology workflows whenever practical.
- Default mode: exact-first (
allow_approx=Falsein APIs that expose it) - Approximate mode: explicitly opt in via
allow_approx=True - Warnings: approximate paths emit warnings when torsion/exact-cycle guarantees may be weakened
For mathematically rigorous classification/proof-oriented workflows, prefer exact mode and treat approximate mode as exploratory.
Example: exact vs approximate fundamental class extraction
from pysurgery.integrations.gudhi_bridge import simplex_tree_to_intersection_form
# Exact-first: raise if exact extraction cannot be completed.
q_exact = simplex_tree_to_intersection_form(st, allow_approx=False)
# Exploratory fallback: allows numerical approximation with warnings.
q_fast = simplex_tree_to_intersection_form(st, allow_approx=True)
Example: exact vs approximate dimension-aware homeomorphism analysis
from pysurgery.homeomorphism import analyze_homeomorphism_2d
# Exact-first classification attempt.
ok_exact, msg_exact = analyze_homeomorphism_2d(c1, c2, allow_approx=False)
# Permissive fallback for noisy/large pipelines.
ok_fast, msg_fast = analyze_homeomorphism_2d(c1, c2, allow_approx=True)
Homeomorphism witness builders
pysurgery.homeomorphism answers: "is a homeomorphism certified by invariants/obstructions?"
pysurgery.homeomorphism_witness goes further and returns a structured witness object when exact data is sufficient.
from pysurgery.homeomorphism_witness import build_homeomorphism_witness
res = build_homeomorphism_witness(c1=c1, c2=c2, dim=2)
if res.status == "success":
print(res.witness.kind) # e.g. "surface_classification"
print(res.witness.theorem) # theorem branch used
print(res.witness.certificates)
else:
print(res.reasoning)
print(res.missing_data)
Dimension-specific builders
from pysurgery.homeomorphism_witness import (
build_surface_homeomorphism_witness,
build_3d_homeomorphism_witness,
build_4d_homeomorphism_witness,
build_high_dim_homeomorphism_witness,
)
build_surface_homeomorphism_witness(...)(2D)build_3d_homeomorphism_witness(...)(3D)build_4d_homeomorphism_witness(...)(Freedman branch)build_high_dim_homeomorphism_witness(...)(n >= 5, surgery-theoretic branch)
For n >= 5, an explicit completion certificate can be supplied via
homotopy_completion_certificate={"provided": True, "exact": True, "validated": True, ...}.
Certified success requires this certificate to be decision-ready (exact and validated).
Legacy homotopy_witness_hook inputs are still accepted and bridged for compatibility.
For nontrivial product groups, factor-wise Wall decompositions are exposed as structured surrogate certificates;
exact success still requires assembly-certified product-group obstruction data.
For 3D geometric-recognition completion, you can provide
recognition_certificate={"provided": True, "exact": True, "validated": True, ...}.
This allows exact success in non-Poincare branches when the certificate is decision-ready.
For high-dimensional nontrivial product groups, provide
product_assembly_certificate={"provided": True, "exact": True, "validated": True, ...}
to upgrade surrogate product decompositions into decision-ready assembly evidence.
4D explicit algebraic witness
In definite 4D cases, the witness may include an integer isometry matrix U (stored in witness.certificates["isometry_matrix"]) such that:
$$ U^T Q_1 U = Q_2. $$
This is an explicit algebraic certificate for the lattice isomorphism part of the classification branch.
Interpreting witness results
status="success": exact theorem/certificate path produced a witness.status="inconclusive": not enough exact data to construct a certified witness (checkmissing_data).status="surgery_required": obstruction branch indicates surgery-level impediment instead of direct witness construction.
witness.exact indicates whether the returned witness is exact-topology certified (True) or exploratory/heuristic (False).
Package layout
pysurgery/
├── core/
│ ├── cup_product.py
│ ├── complexes.py
│ ├── characteristic_classes.py
│ ├── exceptions.py
│ ├── fundamental_group.py
│ ├── group_rings.py
│ ├── intersection_forms.py
│ ├── k_theory.py
│ ├── kirby_calculus.py
│ ├── math_core.py
│ └── quadratic_forms.py
├── bridge/
│ ├── julia_bridge.py
│ └── surgery_backend.jl
├── integrations/
│ ├── gudhi_bridge.py
│ ├── trimesh_bridge.py
│ ├── pytorch_geometric_bridge.py
│ ├── jax_bridge.py
│ └── lean_export.py
Key modules:
-
pysurgery.core.complexes—CWComplex,ChainComplex -
pysurgery.core.intersection_forms— lattice math, parity checks, surgery engine -
pysurgery.core.math_core— SNF / exact integer computation core -
pysurgery.homeomorphism— dimension-aware analyzers -
pysurgery.homeomorphism_witness— explicit witness/certificate builders -
pysurgery.integrationsgudhi_bridge— TDA point clouds → topology objectstrimesh_bridge— meshes → topology objectspytorch_geometric_bridge— graph/ML integrationjax_bridge— differentiable / approximation-oriented integration ideas
Contributing
PRs are welcome—especially for:
- minimal examples (“one function call → one invariant” demos)
- improved docs around mathematical assumptions and failure modes
- performance improvements and additional exact-$\mathbb{Z}$ backends
- more datasets and reproducible example pipelines
If you’re unsure where to start, open an issue describing your use-case and dataset type.
Roadmap (selected)
- Non-abelian / twisted coefficient systems ($\pi_1$-sensitive homology)
- Deeper algebraic surgery tooling (Ranicki-style formulations)
- Learning on structure-set features via GNNs (experimental)
License
MIT License. See LICENSE.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file pysurgery-1.2.1.tar.gz.
File metadata
- Download URL: pysurgery-1.2.1.tar.gz
- Upload date:
- Size: 124.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
1f7fae1e96fd586b2727a37b791c46b1d3105fd77ecd3f61f108ef13041ae313
|
|
| MD5 |
2fe3bf6908fb8542dcda964a7d5b091a
|
|
| BLAKE2b-256 |
962b4dad910149a430c7b1a5a900a70326dbba36e98d6b017c3b0db373028d3d
|
File details
Details for the file pysurgery-1.2.1-py3-none-any.whl.
File metadata
- Download URL: pysurgery-1.2.1-py3-none-any.whl
- Upload date:
- Size: 106.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a351c6bf88f616a53138990ca05d228e682823d6dc7add1b23d1f6a01ed4939e
|
|
| MD5 |
a93e40e8d09be7ea8afe21830b86ced7
|
|
| BLAKE2b-256 |
18ff1661a0deeba12a54dd4de6cd1e4ac960eea21949b9f7809710dc9cfb7967
|