use std::time::{Duration, Instant};
use crate::control::{Control, Stage};
use crate::diag::Diagnostics;
use crate::error::{Error, Result};
use crate::field::{Engine, ScratchPool, SesField, SimdLevel, SurfaceKind};
use crate::geom::Sphere;
use crate::mesh::{self, Mesh, extract, post};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum Quality {
Draft,
Low,
#[default]
Medium,
High,
Ultra,
}
impl Quality {
pub const ALL: [Quality; 5] = [
Quality::Draft,
Quality::Low,
Quality::Medium,
Quality::High,
Quality::Ultra,
];
pub fn spacing(self) -> f64 {
match self {
Self::Draft => 1.0,
Self::Low => 0.7,
Self::Medium => 0.5,
Self::High => 0.25,
Self::Ultra => 0.1,
}
}
pub fn name(self) -> &'static str {
match self {
Self::Draft => "draft",
Self::Low => "low",
Self::Medium => "medium",
Self::High => "high",
Self::Ultra => "ultra",
}
}
pub fn from_name(name: &str) -> Option<Self> {
Self::ALL
.into_iter()
.find(|q| q.name().eq_ignore_ascii_case(name.trim()))
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub enum Resolution {
Spacing(f64),
Quality(Quality),
Density(f64),
}
pub const VERTICES_PER_AREA_H2: f64 = 1.5;
impl Resolution {
pub fn spacing(self) -> f64 {
match self {
Self::Spacing(h) => h,
Self::Quality(q) => q.spacing(),
Self::Density(d) => (VERTICES_PER_AREA_H2 / d).sqrt(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum RefineMode {
#[default]
Exact,
Linear,
}
impl RefineMode {
pub fn name(self) -> &'static str {
match self {
Self::Exact => "exact",
Self::Linear => "linear",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum CavityMode {
#[default]
Keep,
Remove,
Only,
}
impl CavityMode {
pub fn name(self) -> &'static str {
match self {
Self::Keep => "keep",
Self::Remove => "remove",
Self::Only => "only",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum NormalMode {
#[default]
Analytic,
FaceAverage,
None,
}
impl NormalMode {
pub fn name(self) -> &'static str {
match self {
Self::Analytic => "analytic",
Self::FaceAverage => "face-average",
Self::None => "none",
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct SurfaceParams {
pub kind: SurfaceKind,
pub probe_radius: f64,
pub resolution: Resolution,
pub refine: RefineMode,
pub brick_size: usize,
pub simd: SimdLevel,
pub cavities: CavityMode,
pub min_cavity_volume: f64,
pub min_component_area: f64,
pub normals: NormalMode,
pub max_memory: Option<u64>,
pub smoothing: u32,
}
impl Default for SurfaceParams {
fn default() -> Self {
Self::ses(1.4)
}
}
impl SurfaceParams {
pub fn ses(probe_radius: f64) -> Self {
Self {
kind: SurfaceKind::Ses,
probe_radius,
resolution: Resolution::Quality(Quality::Medium),
refine: RefineMode::Exact,
brick_size: 10,
simd: SimdLevel::Auto,
cavities: CavityMode::Keep,
min_cavity_volume: 0.0,
min_component_area: 0.0,
normals: NormalMode::Analytic,
max_memory: None,
smoothing: 0,
}
}
pub fn sas(probe_radius: f64) -> Self {
Self {
kind: SurfaceKind::Sas,
..Self::ses(probe_radius)
}
}
pub fn vdw() -> Self {
Self {
kind: SurfaceKind::Vdw,
..Self::ses(0.0)
}
}
#[must_use]
pub fn with_spacing(mut self, spacing: f64) -> Self {
self.resolution = Resolution::Spacing(spacing);
self
}
#[must_use]
pub fn with_quality(mut self, quality: Quality) -> Self {
self.resolution = Resolution::Quality(quality);
self
}
#[must_use]
pub fn with_density(mut self, density: f64) -> Self {
self.resolution = Resolution::Density(density);
self
}
#[must_use]
pub fn with_max_memory(mut self, bytes: u64) -> Self {
self.max_memory = Some(bytes);
self
}
#[must_use]
pub fn with_refine(mut self, refine: RefineMode) -> Self {
self.refine = refine;
self
}
#[must_use]
pub fn with_brick_size(mut self, cells: usize) -> Self {
self.brick_size = cells;
self
}
#[must_use]
pub fn with_simd(mut self, simd: SimdLevel) -> Self {
self.simd = simd;
self
}
#[must_use]
pub fn with_cavities(mut self, mode: CavityMode) -> Self {
self.cavities = mode;
self
}
#[must_use]
pub fn with_min_cavity_volume(mut self, volume: f64) -> Self {
self.min_cavity_volume = volume;
self
}
#[must_use]
pub fn with_min_component_area(mut self, area: f64) -> Self {
self.min_component_area = area;
self
}
#[must_use]
pub fn with_smoothing(mut self, rounds: u32) -> Self {
self.smoothing = rounds;
self
}
#[must_use]
pub fn with_normals(mut self, normals: NormalMode) -> Self {
self.normals = normals;
self
}
pub fn spacing(&self) -> f64 {
self.resolution.spacing()
}
pub fn effective_probe(&self) -> f64 {
if self.kind == SurfaceKind::Vdw {
0.0
} else {
self.probe_radius
}
}
pub fn validate(&self) -> Result<()> {
if let Resolution::Density(d) = self.resolution
&& !(d.is_finite() && d > 0.0)
{
return Err(Error::InvalidInput(format!(
"vertex density must be finite and > 0, got {d}"
)));
}
let h = self.spacing();
if !(h.is_finite() && (0.01..=10.0).contains(&h)) {
return Err(Error::InvalidInput(format!(
"grid spacing must be within 0.01..=10 Å, got {h}"
)));
}
let p = self.probe_radius;
if self.kind != SurfaceKind::Vdw && !(p.is_finite() && (0.0..=100.0).contains(&p)) {
return Err(Error::InvalidInput(format!(
"probe radius must be within 0..=100 Å, got {p}"
)));
}
for (name, v) in [
("minimum cavity volume", self.min_cavity_volume),
("minimum component area", self.min_component_area),
] {
if !(v.is_finite() && v >= 0.0) {
return Err(Error::InvalidInput(format!(
"{name} must be finite and >= 0, got {v}"
)));
}
}
if !(2..=32).contains(&self.brick_size) {
return Err(Error::InvalidInput(format!(
"brick size must be 2..=32 cells, got {}",
self.brick_size
)));
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Timings {
pub geometry: Duration,
pub classify: Duration,
pub mesh: Duration,
pub assemble: Duration,
pub measure: Duration,
}
impl Timings {
pub fn total(&self) -> Duration {
self.geometry + self.classify + self.mesh + self.assemble + self.measure
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct SurfaceStats {
pub spheres: usize,
pub kind: SurfaceKind,
pub spacing: f64,
pub touched_bricks: usize,
pub surface_bricks: usize,
pub vertices: usize,
pub triangles: usize,
pub area: f64,
pub volume: f64,
pub components: usize,
pub cavities: usize,
pub removed_components: usize,
pub euler: i64,
pub refine_evaluations: u64,
pub simd: &'static str,
pub timings: Timings,
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct SurfaceOutput {
pub mesh: Mesh,
pub components: Vec<mesh::Component>,
pub stats: SurfaceStats,
pub diagnostics: Diagnostics,
}
pub fn compute_surface(spheres: &[Sphere], params: &SurfaceParams) -> Result<SurfaceOutput> {
compute_surface_with(spheres, params, &Control::new())
}
pub fn compute_surface_with(
spheres: &[Sphere],
params: &SurfaceParams,
control: &Control<'_>,
) -> Result<SurfaceOutput> {
run(spheres, params, control, &ScratchPool::default())
}
#[derive(Debug)]
pub struct SurfaceEngine {
params: SurfaceParams,
pool: ScratchPool,
}
impl SurfaceEngine {
pub fn new(params: SurfaceParams) -> Result<Self> {
params.validate()?;
Ok(Self {
params,
pool: ScratchPool::default(),
})
}
pub fn params(&self) -> &SurfaceParams {
&self.params
}
pub fn compute(&mut self, spheres: &[Sphere]) -> Result<SurfaceOutput> {
self.compute_with(spheres, &Control::new())
}
pub fn compute_with(
&mut self,
spheres: &[Sphere],
control: &Control<'_>,
) -> Result<SurfaceOutput> {
run(spheres, &self.params, control, &self.pool)
}
}
pub fn estimate_memory(
surface_bricks: usize,
brick_size: usize,
spacing: f64,
spheres: usize,
) -> (u64, u64) {
let side = brick_size as f64 * spacing;
let area = surface_bricks as f64 * 0.7 * side * side;
let triangles = 2.0 * VERTICES_PER_AREA_H2 * area / (spacing * spacing);
(
triangles as u64,
(triangles * 150.0 + spheres as f64 * 800.0) as u64,
)
}
fn select_components(
mesh: &mut Mesh,
vertex_component: &mut Vec<u32>,
components: &mut Vec<mesh::Component>,
params: &SurfaceParams,
) -> usize {
let mut keep: Vec<bool> = components
.iter()
.map(|c| {
let by_mode = match params.cavities {
CavityMode::Keep => true,
CavityMode::Remove => !c.is_cavity(),
CavityMode::Only => c.is_cavity(),
};
by_mode
&& !(c.is_cavity() && -c.volume < params.min_cavity_volume)
&& c.area >= params.min_component_area
})
.collect();
let removed: Vec<bool> = keep.iter().map(|k| !k).collect();
if removed.iter().any(|&r| r) {
let inner = post::enclosed_by(mesh, vertex_component, components, &removed);
for (k, i) in keep.iter_mut().zip(inner) {
*k &= !i;
}
}
let n = keep.iter().filter(|k| !**k).count();
post::retain_components(mesh, vertex_component, components, &keep);
n
}
fn run(
spheres: &[Sphere],
params: &SurfaceParams,
control: &Control<'_>,
pool: &ScratchPool,
) -> Result<SurfaceOutput> {
params.validate()?;
control.check()?;
let mut timings = Timings::default();
let mut clock = Instant::now();
let mut lap = |slot: &mut Duration| {
let now = Instant::now();
*slot = now - clock;
clock = now;
};
control.report(Stage::Geometry, 0, 1);
let field = SesField::new_with(spheres, params.effective_probe(), params.kind, control)?;
let kind = field.kind();
let engine = Engine::new(field, params.spacing(), params.brick_size, params.simd)?;
control.report(Stage::Geometry, 1, 1);
lap(&mut timings.geometry);
control.report(Stage::Classify, 0, 1);
let (touched, bricks) = engine.surface_bricks()?;
control.check()?;
if let Some(limit) = params.max_memory {
let (triangles, bytes) = estimate_memory(
bricks.len(),
params.brick_size,
params.spacing(),
spheres.len(),
);
if bytes > limit {
return Err(Error::ResourceLimit {
what: format!(
"estimated mesh memory ({bytes} bytes for about {triangles} triangles at {} Å)",
params.spacing()
),
limit,
});
}
}
control.report(Stage::Classify, 1, 1);
lap(&mut timings.classify);
let parts = engine.map_bricks_with(&bricks, control, Stage::Mesh, pool, |key, values| {
extract::mesh_brick(&engine, key, values, params.refine)
})?;
lap(&mut timings.mesh);
control.report(Stage::Assemble, 0, 1);
let refine_evaluations = parts.iter().map(|p| p.evals).sum();
let mesh = extract::assemble(&bricks, &parts)?;
drop(parts);
control.check()?;
control.report(Stage::Assemble, 1, 1);
lap(&mut timings.assemble);
control.report(Stage::Measure, 0, 1);
let (check, edges) = mesh::validate_with(&mesh, None);
let edges = match edges {
Some(edges) if check.is_ok() => edges,
_ => {
return Err(Error::Internal(format!(
"mesh failed validation: {check:?}"
)));
}
};
control.check()?;
let (mut vertex_component, mut components) = mesh::components_with(&mesh, &edges);
drop(edges);
let mut mesh = mesh;
post::group_by_component(&mut mesh, &vertex_component, &mut components);
let removed_components =
select_components(&mut mesh, &mut vertex_component, &mut components, params);
if params.smoothing > 0 {
post::smooth_and_project(&mut mesh, &engine.field, spheres, params.smoothing);
let check = mesh::validate(&mesh);
if !check.is_ok() {
return Err(Error::Internal(format!(
"smoothed mesh failed validation: {check:?}"
)));
}
let origin = mesh
.positions
.first()
.map_or([0.0; 3], |p| p.map(f64::from));
for c in &mut components {
let (mut area, mut volume) = (0.0, 0.0);
for t in &mesh.triangles[c.first_triangle..c.first_triangle + c.triangles] {
let (a, v) = mesh::triangle_area_volume(&mesh, *t, origin);
area += a;
volume += v;
}
c.area = area;
c.volume = volume;
}
}
match params.normals {
NormalMode::Analytic => {}
NormalMode::FaceAverage => post::face_average_normals(&mut mesh),
NormalMode::None => mesh.normals = Vec::new(),
}
mesh.vertex_component = vertex_component;
control.report(Stage::Measure, 1, 1);
lap(&mut timings.measure);
let stats = SurfaceStats {
spheres: spheres.len(),
kind,
spacing: params.spacing(),
touched_bricks: touched,
surface_bricks: bricks.len(),
vertices: mesh.vertex_count(),
triangles: mesh.triangle_count(),
area: components.iter().map(|c| c.area).sum(),
volume: components.iter().map(|c| c.volume).sum(),
components: components.len(),
cavities: components.iter().filter(|c| c.is_cavity()).count(),
removed_components,
euler: components.iter().map(|c| c.euler).sum(),
refine_evaluations,
simd: engine.simd_name(),
timings,
};
Ok(SurfaceOutput {
mesh,
components,
stats,
diagnostics: Diagnostics::new(),
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::control::Progress;
#[cfg(feature = "parallel")]
use crate::export::obj::{ObjOptions, write_obj};
use proptest::prelude::*;
use sesmesh_testkit::clusters::{
Cluster, Rng, cage, cluster_strategy, collinear, cubic_lattice, random_box, random_chain,
with_duplicates,
};
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
fn spheres(c: &Cluster) -> Vec<Sphere> {
c.centers
.iter()
.zip(&c.radii)
.map(|(¢er, &radius)| Sphere::new(center, radius))
.collect()
}
#[cfg(feature = "parallel")]
fn obj_bytes(out: &SurfaceOutput) -> Vec<u8> {
let mut buf = Vec::new();
write_obj(&mut buf, &out.mesh, &ObjOptions::default()).unwrap();
buf
}
#[cfg(feature = "parallel")]
#[test]
fn thread_count_does_not_change_output() {
let c = random_chain(&mut Rng::new(11), 60);
let s = spheres(&c);
let params = SurfaceParams::ses(c.probe).with_spacing(0.3);
let run = |threads| {
rayon::ThreadPoolBuilder::new()
.num_threads(threads)
.build()
.unwrap()
.install(|| compute_surface(&s, ¶ms).unwrap())
};
let one = run(1);
assert!(one.stats.triangles > 1000);
let bytes = obj_bytes(&one);
for threads in [2, 4, 7] {
let other = run(threads);
assert_eq!(other.mesh, one.mesh, "{threads} threads");
assert_eq!(obj_bytes(&other), bytes, "{threads} threads");
}
}
#[test]
fn robustness_corpus() {
let cases = [
cubic_lattice(4, 3.0, 1.6, 1.4),
cage(6.0, 1.5, 1.4),
collinear(8, 2.0, 1.5, 1.4),
with_duplicates(random_box(&mut Rng::new(3), 30, 10.0), 4),
random_chain(&mut Rng::new(9), 50),
];
for (k, c) in cases.iter().enumerate() {
for kind in [SurfaceKind::Ses, SurfaceKind::Sas, SurfaceKind::Vdw] {
let mut p = SurfaceParams::ses(c.probe).with_spacing(0.4);
p.kind = kind;
let out = compute_surface(&spheres(c), &p)
.unwrap_or_else(|e| panic!("case {k} {kind:?}: {e}"));
assert!(out.stats.triangles > 0, "case {k} {kind:?}");
}
}
let mut c = random_chain(&mut Rng::new(4), 20);
for p in &mut c.centers {
p[0] += 1.0e4;
}
compute_surface(&spheres(&c), &SurfaceParams::ses(1.4).with_spacing(0.5)).unwrap();
for probe in [0.1, 10.0] {
compute_surface(&spheres(&c), &SurfaceParams::ses(probe).with_spacing(0.5)).unwrap();
}
}
#[test]
fn far_coordinates_and_huge_extents() {
let c = random_chain(&mut Rng::new(31), 30);
let near = spheres(&c);
let offset = [1.0e4, -2.0e4, 1.5e4];
let far: Vec<Sphere> = near
.iter()
.map(|s| Sphere::new([0, 1, 2].map(|k| s.center[k] + offset[k]), s.radius))
.collect();
let params = SurfaceParams::ses(c.probe).with_spacing(0.5);
let a = compute_surface(&near, ¶ms).unwrap();
let b = compute_surface(&far, ¶ms).unwrap();
assert_ne!(b.stats.simd, "scalar-f64");
assert!(a.stats.vertices.abs_diff(b.stats.vertices) <= 4);
assert!((a.stats.area - b.stats.area).abs() < 1e-4 * a.stats.area);
assert!((a.stats.volume - b.stats.volume).abs() < 1e-4 * a.stats.volume);
let mut pair = near.clone();
pair.extend(
near.iter()
.map(|s| Sphere::new([s.center[0] + 5000.0, s.center[1], s.center[2]], s.radius)),
);
let p = compute_surface(&pair, ¶ms).unwrap();
assert_eq!(p.stats.simd, "scalar-f64");
assert_eq!(p.stats.components, 2 * a.stats.components);
assert!((p.stats.area - 2.0 * a.stats.area).abs() < 1e-4 * a.stats.area);
}
#[test]
fn cancellation_is_prompt() {
let c = random_chain(&mut Rng::new(21), 400);
let s = spheres(&c);
let params = SurfaceParams::ses(c.probe).with_spacing(0.25);
for (stage, after) in [(Stage::Geometry, 0), (Stage::Classify, 0), (Stage::Mesh, 1)] {
let flag = AtomicBool::new(false);
let set_at = Mutex::new(None::<Instant>);
let cb = |p: Progress| {
if p.stage == stage && p.done >= after && !flag.load(Ordering::Relaxed) {
*set_at.lock().unwrap() = Some(Instant::now());
flag.store(true, Ordering::Relaxed);
}
};
let control = Control::new().with_cancel(&flag).with_progress(&cb);
let r = compute_surface_with(&s, ¶ms, &control);
let latency = set_at.lock().unwrap().expect("flag set").elapsed();
assert!(
matches!(r, Err(Error::Cancelled)),
"{stage:?}: {:?}",
r.map(|o| o.stats)
);
let bound = if cfg!(debug_assertions) { 2.0 } else { 0.1 };
assert!(latency.as_secs_f64() < bound, "{stage:?}: {latency:?}");
}
}
#[test]
fn progress_covers_every_stage() {
let c = random_chain(&mut Rng::new(22), 120);
let reports = Mutex::new(Vec::new());
let cb = |p: Progress| reports.lock().unwrap().push(p);
let params = SurfaceParams::ses(c.probe).with_spacing(0.3);
let out = compute_surface_with(&spheres(&c), ¶ms, &Control::new().with_progress(&cb))
.unwrap();
let reports = reports.into_inner().unwrap();
let mut order: Vec<Stage> = Vec::new();
for p in &reports {
assert!(p.done <= p.total, "{p:?}");
if order.last() != Some(&p.stage) {
order.push(p.stage);
}
}
use Stage::*;
assert_eq!(order, [Geometry, Classify, Mesh, Assemble, Measure]);
for stage in order {
let total = reports.iter().find(|p| p.stage == stage).unwrap().total;
assert!(reports.iter().any(|p| p.stage == stage && p.done == 0));
assert!(reports.iter().any(|p| p.stage == stage && p.done == total));
}
let mesh_total = reports.iter().find(|p| p.stage == Mesh).unwrap().total;
assert_eq!(mesh_total, out.stats.surface_bricks as u64);
assert!(reports.iter().filter(|p| p.stage == Mesh).count() > 10);
}
#[test]
fn engine_matches_one_shot() {
let params = SurfaceParams::ses(1.4).with_spacing(0.35);
let mut engine = SurfaceEngine::new(params.clone()).unwrap();
for (seed, n) in [(1, 40), (2, 15), (3, 70), (4, 40)] {
let c = random_chain(&mut Rng::new(seed), n);
let s = spheres(&c);
let a = engine.compute(&s).unwrap();
let b = compute_surface(&s, ¶ms).unwrap();
assert_eq!(a.mesh, b.mesh, "frame {seed}");
}
assert!(SurfaceEngine::new(SurfaceParams::ses(1.4).with_spacing(-1.0)).is_err());
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(24))]
#[test]
fn random_clusters_mesh_cleanly(
c in cluster_strategy(25),
h in 0.25f64..0.9,
brick in 2usize..12,
) {
let p = SurfaceParams::ses(c.probe).with_spacing(h).with_brick_size(brick);
let out = compute_surface(&spheres(&c), &p);
prop_assert!(out.is_ok(), "{:?}", out.err());
}
}
}