The Library
The engine behind the CLI as a crate: sesmesh = "1". Every snippet on this page compiles against 1.1.0; the API reference documents every public item.
Add the crate
[dependencies]
sesmesh = "1"
# single-threaded, no gzip or TOML radii (e.g. for WASM):
# sesmesh = { version = "1", default-features = false }| Feature | Default | Adds |
|---|---|---|
parallel | on | rayon: bricks and stages on every core of the current pool |
gzip | on | gzip-compressed input and output (.gz) |
radii-file | on | radius rules from TOML files |
hip | off | GPU back end for AMD GPUs through HIP: building needs ROCm's hipcc; the program still runs where ROCm is missing (GPU) |
cuda | off | GPU back end for NVIDIA GPUs through CUDA: building needs CUDA's nvcc; the program still runs where the NVIDIA driver is missing (GPU) |
MSRV 1.89. Semantic versioning from 1.0; option structs are #[non_exhaustive]:
build them from their constructors or Default and assign fields.
Quick start
Spheres in, a validated mesh and its statistics out:
use sesmesh::{compute_surface, mesh, Sphere, SurfaceParams};
let atoms = [Sphere::new([0.0, 0.0, 0.0], 1.7), Sphere::new([3.0, 0.0, 0.0], 1.7)];
let out = compute_surface(&atoms, &SurfaceParams::ses(1.4).with_spacing(0.3))?;
assert!(mesh::validate(&out.mesh).is_ok()); // closed, oriented, manifold
assert_eq!(out.stats.components, 1);Sphere is a centre and a radius in Å; radius 0 means “ignore”.
compute_surface returns a SurfaceOutput with the mesh, its
components, statistics and diagnostics.
From a file
Read, select atoms, assign radii, mesh, write. Selection follows the CLI defaults (first model, no waters or hydrogens, highest-occupancy alt-locs).
use sesmesh::export::ply::{PlyOptions, write_ply_path};
use sesmesh::io::{ReadOptions, read_path};
use sesmesh::radii::{RadiusOptions, assign};
use sesmesh::{Diagnostics, Quality, Selection, Sphere, SurfaceParams, compute_surface};
fn main() -> sesmesh::Result<()> {
let structure = read_path("4hhb.cif.gz", &ReadOptions::default())?;
let mut diags = Diagnostics::new();
let atoms = structure.select(&Selection::default(), &mut diags)?;
let radii = assign(&atoms, &RadiusOptions::default(), &mut diags)?;
let spheres = Sphere::from_atoms(&atoms, &radii)?;
let params = SurfaceParams::ses(1.4).with_quality(Quality::High);
let out = compute_surface(&spheres, ¶ms)?;
for c in &out.components {
let kind = if c.is_cavity() { "cavity" } else { "surface" };
println!("{kind}: {} triangles, {:.1} Ų, {:.1} ų", c.triangles, c.area, c.volume);
}
write_ply_path("4hhb.ply", &out.mesh, &PlyOptions::default())?;
Ok(())
}Readers: io::read_path, io::read_bytes (PDB, mmCIF, XYZ, PQR,
gzip detected by magic bytes); biological assemblies with
ReadOptions::assembly. Radius sets: Bondi (default), Alvarez, ProtOr,
uniform, or custom rules (radii::RadiusOptions).
Parameters
use sesmesh::mesh::Decimation;
use sesmesh::{CavityMode, NormalMode, SurfaceParams};
let params = SurfaceParams::ses(1.4)
.with_spacing(0.25) // grid spacing in Å
.with_cavities(CavityMode::Remove) // drop internal cavities
.with_smoothing(2) // Taubin rounds + exact re-projection
.with_remove_fragments(true) // drop sub-grid fragments (1.1)
.with_decimation(Decimation::ratio(0.25).with_max_error(0.05))
.with_max_memory(4 << 30) // 4 GiB estimate limit …
.with_auto_coarsen(true) // … coarsen instead of failing
.with_normals(NormalMode::Analytic);| Builder | Sets |
|---|---|
SurfaceParams::ses(r), ::sas(r), ::vdw() | Surface kind and probe radius |
with_spacing(h), with_quality(Quality::High), with_density(d) | Resolution: spacing in Å, preset, or vertices per Ų |
with_cavities(CavityMode::…) | Keep (exact SES), Remove, Only; plus with_min_cavity_volume, with_min_component_area |
with_remove_fragments(true) | Drop sub-grid fragments: tiny solid components without a convex atom patch, cut off by the grid from re-entrant sheets thinner than the spacing (off by default, since 1.1) |
with_smoothing(n) | Taubin rounds, then exact re-projection |
with_decimation(Decimation::…) | ratio, with_max_triangles, with_max_error (Å) |
with_max_memory(bytes), with_auto_coarsen(true) | Memory guard: refuse, or coarsen until the estimate fits |
with_normals(NormalMode::…) | Analytic, FaceAverage, None |
with_refine, with_simd, with_brick_size | Vertex placement, kernel instruction set, brick edge |
with_backend(Backend::…) | Cpu (default), Auto, Backend::hip(device), Backend::cuda(device): where the mesh stage runs (GPU) |
What you get back
| Field | Content |
|---|---|
out.mesh.positions, .normals | Vec<[f32; 3]>: vertices on the surface, unit normals into the solvent |
out.mesh.triangles | Vec<[u32; 3]>, counter-clockwise seen from outside, grouped by component |
out.mesh.vertex_atom, .vertex_patch, .vertex_component | Nearest input sphere, patch (PatchKind: convex, saddle, concave), component index |
out.components | Per component: vertices, triangles, area, signed volume (cavities negative), Euler characteristic, first triangle |
out.stats | Totals, spacing used, removed fragments, decimation, the memory guard's estimate, refine evaluations, SIMD kernel, stage timings |
Per-vertex colours and per-atom areas, the way the CLI computes them:
let structure = read_path("1crn.cif", &ReadOptions::default())?;
let mut diags = Diagnostics::new();
let atoms = structure.select(&Selection::default(), &mut diags)?;
let radii = assign(&atoms, &RadiusOptions::default(), &mut diags)?;
let out = compute_surface(&Sphere::from_atoms(&atoms, &radii)?, &SurfaceParams::default())?;
// Colour each vertex by the element of its nearest atom.
let palette = ElementPalette::default();
let elements: Vec<_> = atoms.iter().map(|a| a.element).collect();
let mut options = PlyOptions::default();
options.vertex_colors = out
.mesh
.vertex_atom
.iter()
.map(|&i| palette.color(elements[i as usize]))
.collect();
write_ply_path("1crn.ply", &out.mesh, &options)?;
// SES area per atom (Ų), from the triangles nearest to it.
let areas = mesh::atom_areas(&out.mesh, atoms.len());
let exposed = areas.iter().filter(|&&a| a > 1.0).count();
println!("{exposed} of {} atoms expose more than 1 Ų", atoms.len());
assert!(mesh::validate(&out.mesh).is_ok());Engines & trajectories
SurfaceEngine validates parameters once and keeps per-thread buffers between
calls; Control adds cancellation (an AtomicBool, honoured within
about 100 ms) and progress callbacks per stage.
use std::sync::atomic::AtomicBool;
use sesmesh::{Control, Progress, Sphere, Stage, SurfaceEngine, SurfaceParams};
fn main() -> sesmesh::Result<()> {
// Parameters are validated once; per-thread buffers are kept between
// frames.
let mut engine = SurfaceEngine::new(SurfaceParams::ses(1.4).with_spacing(0.4))?;
let cancel = AtomicBool::new(false);
let progress = |p: Progress| {
if p.stage == Stage::Mesh && p.done == p.total {
eprint!(".");
}
};
let control = Control::new().with_cancel(&cancel).with_progress(&progress);
for frame in 0..10 {
// Two atoms moving apart: one component, then two.
let d = 2.5 + 0.6 * f64::from(frame);
let spheres = [Sphere::new([0.0; 3], 1.7), Sphere::new([d, 0.0, 0.0], 1.7)];
let out = engine.compute_with(&spheres, &control)?;
println!(
"frame {frame}: distance {d:.1} Å → {} component(s), area {:.2} Ų",
out.stats.components, out.stats.area
);
}
eprintln!();
Ok(())
}Field queries
SesField answers point queries on the exact surface function: signed
distance (negative inside), the closest surface point, the normal and the patch with its
atoms — useful for docking scores, probes or your own mesher.
use sesmesh::field::Patch;
use sesmesh::{SesField, Sphere, SurfaceKind};
fn main() -> sesmesh::Result<()> {
let spheres = [
Sphere::new([0.0, 0.0, 0.0], 1.7),
Sphere::new([3.0, 0.0, 0.0], 1.7),
];
let field = SesField::new(&spheres, 1.4, SurfaceKind::Ses)?;
// Negative inside the molecule, 0 on the SES, positive in the solvent.
for point in [
[-1.7, 0.0, 0.0],
[1.5, 1.0, 0.0],
[1.5, 1.5, 0.0],
[0.0, 3.0, 0.0],
] {
let s = field.sample(point);
let patch = match s.patch {
Patch::Convex { atom } => format!("convex (atom {atom})"),
Patch::Saddle { atoms } => format!("saddle (atoms {atoms:?})"),
Patch::Concave { atoms } => format!("concave (atoms {atoms:?})"),
_ => "solvent".to_string(),
};
println!(
"{point:?}: F = {:+.4} Å, {patch}, normal {:?}",
s.value,
s.normal.map(|n| n.map(|c| (c * 1000.0).round() / 1000.0))
);
}
Ok(())
}Threads & determinism
sesmesh runs in the current rayon pool. The result is bit-identical for any pool size, so you can trade cores for latency without changing a single byte of output.
let spheres = [Sphere::new([0.0; 3], 1.7), Sphere::new([3.0, 0.0, 0.0], 1.7)];
let params = SurfaceParams::ses(1.4).with_spacing(0.3);
// sesmesh runs in the current rayon pool: limit it to four threads.
let pool = rayon::ThreadPoolBuilder::new().num_threads(4).build()?;
let out = pool.install(|| compute_surface(&spheres, ¶ms))?;
println!("{} triangles", out.stats.triangles);GPU back end
With the feature hip or cuda, the mesh stage can run on an AMD GPU
through ROCm or on an NVIDIA GPU through CUDA, with the same kernels. The device classifies the grid, gathers candidates and samples the field while the CPU threads
mesh. With the default exact refinement the output is the CPU back end's, byte for byte.
RefineMode::Fast also refines the vertices on the GPU, in f32, for previews:
same triangles, vertices as close to the surface, last bits different. Open the device once
with a SurfaceEngine (about 50 ms).
use sesmesh::{Backend, RefineMode, Sphere, SurfaceEngine, SurfaceParams};
let spheres = [Sphere::new([0.0; 3], 1.7), Sphere::new([3.0, 0.0, 0.0], 1.7)];
let params = SurfaceParams::ses(1.4)
.with_spacing(0.25)
.with_backend(Backend::Auto) // the GPU if one opens, else the CPU
.with_refine(RefineMode::Fast); // preview; Exact on the CPU
let mut engine = SurfaceEngine::new(params)?;
let out = engine.compute(&spheres)?;
println!("{} triangles on {}", out.stats.triangles, out.stats.device.as_deref().unwrap_or("the CPU"));Backend::Auto never fails for lack of a GPU; a GpuFallback warning
says why when a GPU runtime is installed but its device cannot be used.
Backend::hip(i) and Backend::cuda(i) fail instead
(Error::Backend); Auto tries HIP, then CUDA, then the CPU. The GPU
code is f32 and integer only. HIP is tested on an integrated RDNA 3.5 GPU (Radeon 8060S),
with code objects for ROCm's generic RDNA 2, 3 and 4 targets; CUDA on a GeForce RTX 2070
(sm_75), with a fat binary for compute capability 7.5 to 12.0.
Errors & warnings
Every fallible call returns sesmesh::Result. Error separates I/O,
parse errors (with line and column), invalid input, empty selections, resource limits,
cancellation and internal invariants. Non-fatal problems — unknown elements, missing
radii, discarded alt-locs — are collected in Diagnostics. The library never
prints.
match read_path("broken.pdb", &ReadOptions::default()) {
Ok(structure) => {
let mut diags = Diagnostics::new();
let _ = structure.select(&Selection::default(), &mut diags);
for w in diags.warnings() {
eprintln!("warning: {w}"); // e.g. unknown elements, alt-locs
}
}
Err(Error::Parse { line, message, .. }) => eprintln!("line {line:?}: {message}"),
Err(e) => eprintln!("error: {e}"),
}Cite
If sesmesh helps your work, please cite it, giving the version you used. Each release is archived on Zenodo with its own DOI:
@software{varetto_sesmesh,
author = {Varetto, Ugo},
title = {{sesmesh: Solvent Excluded Surface meshes for molecules}},
version = {1.3.2},
year = {2026},
publisher = {Zenodo},
doi = {10.5281/zenodo.24412360},
url = {https://doi.org/10.5281/zenodo.24412360}
}doi:10.5281/zenodo.24238836 stands for all versions and resolves to the latest. The same metadata is in CITATION.cff (GitHub: Cite this repository).
Where your work relies on a method sesmesh implements, please cite that method too:
- C. Quan, B. Stamm, “Mathematical analysis and calculation of molecular surfaces,” J. Comput. Phys. 322:760–782, 2016. doi:10.1016/j.jcp.2016.07.007
- M. L. Connolly, “Analytical molecular surface calculation,” J. Appl. Cryst. 16(5):548–558, 1983. doi:10.1107/S0021889883010985
- W. E. Lorensen, H. E. Cline, “Marching cubes: a high resolution 3D surface construction algorithm,” Comput. Graph. 21(4):163–169, 1987. doi:10.1145/37402.37422
- W. Schroeder, R. Maynard, B. Geveci, “Flying edges: a high-performance scalable isocontouring algorithm,” IEEE LDAV 2015. doi:10.1109/LDAV.2015.7348069
- G. Taubin, “A signal processing approach to fair surface design,” SIGGRAPH ’95, 351–358, 1995.
- M. Garland, P. S. Heckbert, “Surface simplification using quadric error metrics,” SIGGRAPH ’97, 209–216, 1997. doi:10.1145/258734.258849
- B. Lee, F. M. Richards, “The interpretation of protein structures: estimation of static accessibility,” J. Mol. Biol. 55(3):379–400, 1971.
Full reference list: specification §12.
API reference on docs.rs ↗