use super::SurfaceKind;
use crate::control::Control;
use crate::error::{Error, Result};
use crate::geom::{Arrangement, CellGrid, EPS, Sphere, Status, Vec3};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Patch {
Solvent,
Convex {
atom: usize,
},
Saddle {
atoms: [usize; 2],
},
Concave {
atoms: [usize; 3],
},
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct FieldSample {
pub value: f64,
pub closest: [f64; 3],
pub normal: Option<[f64; 3]>,
pub patch: Patch,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Feature {
Solvent,
Beyond,
Sphere(u32),
Circle(u32),
Vertex(u32),
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct PointEval {
pub(crate) distance: f64,
pub(crate) closest: Vec3,
pub(crate) feature: Feature,
}
#[derive(Debug, Default)]
pub(crate) struct LocalCandidates {
inside: Vec<u32>,
near: Vec<u32>,
spheres: Vec<u32>,
s_off: Vec<u32>,
s_blk: Vec<u32>,
circles: Vec<u32>,
c_off: Vec<u32>,
c_blk: Vec<u32>,
vertices: Vec<u32>,
order: Vec<(f64, u32)>,
}
#[cfg(all(test, feature = "hip"))]
pub(crate) struct Superset<'a> {
pub(crate) inside: &'a [u32],
pub(crate) spheres: &'a [u32],
pub(crate) circles: &'a [u32],
pub(crate) vertices: &'a [u32],
pub(crate) near: &'a [u32],
}
impl LocalCandidates {
#[cfg(all(test, feature = "hip"))]
pub(crate) fn same_as(&self, o: &Self, ses: bool) -> bool {
let inside = if ses {
let (mut x, mut y) = (self.inside.clone(), o.inside.clone());
x.sort_unstable();
y.sort_unstable();
x == y
} else {
self.inside == o.inside
};
inside
&& self.near == o.near
&& self.spheres == o.spheres
&& self.s_off == o.s_off
&& self.s_blk == o.s_blk
&& self.circles == o.circles
&& self.c_off == o.c_off
&& self.c_blk == o.c_blk
&& self.vertices == o.vertices
}
#[cfg(all(test, feature = "hip"))]
pub(crate) fn len_marker(&self) -> usize {
self.inside.len() + self.near.len() + self.s_blk.len() + self.c_blk.len()
}
fn clear(&mut self) {
self.inside.clear();
self.near.clear();
self.spheres.clear();
self.s_off.clear();
self.s_off.push(0);
self.s_blk.clear();
self.circles.clear();
self.c_off.clear();
self.c_off.push(0);
self.c_blk.clear();
self.vertices.clear();
self.order.clear();
}
fn filter_blockers(near: &[u32], row: &[u32], out: &mut Vec<u32>) {
out.extend(row.iter().filter(|k| near.binary_search(k).is_ok()));
}
}
fn sort_nearest(v: &mut [(f64, u32)]) {
v.sort_unstable_by(|x, y| x.0.total_cmp(&y.0).then(x.1.cmp(&y.1)));
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct NearEval {
pub(crate) value: f64,
pub(crate) feature: Feature,
pub(crate) closest: Vec3,
}
#[derive(Debug, Clone)]
pub struct SesField {
pub(crate) arr: Arrangement,
pub(crate) kind: SurfaceKind,
pub(crate) probe: f64,
pub(crate) circle_cells: CellGrid,
pub(crate) vertex_cells: CellGrid,
pub(crate) rho_max: f64,
extent: f64,
}
impl SesField {
pub fn new(spheres: &[Sphere], probe_radius: f64, kind: SurfaceKind) -> Result<Self> {
Self::new_with(spheres, probe_radius, kind, &Control::new())
}
pub(crate) fn new_with(
spheres: &[Sphere],
probe_radius: f64,
kind: SurfaceKind,
control: &Control<'_>,
) -> Result<Self> {
if !(probe_radius.is_finite() && probe_radius >= 0.0) {
return Err(Error::InvalidInput(format!(
"probe radius must be finite and >= 0, got {probe_radius}"
)));
}
let kind = if kind == SurfaceKind::Ses && probe_radius == 0.0 {
SurfaceKind::Vdw
} else {
kind
};
let mut arr = match kind {
SurfaceKind::Ses => {
Arrangement::build_with(spheres, probe_radius, true, false, control)?
}
SurfaceKind::Sas => {
Arrangement::build_with(spheres, probe_radius, false, false, control)?
}
SurfaceKind::Vdw => Arrangement::build_with(spheres, 0.0, false, false, control)?,
};
debug_assert!(arr.arcs.is_empty());
let status = &arr.status;
arr.neighbors.retain_rows(|i| status[i] == Status::Exposed);
let cell = (2.0 * arr.max_expanded).max(1e-6);
let circle_cells = CellGrid::new(
&arr.circles.iter().map(|c| c.center).collect::<Vec<_>>(),
cell,
);
let vertex_cells = CellGrid::new(
&arr.vertices.iter().map(|v| v.position).collect::<Vec<_>>(),
cell,
);
let rho_max = arr.circles.iter().map(|c| c.radius).fold(0.0, f64::max);
let extent = match arr.centers.first() {
None => 0.0,
Some(&first) => {
let (lo, hi) = arr
.centers
.iter()
.fold((first, first), |(lo, hi), &c| (lo.min(c), hi.max(c)));
(hi - lo).norm() + 4.0 * arr.max_expanded + 4.0 * probe_radius + 1.0
}
};
Ok(Self {
arr,
kind,
probe: probe_radius,
circle_cells,
vertex_cells,
rho_max,
extent,
})
}
pub fn kind(&self) -> SurfaceKind {
self.kind
}
pub fn probe_radius(&self) -> f64 {
self.probe
}
pub fn value(&self, point: [f64; 3]) -> f64 {
self.sample(point).value
}
pub fn sample(&self, point: [f64; 3]) -> FieldSample {
let x = Vec3::from_array(point);
let orig = |i: u32| self.arr.orig[i as usize] as usize;
if self.arr.centers.is_empty() {
return FieldSample {
value: if self.kind == SurfaceKind::Ses {
self.probe
} else {
f64::INFINITY
},
closest: point,
normal: None,
patch: Patch::Solvent,
};
}
match self.kind {
SurfaceKind::Ses => {
let mut cutoff = self.probe + 4.0;
let e = loop {
let e = self.ses_eval(x, cutoff);
if e.feature != Feature::Beyond || cutoff > self.extent {
break e;
}
cutoff *= 2.0;
};
let patch = match e.feature {
Feature::Solvent | Feature::Beyond => Patch::Solvent,
Feature::Sphere(i) => Patch::Convex { atom: orig(i) },
Feature::Circle(c) => {
let c = &self.arr.circles[c as usize];
Patch::Saddle {
atoms: [orig(c.i), orig(c.j)],
}
}
Feature::Vertex(v) => Patch::Concave {
atoms: self.arr.vertices[v as usize].atoms.map(orig),
},
};
let to_p = e.closest - x;
let normal = (patch != Patch::Solvent && to_p.norm() > 1e-12)
.then(|| to_p.normalized().to_array());
FieldSample {
value: self.probe - e.distance,
closest: e.closest.to_array(),
normal,
patch,
}
}
SurfaceKind::Sas | SurfaceKind::Vdw => {
let mut cutoff = 4.0;
let (value, i) = loop {
let (v, i) = self.sphere_eval(x, cutoff);
if i.is_some() || cutoff > self.extent {
break (v, i);
}
cutoff *= 2.0;
};
let Some(i) = i else {
return FieldSample {
value,
closest: point,
normal: None,
patch: Patch::Solvent,
};
};
let (c, r) = (self.arr.centers[i as usize], self.arr.expanded[i as usize]);
let dir = x - c;
let len = dir.norm();
let unit = if len > 1e-12 { dir / len } else { Vec3::X };
FieldSample {
value,
closest: (c + unit * r).to_array(),
normal: (len > 1e-12).then(|| unit.to_array()),
patch: Patch::Convex { atom: orig(i) },
}
}
}
}
fn inside_sas(&self, x: Vec3) -> bool {
let a = &self.arr;
let mut inside = false;
a.cells.for_each_near(x, a.max_expanded, |k| {
let k = k as usize;
if !inside && a.status[k] != Status::Contained && x.dist(a.centers[k]) < a.expanded[k] {
inside = true;
}
});
inside
}
pub(crate) fn ses_eval(&self, x: Vec3, cutoff: f64) -> PointEval {
let a = &self.arr;
if !self.inside_sas(x) {
return PointEval {
distance: 0.0,
closest: x,
feature: Feature::Solvent,
};
}
let mut best = PointEval {
distance: cutoff,
closest: x,
feature: Feature::Beyond,
};
a.cells.for_each_near(x, cutoff + a.max_expanded, |i| {
if a.status[i as usize] == Status::Exposed {
self.try_sphere(x, i, &mut best);
}
});
self.circle_cells
.for_each_near(x, cutoff + self.rho_max, |ci| {
self.try_circle(x, ci, &mut best);
});
self.vertex_cells
.for_each_near(x, cutoff, |vi| self.try_vertex(x, vi, &mut best));
best
}
#[inline]
fn try_sphere(&self, x: Vec3, i: u32, best: &mut PointEval) {
self.try_sphere_with(x, i, self.arr.neighbors.row(i as usize), best);
}
#[inline]
fn try_sphere_with(&self, x: Vec3, i: u32, blockers: &[u32], best: &mut PointEval) {
let a = &self.arr;
let iu = i as usize;
let v = x - a.centers[iu];
let len = v.norm();
let lb = (len - a.expanded[iu]).abs();
if lb >= best.distance || len < 1e-12 {
return;
}
let q = a.centers[iu] + v * (a.expanded[iu] / len);
let free = blockers
.iter()
.all(|&k| q.dist(a.centers[k as usize]) >= a.expanded[k as usize] - EPS);
if free {
*best = PointEval {
distance: lb,
closest: q,
feature: Feature::Sphere(i),
};
}
}
#[inline]
fn try_circle(&self, x: Vec3, ci: u32, best: &mut PointEval) {
self.try_circle_with(x, ci, self.arr.circle_blockers.row(ci as usize), best);
}
#[inline]
fn try_circle_with(&self, x: Vec3, ci: u32, blockers: &[u32], best: &mut PointEval) {
let a = &self.arr;
let c = &a.circles[ci as usize];
let y = x - c.center;
let along = y.dot(c.axis);
let w = y - c.axis * along;
let wl = w.norm();
let dist = (along * along + (wl - c.radius) * (wl - c.radius)).sqrt();
if dist >= best.distance {
return;
}
let dir = if wl > 1e-12 { w / wl } else { c.e1 };
let q = c.center + dir * c.radius;
let free = blockers
.iter()
.all(|&k| q.dist(a.centers[k as usize]) >= a.expanded[k as usize] - EPS);
if free {
*best = PointEval {
distance: dist,
closest: q,
feature: Feature::Circle(ci),
};
}
}
#[inline]
fn try_vertex(&self, x: Vec3, vi: u32, best: &mut PointEval) {
let p = self.arr.vertices[vi as usize].position;
let d = x.dist(p);
if d < best.distance {
*best = PointEval {
distance: d,
closest: p,
feature: Feature::Vertex(vi),
};
}
}
pub(crate) fn gather_local(&self, b: Vec3, rho: f64, band: f64, out: &mut LocalCandidates) {
let a = &self.arr;
out.clear();
match self.kind {
SurfaceKind::Ses => {
let reach = self.probe + band + rho;
a.cells.for_each_near(b, reach + a.max_expanded, |k| {
let ku = k as usize;
if a.status[ku] == Status::Contained {
return;
}
let d = b.dist(a.centers[ku]);
if d < a.expanded[ku] + reach {
out.near.push(k);
}
if d < a.expanded[ku] + rho {
out.inside.push(k);
}
let lb = (d - a.expanded[ku]).abs();
if a.status[ku] == Status::Exposed && lb <= reach {
out.order.push((lb, k));
}
});
out.near.sort_unstable();
sort_nearest(&mut out.order);
for &(_, k) in &out.order {
out.spheres.push(k);
LocalCandidates::filter_blockers(
&out.near,
a.neighbors.row(k as usize),
&mut out.s_blk,
);
out.s_off.push(out.s_blk.len() as u32);
}
out.order.clear();
self.circle_cells
.for_each_near(b, reach + self.rho_max, |ci| {
let c = &a.circles[ci as usize];
let y = b - c.center;
let along = y.dot(c.axis);
let wl = (y - c.axis * along).norm();
let dist = (along * along + (wl - c.radius) * (wl - c.radius)).sqrt();
if dist <= reach {
out.order.push((dist, ci));
}
});
sort_nearest(&mut out.order);
for &(_, ci) in &out.order {
out.circles.push(ci);
LocalCandidates::filter_blockers(
&out.near,
a.circle_blockers.row(ci as usize),
&mut out.c_blk,
);
out.c_off.push(out.c_blk.len() as u32);
}
out.order.clear();
self.vertex_cells.for_each_near(b, reach, |vi| {
let d = b.dist(a.vertices[vi as usize].position);
if d <= reach {
out.order.push((d, vi));
}
});
sort_nearest(&mut out.order);
out.vertices.extend(out.order.iter().map(|o| o.1));
}
SurfaceKind::Sas | SurfaceKind::Vdw => {
let reach = band + rho;
a.cells.for_each_near(b, reach + a.max_expanded, |k| {
let ku = k as usize;
if a.status[ku] != Status::Contained
&& b.dist(a.centers[ku]) - a.expanded[ku] < reach
{
out.order.push((b.dist(a.centers[ku]) - a.expanded[ku], k));
}
});
sort_nearest(&mut out.order);
out.inside.extend(out.order.iter().map(|o| o.1));
}
}
out.order.clear();
}
#[cfg(all(test, feature = "hip"))]
pub(crate) fn gather_local_from(
&self,
b: Vec3,
rho: f64,
band: f64,
sup: &Superset<'_>,
out: &mut LocalCandidates,
) {
let a = &self.arr;
out.clear();
match self.kind {
SurfaceKind::Ses => {
let reach = self.probe + band + rho;
for &k in sup.near {
let ku = k as usize;
if a.status[ku] != Status::Contained
&& b.dist(a.centers[ku]) < a.expanded[ku] + reach
{
out.near.push(k);
}
}
for &k in sup.inside {
let ku = k as usize;
if a.status[ku] != Status::Contained
&& b.dist(a.centers[ku]) < a.expanded[ku] + rho
{
out.inside.push(k);
}
}
for &k in sup.spheres {
let ku = k as usize;
let lb = (b.dist(a.centers[ku]) - a.expanded[ku]).abs();
if a.status[ku] == Status::Exposed && lb <= reach {
out.order.push((lb, k));
}
}
out.near.sort_unstable();
sort_nearest(&mut out.order);
for &(_, k) in &out.order {
out.spheres.push(k);
LocalCandidates::filter_blockers(
&out.near,
a.neighbors.row(k as usize),
&mut out.s_blk,
);
out.s_off.push(out.s_blk.len() as u32);
}
out.order.clear();
for &ci in sup.circles {
let c = &a.circles[ci as usize];
let y = b - c.center;
let along = y.dot(c.axis);
let wl = (y - c.axis * along).norm();
let dist = (along * along + (wl - c.radius) * (wl - c.radius)).sqrt();
if dist <= reach {
out.order.push((dist, ci));
}
}
sort_nearest(&mut out.order);
for &(_, ci) in &out.order {
out.circles.push(ci);
LocalCandidates::filter_blockers(
&out.near,
a.circle_blockers.row(ci as usize),
&mut out.c_blk,
);
out.c_off.push(out.c_blk.len() as u32);
}
out.order.clear();
for &vi in sup.vertices {
let d = b.dist(a.vertices[vi as usize].position);
if d <= reach {
out.order.push((d, vi));
}
}
sort_nearest(&mut out.order);
out.vertices.extend(out.order.iter().map(|o| o.1));
}
SurfaceKind::Sas | SurfaceKind::Vdw => {
let reach = band + rho;
for &k in sup.inside {
let ku = k as usize;
if a.status[ku] != Status::Contained
&& b.dist(a.centers[ku]) - a.expanded[ku] < reach
{
out.order.push((b.dist(a.centers[ku]) - a.expanded[ku], k));
}
}
sort_nearest(&mut out.order);
out.inside.extend(out.order.iter().map(|o| o.1));
}
}
out.order.clear();
}
pub(crate) fn eval_local(&self, x: Vec3, band: f64, l: &LocalCandidates) -> NearEval {
let a = &self.arr;
match self.kind {
SurfaceKind::Ses => {
let inside = l
.inside
.iter()
.any(|&k| x.dist(a.centers[k as usize]) < a.expanded[k as usize]);
if !inside {
return NearEval {
value: self.probe,
feature: Feature::Solvent,
closest: x,
};
}
let mut best = PointEval {
distance: self.probe + band,
closest: x,
feature: Feature::Beyond,
};
for (k, &i) in l.spheres.iter().enumerate() {
let blk = &l.s_blk[l.s_off[k] as usize..l.s_off[k + 1] as usize];
self.try_sphere_with(x, i, blk, &mut best);
}
for (k, &ci) in l.circles.iter().enumerate() {
let blk = &l.c_blk[l.c_off[k] as usize..l.c_off[k + 1] as usize];
self.try_circle_with(x, ci, blk, &mut best);
}
for &vi in &l.vertices {
self.try_vertex(x, vi, &mut best);
}
NearEval {
value: self.probe - best.distance,
feature: best.feature,
closest: best.closest,
}
}
SurfaceKind::Sas | SurfaceKind::Vdw => {
let mut best = (band, None);
for &k in &l.inside {
let v = x.dist(a.centers[k as usize]) - a.expanded[k as usize];
if v < best.0 {
best = (v, Some(k));
}
}
NearEval {
value: best.0,
feature: best.1.map_or(Feature::Beyond, Feature::Sphere),
closest: x,
}
}
}
}
pub(crate) fn sphere_eval(&self, x: Vec3, cutoff: f64) -> (f64, Option<u32>) {
let a = &self.arr;
let mut best = (cutoff, None);
a.cells.for_each_near(x, cutoff + a.max_expanded, |k| {
let ku = k as usize;
if a.status[ku] == Status::Contained {
return;
}
let v = x.dist(a.centers[ku]) - a.expanded[ku];
if v < best.0 {
best = (v, Some(k));
}
});
best
}
pub(crate) fn clamped_value(&self, x: Vec3, band: f64) -> f64 {
match self.kind {
SurfaceKind::Ses => self.probe - self.ses_eval(x, self.probe + band).distance,
SurfaceKind::Sas | SurfaceKind::Vdw => self.sphere_eval(x, band).0,
}
}
}