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 remove_fragments: bool,
pub normals: NormalMode,
pub max_memory: Option<u64>,
pub auto_coarsen: bool,
pub smoothing: u32,
pub decimation: Option<mesh::Decimation>,
}
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,
remove_fragments: false,
normals: NormalMode::Analytic,
max_memory: None,
auto_coarsen: false,
smoothing: 0,
decimation: None,
}
}
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_remove_fragments(mut self, on: bool) -> Self {
self.remove_fragments = on;
self
}
#[must_use]
pub fn with_auto_coarsen(mut self, on: bool) -> Self {
self.auto_coarsen = on;
self
}
#[must_use]
pub fn with_smoothing(mut self, rounds: u32) -> Self {
self.smoothing = rounds;
self
}
#[must_use]
pub fn with_decimation(mut self, decimation: mesh::Decimation) -> Self {
self.decimation = Some(decimation);
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}"
)));
}
if let Some(d) = &self.decimation {
if !(d.ratio.is_finite() && d.ratio > 0.0 && d.ratio <= 1.0) {
return Err(Error::InvalidInput(format!(
"decimation ratio must be within (0, 1], got {}",
d.ratio
)));
}
if d.max_error.is_nan() || d.max_error < 0.0 {
return Err(Error::InvalidInput(format!(
"decimation error bound must be >= 0, got {}",
d.max_error
)));
}
}
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 removed_fragments: usize,
pub decimation: Option<mesh::DecimationStats>,
pub euler: i64,
pub refine_evaluations: u64,
pub simd: &'static str,
pub estimated_triangles: Option<u64>,
pub estimated_memory: Option<u64>,
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)
}
}
const PEAK_FIXED: u64 = 16 << 20;
const PEAK_PER_SPHERE: u64 = 1_200;
const PEAK_PER_TRIANGLE: u64 = 150;
const PEAK_PER_TRIANGLE_DECIMATION: u64 = 50;
const PEAK_PER_TRIANGLE_SMOOTHING: u64 = 50;
fn peak_bytes(triangles: u64, spheres: usize, params: &SurfaceParams) -> u64 {
let mut per_triangle = PEAK_PER_TRIANGLE;
if params.decimation.is_some() {
per_triangle += PEAK_PER_TRIANGLE_DECIMATION;
}
if params.smoothing > 0 {
per_triangle += PEAK_PER_TRIANGLE_SMOOTHING;
}
PEAK_FIXED + spheres as u64 * PEAK_PER_SPHERE + triangles * per_triangle
}
const SAMPLE_BRICKS: usize = 512;
fn estimate_triangles(engine: &Engine, bricks: &[[i32; 3]], pool: &ScratchPool) -> u64 {
if bricks.is_empty() {
return 0;
}
let stride = bricks.len().div_ceil(SAMPLE_BRICKS);
let sample: Vec<[i32; 3]> = bricks.iter().step_by(stride).copied().collect();
let b = engine.lattice.b as usize;
let counts = engine.map_bricks_pooled(&sample, pool, |_, values| {
extract::brick_triangles(b, values) as f64
});
let total: f64 = counts.iter().sum();
if stride == 1 {
return total as u64;
}
let n = counts.len() as f64;
let mean = total / n;
let variance = counts.iter().map(|c| (c - mean).powi(2)).sum::<f64>() / (n - 1.0);
((mean + 2.0 * (variance / n).sqrt()) * bricks.len() as f64).ceil() as u64
}
const PILOT_SIDE: f64 = 5.0;
const EXTRAPOLATION_MARGIN: f64 = 1.1;
const PEAK_PER_TOUCHED_BRICK: u64 = 100;
struct Fit {
spacing: f64,
touched: usize,
bricks: Vec<[i32; 3]>,
estimate: (u64, u64),
}
fn fit_memory(
mut engine: Engine,
spheres: usize,
params: &SurfaceParams,
limit: u64,
control: &Control<'_>,
pool: &ScratchPool,
) -> Result<(Engine, Fit)> {
let rebuild = |engine: Engine, h: f64| -> Result<(Engine, usize, Vec<[i32; 3]>)> {
let engine = Engine::new(engine.field, h, params.brick_size, params.simd)?;
let (touched, bricks) = engine.surface_bricks()?;
control.check()?;
Ok((engine, touched, bricks))
};
let bytes = |triangles: f64, touched: f64| {
peak_bytes(triangles as u64, spheres, params)
+ (touched * PEAK_PER_TOUCHED_BRICK as f64) as u64
};
let refuse = |bytes: u64, triangles: u64, h: f64| Error::ResourceLimit {
what: format!(
"estimated peak memory ({bytes} bytes for about {triangles} triangles at {h} Å)"
),
limit,
};
let requested = params.spacing();
let pilot = requested.max(PILOT_SIDE / params.brick_size as f64);
let (mut touched, mut bricks);
(engine, touched, bricks) = rebuild(engine, pilot)?;
let pilot_touched = touched as f64;
let pilot_triangles = estimate_triangles(&engine, &bricks, pool);
control.check()?;
let predict = |h: f64| {
let s = pilot / h;
let margin = if h < pilot { EXTRAPOLATION_MARGIN } else { 1.0 };
let triangles = pilot_triangles as f64 * s * s * margin;
let touched = pilot_touched * (s * s * s).max(1.0);
(triangles, bytes(triangles, touched), bytes(0.0, touched))
};
let mut h = requested;
let (triangles, predicted, classifying) = predict(h);
if predicted > limit && (classifying > limit || predicted / 2 > limit) {
if !params.auto_coarsen || h >= 10.0 {
return Err(refuse(predicted, triangles as u64, h));
}
let (triangles, coarsest, _) = predict(10.0);
if coarsest > limit {
return Err(refuse(coarsest, triangles as u64, 10.0));
}
let (mut lo, mut hi) = (h, 10.0);
for _ in 0..40 {
let mid = 0.5 * (lo + hi);
if predict(mid).1 > limit {
lo = mid;
} else {
hi = mid;
}
}
h = hi;
}
let mut finest_touched = pilot_touched;
let (mut current, mut triangles) = (pilot, pilot_triangles);
let mut attempts = 0;
loop {
if h != current {
(engine, touched, bricks) = rebuild(engine, h)?;
finest_touched = finest_touched.max(touched as f64);
(current, triangles) = (h, estimate_triangles(&engine, &bricks, pool));
control.check()?;
}
let used = bytes(triangles as f64, finest_touched);
if used <= limit {
let fit = Fit {
spacing: h,
touched,
bricks,
estimate: (triangles, used),
};
return Ok((engine, fit));
}
let fixed = bytes(0.0, finest_touched);
if !params.auto_coarsen || attempts == 4 || limit <= fixed || h >= 10.0 {
return Err(refuse(used, triangles, h));
}
let factor = ((used - fixed) as f64 / (limit - fixed) as f64).sqrt();
h = (h * factor * 1.05).min(10.0);
attempts += 1;
}
}
pub fn estimate_memory(
surface_bricks: usize,
brick_size: usize,
spacing: f64,
spheres: usize,
) -> (u64, u64) {
let side = brick_size as f64 * spacing;
let per_brick = 2.1 * (brick_size * brick_size) as f64 * (side / 2.5).powf(0.6).max(1.0);
let triangles = (surface_bricks as f64 * per_brick) as u64;
(
triangles,
peak_bytes(triangles, spheres, &SurfaceParams::default()),
)
}
fn select_components(
mesh: &mut Mesh,
vertex_component: &mut Vec<u32>,
components: &mut Vec<mesh::Component>,
params: &SurfaceParams,
kind: SurfaceKind,
) -> (usize, usize) {
let fragment = if params.remove_fragments && kind == SurfaceKind::Ses {
post::fragments(mesh, vertex_component, components)
} else {
vec![false; components.len()]
};
let mut keep: Vec<bool> = components
.iter()
.zip(&fragment)
.map(|(c, &f)| {
let by_mode = match params.cavities {
CavityMode::Keep => true,
CavityMode::Remove => !c.is_cavity(),
CavityMode::Only => c.is_cavity(),
};
!f && 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 fragments = fragment.iter().filter(|&&f| f).count();
let n = keep.iter().filter(|k| !**k).count() - fragments;
post::retain_components(mesh, vertex_component, components, &keep);
(n, fragments)
}
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;
};
if let Some(limit) = params.max_memory {
let bytes = peak_bytes(0, spheres.len(), params);
if bytes > limit {
return Err(Error::ResourceLimit {
what: format!(
"estimated peak memory ({bytes} bytes for {} spheres before any triangle)",
spheres.len()
),
limit,
});
}
}
control.report(Stage::Geometry, 0, 1);
let field = SesField::new_with(spheres, params.effective_probe(), params.kind, control)?;
let kind = field.kind();
let mut 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 (spacing, touched, bricks, memory_estimate) = match params.max_memory {
None => {
let (touched, bricks) = engine.surface_bricks()?;
(params.spacing(), touched, bricks, None)
}
Some(limit) => {
let fit;
(engine, fit) = fit_memory(engine, spheres.len(), params, limit, control, pool)?;
(fit.spacing, fit.touched, fit.bricks, Some(fit.estimate))
}
};
control.check()?;
control.report(Stage::Classify, 1, 1);
lap(&mut timings.classify);
let chunk = crate::par::chunk_len(bricks.len());
let parts = engine.fold_brick_chunks_with(
&bricks,
chunk,
control,
Stage::Mesh,
pool,
extract::ChunkMesh::default,
|part, key, values| part.push(&engine, key, values, params.refine),
)?;
let simd = engine.simd_name();
let field = if params.smoothing > 0 {
Some(engine.field)
} else {
drop(engine);
None
};
lap(&mut timings.mesh);
control.report(Stage::Assemble, 0, 1);
let refine_evaluations = parts.iter().map(extract::ChunkMesh::evals).sum();
let mesh = extract::assemble(&bricks, chunk, 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, removed_fragments) = select_components(
&mut mesh,
&mut vertex_component,
&mut components,
params,
kind,
);
if let Some(field) = field {
post::smooth_and_project(&mut mesh, &field, spheres, params.smoothing);
drop(field);
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;
}
}
let mut decimation = None;
if let Some(d) = ¶ms.decimation {
mesh.vertex_component = vertex_component;
decimation = Some(mesh::decimate(&mut mesh, d));
let check = mesh::validate(&mesh);
if !check.is_ok() {
return Err(Error::Internal(format!(
"decimated mesh failed validation: {check:?}"
)));
}
let (vc, comps) = mesh::components(&mesh);
vertex_component = vc;
components = comps;
post::group_by_component(&mut mesh, &vertex_component, &mut components);
}
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,
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,
removed_fragments,
decimation,
euler: components.iter().map(|c| c.euler).sum(),
refine_evaluations,
simd,
estimated_triangles: memory_estimate.map(|e| e.0),
estimated_memory: memory_estimate.map(|e| e.1),
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 triangle_estimate_matches_the_mesh() {
let c = random_chain(&mut Rng::new(5), 80);
let s = spheres(&c);
for (h, exact) in [(0.5, true), (0.1, false)] {
let field = SesField::new(&s, c.probe, SurfaceKind::Ses).unwrap();
let engine = Engine::new(field, h, 10, SimdLevel::Auto).unwrap();
let (_, bricks) = engine.surface_bricks().unwrap();
assert_eq!(bricks.len() <= SAMPLE_BRICKS, exact, "{}", bricks.len());
let estimate = estimate_triangles(&engine, &bricks, &ScratchPool::default());
let real = compute_surface(&s, &SurfaceParams::ses(c.probe).with_spacing(h))
.unwrap()
.stats
.triangles as u64;
if exact {
assert_eq!(estimate, real);
} else {
assert!(
estimate >= real && estimate * 10 < real * 12,
"{estimate} vs {real}"
);
}
}
let plain = SurfaceParams::default();
assert_eq!(peak_bytes(0, 0, &plain), PEAK_FIXED);
let decimating = plain.clone().with_decimation(mesh::Decimation::ratio(0.5));
assert!(peak_bytes(1000, 10, &decimating) > peak_bytes(1000, 10, &plain));
}
#[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());
}
#[test]
fn fragments_hold_no_atoms() {
let cross = |a: [f64; 3], b: [f64; 3]| {
[
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
]
};
let normalize = |a: [f64; 3]| {
let n = (a[0] * a[0] + a[1] * a[1] + a[2] * a[2]).sqrt();
a.map(|c| c / n)
};
let mut rng = Rng::new(9);
let mut fragments = 0;
for _ in 0..48 {
let (probe, radius) = (1.4, rng.uniform(1.5, 1.8));
let height = probe * rng.uniform(0.97, 1.03);
let rho = ((radius + probe).powi(2) - height * height).sqrt();
let (u, w) = (rng.unit(), rng.unit());
let v = normalize(cross(u, w));
let u = normalize(cross(v, normalize(cross(u, v))));
let w = cross(v, u);
let origin = [0, 1, 2].map(|_| rng.uniform(-5.0, 5.0));
let s: Vec<Sphere> = (0..3)
.map(|k| {
let a = std::f64::consts::TAU * f64::from(k) / 3.0 + rng.uniform(-0.1, 0.1);
let (c, d) = (rho * a.cos(), rho * a.sin());
Sphere::new([0, 1, 2].map(|i| origin[i] + c * u[i] + d * w[i]), radius)
})
.collect();
let base = SurfaceParams::ses(probe).with_spacing(rng.uniform(0.2, 0.5));
let kept = compute_surface(&s, &base).unwrap();
let out = compute_surface(&s, &base.with_remove_fragments(true)).unwrap();
assert!(mesh::validate(&out.mesh).is_ok());
let mask = post::fragments(&kept.mesh, &kept.mesh.vertex_component, &kept.components);
let n = mask.iter().filter(|&&f| f).count();
assert_eq!(out.stats.removed_fragments, n);
fragments += n;
for (c, &f) in kept.components.iter().zip(&mask) {
for a in &s {
assert!(!f || !post::inside_component(&kept.mesh, c, a.center));
}
}
let rest: Vec<_> = kept
.components
.iter()
.zip(&mask)
.filter(|(_, f)| !**f)
.map(|(c, _)| (c.vertices, c.triangles, c.area, c.volume, c.euler))
.collect();
let now: Vec<_> = out
.components
.iter()
.map(|c| (c.vertices, c.triangles, c.area, c.volume, c.euler))
.collect();
assert_eq!(rest, now);
let all = mesh::Component {
vertices: out.mesh.vertex_count(),
triangles: out.mesh.triangle_count(),
area: 0.0,
volume: 0.0,
euler: 0,
first_triangle: 0,
};
for a in &s {
assert!(post::inside_component(&out.mesh, &all, a.center));
}
}
assert!(fragments > 0, "no fragment generated");
}
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());
}
}
}