#[derive(Clone, Debug)]
pub struct CellList {
pub n_cells: [usize; 3],
pub cell_size: [f64; 3],
pub n_cells_total: usize,
pub cell_start: Vec<u32>,
pub cell_count: Vec<u32>,
pub sorted_indices: Vec<usize>,
rc: f64,
box_dims: [f64; 3],
}
impl CellList {
#[must_use]
pub fn new(rc: f64, box_side: f64) -> Self {
Self::new_with_dims(rc, [box_side; 3])
}
#[must_use]
pub fn new_with_dims(rc: f64, box_dims: [f64; 3]) -> Self {
let n_cells = [
(box_dims[0] / rc).floor() as usize,
(box_dims[1] / rc).floor() as usize,
(box_dims[2] / rc).floor() as usize,
];
let n_cells = [n_cells[0].max(3), n_cells[1].max(3), n_cells[2].max(3)];
let cell_size = [
box_dims[0] / n_cells[0] as f64,
box_dims[1] / n_cells[1] as f64,
box_dims[2] / n_cells[2] as f64,
];
let n_cells_total = n_cells[0] * n_cells[1] * n_cells[2];
Self {
n_cells,
cell_size,
n_cells_total,
cell_start: vec![0; n_cells_total],
cell_count: vec![0; n_cells_total],
sorted_indices: Vec::new(),
rc,
box_dims,
}
}
pub fn rebuild(&mut self, positions: &[f64], n: usize) {
let mut cell_ids = Vec::with_capacity(n);
for i in 0..n {
let cell_id = self.position_to_cell_id(
positions[i * 3],
positions[i * 3 + 1],
positions[i * 3 + 2],
);
cell_ids.push(cell_id);
}
self.sorted_indices = (0..n).collect();
self.sorted_indices.sort_by_key(|&i| cell_ids[i]);
self.cell_count.fill(0);
for &idx in &self.sorted_indices {
self.cell_count[cell_ids[idx]] += 1;
}
let mut offset = 0u32;
for c in 0..self.n_cells_total {
self.cell_start[c] = offset;
offset += self.cell_count[c];
}
}
fn position_to_cell_id(&self, x: f64, y: f64, z: f64) -> usize {
let cx = ((x / self.cell_size[0]) as usize).min(self.n_cells[0] - 1);
let cy = ((y / self.cell_size[1]) as usize).min(self.n_cells[1] - 1);
let cz = ((z / self.cell_size[2]) as usize).min(self.n_cells[2] - 1);
cx + cy * self.n_cells[0] + cz * self.n_cells[0] * self.n_cells[1]
}
#[must_use]
pub fn sort_array(&self, data: &[f64], stride: usize) -> Vec<f64> {
let mut sorted = vec![0.0f64; data.len()];
for (new_idx, &old_idx) in self.sorted_indices.iter().enumerate() {
for s in 0..stride {
sorted[new_idx * stride + s] = data[old_idx * stride + s];
}
}
sorted
}
#[must_use]
pub fn unsort_array(&self, data: &[f64], stride: usize) -> Vec<f64> {
let mut unsorted = vec![0.0f64; data.len()];
for (new_idx, &old_idx) in self.sorted_indices.iter().enumerate() {
for s in 0..stride {
unsorted[old_idx * stride + s] = data[new_idx * stride + s];
}
}
unsorted
}
#[must_use]
pub fn gpu_params(&self) -> Vec<f64> {
vec![
self.n_cells[0] as f64,
self.n_cells[1] as f64,
self.n_cells[2] as f64,
self.cell_size[0],
self.cell_size[1],
self.cell_size[2],
self.n_cells_total as f64,
0.0, ]
}
#[must_use]
pub fn cell_start_u32(&self) -> &[u32] {
&self.cell_start
}
#[must_use]
pub fn cell_count_u32(&self) -> &[u32] {
&self.cell_count
}
#[must_use]
pub fn cutoff(&self) -> f64 {
self.rc
}
#[must_use]
pub fn box_dims(&self) -> [f64; 3] {
self.box_dims
}
#[must_use]
pub fn memory_usage(&self) -> usize {
let n = self.sorted_indices.len();
let cells = self.n_cells_total;
n * std::mem::size_of::<usize>() + cells * 8
}
#[must_use]
pub fn occupancy_stats(&self) -> CellStats {
if self.n_cells_total == 0 || self.sorted_indices.is_empty() {
return CellStats::default();
}
let non_empty: Vec<u32> = self.cell_count.iter().copied().filter(|&c| c > 0).collect();
let min_occ = non_empty.iter().copied().min().unwrap_or(0);
let max_occ = non_empty.iter().copied().max().unwrap_or(0);
let mean_occ = if non_empty.is_empty() {
0.0
} else {
non_empty.iter().sum::<u32>() as f64 / non_empty.len() as f64
};
let n_empty = self.n_cells_total - non_empty.len();
CellStats {
n_cells_total: self.n_cells_total,
n_empty,
min_occupancy: min_occ,
max_occupancy: max_occ,
mean_occupancy: mean_occ,
}
}
}
#[derive(Clone, Debug, Default)]
pub struct CellStats {
pub n_cells_total: usize,
pub n_empty: usize,
pub min_occupancy: u32,
pub max_occupancy: u32,
pub mean_occupancy: f64,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_cell_list_construction() {
let cell_list = CellList::new(2.0, 10.0);
assert_eq!(cell_list.n_cells, [5, 5, 5]);
assert_eq!(cell_list.n_cells_total, 125);
assert!((cell_list.cell_size[0] - 2.0).abs() < 1e-10);
}
#[test]
fn test_cell_list_minimum_cells() {
let cell_list = CellList::new(5.0, 10.0);
assert_eq!(cell_list.n_cells, [3, 3, 3]);
assert_eq!(cell_list.n_cells_total, 27);
}
#[test]
fn test_cell_list_rebuild() {
let mut cell_list = CellList::new(5.0, 10.0);
let positions = vec![
1.0, 1.0, 1.0, 8.0, 8.0, 8.0, 1.0, 8.0, 1.0, 8.0, 1.0, 8.0, ];
cell_list.rebuild(&positions, 4);
assert_eq!(cell_list.sorted_indices.len(), 4);
let total: u32 = cell_list.cell_count.iter().sum();
assert_eq!(total, 4);
}
#[test]
fn test_sort_unsort_roundtrip() {
let mut cell_list = CellList::new(5.0, 10.0);
let positions = vec![
1.0, 2.0, 3.0, 7.0, 8.0, 9.0, 4.0, 5.0, 6.0, ];
cell_list.rebuild(&positions, 3);
let sorted = cell_list.sort_array(&positions, 3);
let unsorted = cell_list.unsort_array(&sorted, 3);
for (i, (&orig, &recovered)) in positions.iter().zip(unsorted.iter()).enumerate() {
assert!(
(orig - recovered).abs() < 1e-10,
"Mismatch at index {i}: {orig} vs {recovered}"
);
}
}
#[test]
fn test_gpu_params() {
let cell_list = CellList::new(2.0, 10.0);
let params = cell_list.gpu_params();
assert_eq!(params.len(), 8);
assert_eq!(params[0], 5.0); assert_eq!(params[1], 5.0); assert_eq!(params[2], 5.0); assert!((params[3] - 2.0).abs() < 1e-10); assert_eq!(params[6], 125.0); }
#[test]
fn test_occupancy_stats() {
let mut cell_list = CellList::new(5.0, 10.0);
let positions = vec![1.0, 1.0, 1.0, 1.1, 1.1, 1.1, 1.2, 1.2, 1.2, 9.0, 9.0, 9.0];
cell_list.rebuild(&positions, 4);
let stats = cell_list.occupancy_stats();
assert_eq!(stats.n_cells_total, 27);
assert_eq!(stats.n_empty, 25);
assert_eq!(stats.min_occupancy, 1);
assert_eq!(stats.max_occupancy, 3);
}
#[test]
fn test_non_cubic_box() {
let cell_list = CellList::new_with_dims(2.0, [10.0, 8.0, 6.0]);
assert_eq!(cell_list.n_cells, [5, 4, 3]);
assert_eq!(cell_list.n_cells_total, 60);
}
}