#![deny(unsafe_op_in_unsafe_fn)]
use std::cell::RefCell;
use std::ffi::{c_char, c_int, CString};
use std::ptr;
use std::sync::atomic::{AtomicUsize, Ordering};
use crate::{Cell, Error};
static WANTED_THREADS: AtomicUsize = AtomicUsize::new(0);
#[cfg(not(feature = "parallel"))]
fn with_threads<R: Send>(work: impl FnOnce() -> R + Send) -> R {
work()
}
#[cfg(feature = "parallel")]
fn with_threads<R: Send>(work: impl FnOnce() -> R + Send) -> R {
let n = WANTED_THREADS.load(Ordering::Relaxed);
if n == 0 {
return work();
}
if n == 1 {
return crate::run_on_caller(work);
}
if rayon::current_thread_index().is_some() && rayon::current_num_threads() == n {
return work();
}
struct Slot {
n: usize,
pool: rayon::ThreadPool,
}
static CACHE: std::sync::Mutex<Option<Slot>> = std::sync::Mutex::new(None);
let mut guard = CACHE.lock().unwrap_or_else(|err| err.into_inner());
if guard.as_ref().map(|slot| slot.n) != Some(n) {
*guard = None;
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(n)
.build()
.unwrap_or_else(|_| {
rayon::ThreadPoolBuilder::new()
.num_threads(1)
.build()
.unwrap()
});
*guard = Some(Slot { n, pool });
}
guard.as_ref().unwrap().pool.install(work)
}
#[no_mangle]
pub extern "C" fn lc_set_threads(n: c_int) {
let n = if n < 0 { 1 } else { n as usize };
WANTED_THREADS.store(n, Ordering::Relaxed);
}
#[no_mangle]
pub extern "C" fn lc_num_threads() -> c_int {
let n = WANTED_THREADS.load(Ordering::Relaxed);
if n == 0 {
default_width() as c_int
} else {
n as c_int
}
}
fn default_width() -> usize {
#[cfg(feature = "parallel")]
{
rayon::current_num_threads()
}
#[cfg(not(feature = "parallel"))]
{
1
}
}
#[cfg(feature = "parallel")]
pub(crate) fn search_width() -> usize {
WANTED_THREADS.load(Ordering::Relaxed)
}
#[derive(Clone, Copy)]
struct Continuation {
ctx: usize,
cb: usize,
}
thread_local! {
#[allow(clippy::missing_const_for_thread_local)]
static CONTINUATION: std::cell::Cell<Option<Continuation>> = std::cell::Cell::new(None);
}
fn take_continuation() -> Option<Continuation> {
CONTINUATION.with(|slot| slot.get())
}
fn run_continuation(cont: Option<Continuation>) {
let Some(cont) = cont else {
return;
};
let cb: extern "C" fn(*mut std::ffi::c_void) = unsafe { std::mem::transmute(cont.cb) };
cb(cont.ctx as *mut std::ffi::c_void);
}
#[no_mangle]
pub extern "C" fn lc_set_continuation(
ctx: *mut std::ffi::c_void,
cb: Option<extern "C" fn(*mut std::ffi::c_void)>,
) {
CONTINUATION.with(|slot| {
slot.set(cb.map(|cb| Continuation {
ctx: ctx as usize,
cb: cb as usize,
}))
});
}
#[no_mangle]
pub extern "C" fn lc_set_gpu_curve_split(
f: Option<
unsafe extern "C" fn(
atom_bin: *const u32,
natom: usize,
coords: *const u32,
ncell: usize,
parts: u32,
assign: *mut u32,
out_weight: *mut u64,
method: u8,
) -> i32,
>,
) {
crate::partition::register_device_curve(f);
}
#[no_mangle]
pub extern "C" fn lc_for_slabs(
n: c_int,
ctx: *mut std::ffi::c_void,
cb: Option<extern "C" fn(*mut std::ffi::c_void, c_int, c_int)>,
) {
let Some(cb) = cb else {
return;
};
if n <= 0 {
return;
}
let ctx_bits = ctx as usize;
let cb_bits = cb as usize;
with_threads(move || {
let call = |begin: c_int, end: c_int| {
let ctx = ctx_bits as *mut std::ffi::c_void;
let cb: extern "C" fn(*mut std::ffi::c_void, c_int, c_int) =
unsafe { std::mem::transmute(cb_bits) };
cb(ctx, begin, end);
};
#[cfg(not(feature = "parallel"))]
call(0, n);
#[cfg(feature = "parallel")]
if WANTED_THREADS.load(Ordering::Relaxed) <= 1 {
call(0, n);
} else {
rayon::broadcast(move |worker| {
let workers = worker.num_threads().max(1);
let t = worker.index();
let begin = (n as usize) * t / workers;
let end = (n as usize) * (t + 1) / workers;
call(begin as c_int, end as c_int);
});
}
});
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct lc_cell {
pub ax: f64,
pub ay: f64,
pub az: f64,
pub bx: f64,
pub by: f64,
pub bz: f64,
pub cx: f64,
pub cy: f64,
pub cz: f64,
pub ox: f64,
pub oy: f64,
pub oz: f64,
}
thread_local! {
static LAST_ERROR: RefCell<Option<CString>> = const { RefCell::new(None) };
}
fn set_error(msg: &str) {
LAST_ERROR.with(|slot| {
let cstr = CString::new(msg).unwrap_or_else(|_| {
CString::new("error message contained NUL").expect("fallback has no NUL")
});
*slot.borrow_mut() = Some(cstr);
});
}
fn clear_error() {
LAST_ERROR.with(|slot| {
*slot.borrow_mut() = None;
});
}
fn fail(err: Error) -> c_int {
set_error(&err.to_string());
1
}
fn fail_msg(msg: &str) -> c_int {
set_error(msg);
1
}
#[no_mangle]
pub extern "C" fn lc_last_error() -> *const c_char {
LAST_ERROR.with(|slot| {
slot.borrow()
.as_ref()
.map(|s| s.as_ptr())
.unwrap_or(ptr::null())
})
}
#[no_mangle]
pub extern "C" fn lc_version() -> *const c_char {
concat!(env!("CARGO_PKG_VERSION"), "\0").as_ptr() as *const c_char
}
#[no_mangle]
pub unsafe extern "C" fn lc_knearest(
xyz: *const f64,
n: usize,
simbox: *const lc_cell,
k: usize,
mask: *const c_int,
cell_hint: f64,
out_nn: *mut c_int,
) -> c_int {
unsafe {
lc_knearest_many(
xyz,
n,
1,
simbox,
k,
mask,
cell_hint,
out_nn,
ptr::null_mut(),
)
}
}
#[no_mangle]
pub unsafe extern "C" fn lc_knearest_d2(
xyz: *const f64,
n: usize,
simbox: *const lc_cell,
k: usize,
mask: *const c_int,
cell_hint: f64,
out_nn: *mut c_int,
out_d2: *mut f64,
) -> c_int {
unsafe { lc_knearest_many(xyz, n, 1, simbox, k, mask, cell_hint, out_nn, out_d2) }
}
#[no_mangle]
pub unsafe extern "C" fn lc_knearest_many(
xyz: *const f64,
n: usize,
n_frames: usize,
simbox: *const lc_cell,
k: usize,
mask: *const c_int,
cell_hint: f64,
out_nn: *mut c_int,
out_d2: *mut f64,
) -> c_int {
if n == 0 || n_frames == 0 {
return fail(Error::Empty);
}
if k == 0 {
return fail(Error::ZeroK);
}
if xyz.is_null() || simbox.is_null() || out_nn.is_null() {
return fail_msg("null pointer");
}
let Some(n_pts) = n.checked_mul(n_frames) else {
return fail(Error::Overflow);
};
let Some(need) = n_pts.checked_mul(k) else {
return fail(Error::Overflow);
};
let max_xyz = (isize::MAX as usize) / 3;
let max_out = (isize::MAX as usize) / std::mem::size_of::<c_int>();
if n_pts > max_xyz || need > max_out {
return fail(Error::Overflow);
}
let box_c = unsafe { *simbox };
let sim = match Cell::from_vectors(
[box_c.ax, box_c.ay, box_c.az],
[box_c.bx, box_c.by, box_c.bz],
[box_c.cx, box_c.cy, box_c.cz],
[box_c.ox, box_c.oy, box_c.oz],
) {
Ok(b) => b,
Err(e) => {
set_error(&e.to_string());
return 1;
}
};
let pts: &[[f64; 3]] = unsafe { std::slice::from_raw_parts(xyz.cast::<[f64; 3]>(), n_pts) };
let mask_vec: Option<Vec<bool>> = if mask.is_null() {
None
} else {
let raw = unsafe { std::slice::from_raw_parts(mask, n) };
Some(raw.iter().map(|&v| v != 0).collect())
};
let hint = if cell_hint > 0.0 {
Some(cell_hint)
} else {
None
};
let nn = unsafe { std::slice::from_raw_parts_mut(out_nn, need) };
let d2_store;
let d2 = if out_d2.is_null() {
None
} else {
d2_store = unsafe { std::slice::from_raw_parts_mut(out_d2, need) };
Some(&mut d2_store[..])
};
let cont = take_continuation();
let err = with_threads(|| {
let found = if n_frames == 1 {
crate::knearest_into_d2(pts, &sim, k, mask_vec.as_deref(), hint, nn, d2)
} else {
crate::knearest_into_many(pts, n, n_frames, &sim, k, mask_vec.as_deref(), hint, nn, d2)
};
if found.is_ok() {
run_continuation(cont);
}
found
});
if let Err(e) = err {
set_error(&e.to_string());
return 1;
}
clear_error();
0
}
#[no_mangle]
pub unsafe extern "C" fn lc_pairs_within(
xyz: *const f64,
n: usize,
simbox: *const lc_cell,
cutoff: f64,
mask: *const c_int,
cell_hint: f64,
half: c_int,
out_i: *mut c_int,
out_j: *mut c_int,
out_shift: *mut c_int,
out_d2: *mut f64,
cap: usize,
out_count: *mut usize,
) -> c_int {
if out_count.is_null() {
return fail_msg("null pointer");
}
let (key, found) = match unsafe { pairs_call(xyz, n, simbox, cutoff, mask, cell_hint, half) } {
Ok(v) => v,
Err(code) => return code,
};
let rows = found.rows();
unsafe {
*out_count = rows;
}
let query = out_i.is_null() && out_j.is_null() && out_shift.is_null() && out_d2.is_null();
if query {
park(&key, found);
clear_error();
return 0;
}
if out_i.is_null() || out_j.is_null() || out_shift.is_null() || out_d2.is_null() {
return fail_msg("null pointer");
}
if cap < rows {
park(&key, found);
return fail_msg("pair buffer is shorter than the pair count");
}
match rows.checked_mul(3) {
Some(v) if v <= isize::MAX as usize => {}
_ => return fail(Error::Overflow),
}
let cols = ColumnOut(out_i, out_j, out_shift, out_d2);
crate::pairs::in_pool(found.rows(), move || {
let (i, j, s, d) = cols.get();
unsafe { found.write_columns(i, j, s, d) }
});
clear_error();
0
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct lc_pair {
pub i: c_int,
pub j: c_int,
pub shift: [c_int; 3],
pub dist2: f64,
}
#[no_mangle]
pub unsafe extern "C" fn lc_pairs_within_rows(
xyz: *const f64,
n: usize,
simbox: *const lc_cell,
cutoff: f64,
mask: *const c_int,
cell_hint: f64,
half: c_int,
out: *mut lc_pair,
cap: usize,
out_count: *mut usize,
) -> c_int {
if out_count.is_null() {
return fail_msg("null pointer");
}
let (key, found) = match unsafe { pairs_call(xyz, n, simbox, cutoff, mask, cell_hint, half) } {
Ok(v) => v,
Err(code) => return code,
};
let rows = found.rows();
unsafe {
*out_count = rows;
}
if out.is_null() {
park(&key, found);
clear_error();
return 0;
}
if cap < rows {
park(&key, found);
return fail_msg("pair buffer is shorter than the pair count");
}
let rows_out = RowOut(out);
with_threads(move || {
crate::pairs::in_pool(found.rows(), move || {
let out = rows_out.get();
unsafe { found.write_rows(out, |i, j, shift, dist2| lc_pair { i, j, shift, dist2 }) }
})
});
clear_error();
0
}
#[no_mangle]
pub extern "C" fn lc_stencil_builds() -> u64 {
crate::stencil_builds()
}
#[no_mangle]
pub unsafe extern "C" fn lc_pairs_open(
xyz: *const f64,
n: usize,
cutoff: f64,
cell_hint: f64,
out: *mut lc_pair,
cap: usize,
out_count: *mut usize,
) -> c_int {
let periodic = [0, 0, 0];
unsafe {
lc_pairs_within_pbc(
xyz,
n,
std::ptr::null(),
periodic.as_ptr(),
cutoff,
std::ptr::null(),
cell_hint,
1,
0,
0,
out,
cap,
out_count,
)
}
}
#[no_mangle]
pub unsafe extern "C" fn lc_pairs_within_pbc(
xyz: *const f64,
n: usize,
simbox: *const lc_cell,
pbc: *const c_int,
cutoff: f64,
mask: *const c_int,
cell_hint: f64,
half: c_int,
closed: c_int,
exclude_self_images: c_int,
out: *mut lc_pair,
cap: usize,
out_count: *mut usize,
) -> c_int {
if out_count.is_null() {
return fail_msg("null pointer");
}
let periodic = if pbc.is_null() {
[true, true, true]
} else {
let flags = unsafe { [*pbc, *pbc.add(1), *pbc.add(2)] };
[flags[0] != 0, flags[1] != 0, flags[2] != 0]
};
if n == 0 {
unsafe { *out_count = 0 };
clear_error();
return 0;
}
if xyz.is_null() || (periodic != [false, false, false] && simbox.is_null()) {
return fail_msg("null pointer");
}
if n > c_int::MAX as usize || n > (isize::MAX as usize) / 3 {
return fail(Error::Overflow);
}
let hint = if cell_hint > 0.0 {
Some(cell_hint)
} else {
None
};
let pts = unsafe { std::slice::from_raw_parts(xyz.cast::<[f64; 3]>(), n) };
let mask_raw: Option<&[c_int]> = if mask.is_null() {
None
} else {
Some(unsafe { std::slice::from_raw_parts(mask, n) })
};
let key = OpenKey {
xyz: xyz_bits(pts),
periodic,
cutoff: cutoff.to_bits(),
mask: mask_raw.map(|m| m.iter().map(|&v| v != 0).collect()),
cell_hint: hint.map(f64::to_bits),
half: half != 0,
closed: closed != 0,
exclude_self: exclude_self_images != 0,
box_bits: if periodic == [false, false, false] || simbox.is_null() {
[0; 12]
} else {
box_bits(unsafe { &*simbox })
},
};
let rows = if let Some(parked) = take_open(&key) {
parked
} else {
match open_rows(pts, simbox, periodic, cutoff, mask_raw, hint, &key) {
Ok(rows) => rows,
Err(code) => return code,
}
};
unsafe { *out_count = rows.len() };
if out.is_null() {
park_open(key, rows);
clear_error();
return 0;
}
if cap < rows.len() {
let len = rows.len();
park_open(key, rows);
let _ = len;
return fail_msg("pair buffer is shorter than the pair count");
}
let dest = unsafe { std::slice::from_raw_parts_mut(out, rows.len()) };
dest.copy_from_slice(&rows);
clear_error();
0
}
struct OpenKey {
xyz: Vec<u64>,
periodic: [bool; 3],
cutoff: u64,
mask: Option<Vec<bool>>,
cell_hint: Option<u64>,
half: bool,
closed: bool,
exclude_self: bool,
box_bits: [u64; 12],
}
struct ParkedOpen {
key: OpenKey,
rows: Vec<lc_pair>,
}
thread_local! {
static PARKED_OPEN: RefCell<Option<ParkedOpen>> = const { RefCell::new(None) };
}
fn xyz_bits(xyz: &[[f64; 3]]) -> Vec<u64> {
let mut bits = Vec::with_capacity(xyz.len() * 3);
for point in xyz {
bits.push(point[0].to_bits());
bits.push(point[1].to_bits());
bits.push(point[2].to_bits());
}
bits
}
fn take_open(key: &OpenKey) -> Option<Vec<lc_pair>> {
let parked = PARKED_OPEN.with(|slot| slot.borrow_mut().take())?;
let same = parked.key.periodic == key.periodic
&& parked.key.cutoff == key.cutoff
&& parked.key.cell_hint == key.cell_hint
&& parked.key.half == key.half
&& parked.key.closed == key.closed
&& parked.key.exclude_self == key.exclude_self
&& parked.key.box_bits == key.box_bits
&& parked.key.mask == key.mask
&& parked.key.xyz == key.xyz;
if same {
Some(parked.rows)
} else {
None
}
}
fn park_open(key: OpenKey, rows: Vec<lc_pair>) {
PARKED_OPEN.with(|slot| {
*slot.borrow_mut() = Some(ParkedOpen { key, rows });
});
}
fn open_rows(
pts: &[[f64; 3]],
simbox: *const lc_cell,
periodic: [bool; 3],
cutoff: f64,
mask: Option<&[c_int]>,
hint: Option<f64>,
key: &OpenKey,
) -> Result<Vec<lc_pair>, c_int> {
let cell = if periodic == [false, false, false] {
Cell::ortho(1.0, 1.0, 1.0).map_err(|err| fail(err.into()))?
} else {
let raw = unsafe { *simbox };
crate::cell_for_pbc(
[
[raw.ax, raw.ay, raw.az],
[raw.bx, raw.by, raw.bz],
[raw.cx, raw.cy, raw.cz],
],
[raw.ox, raw.oy, raw.oz],
periodic,
)
.map_err(fail)?
};
let mask_vec: Option<Vec<bool>> = mask.map(|m| m.iter().map(|&v| v != 0).collect());
let mut query = crate::PbcQuery::new(periodic, cutoff)
.cell_hint(hint)
.half(key.half)
.closed(key.closed)
.exclude_self_images(key.exclude_self);
query.mask = mask_vec.as_deref();
let found = with_threads(|| crate::pairs_within_pbc(pts, &cell, &query)).map_err(fail)?;
let mut rows = Vec::with_capacity(found.len());
for pair in found {
if pair.i > c_int::MAX as usize || pair.j > c_int::MAX as usize {
return Err(fail(Error::Overflow));
}
rows.push(lc_pair {
i: pair.i as c_int,
j: pair.j as c_int,
shift: pair.shift,
dist2: pair.dist2,
});
}
Ok(rows)
}
unsafe fn pairs_call<'a>(
xyz: *const f64,
n: usize,
simbox: *const lc_cell,
cutoff: f64,
mask: *const c_int,
cell_hint: f64,
half: c_int,
) -> Result<(PairKey<'a>, crate::pairs::Found), c_int> {
if n == 0 {
return Err(fail(Error::Empty));
}
if xyz.is_null() || simbox.is_null() {
return Err(fail_msg("null pointer"));
}
if n > c_int::MAX as usize || n > (isize::MAX as usize) / 3 {
return Err(fail(Error::Overflow));
}
let box_c = unsafe { *simbox };
let sim = Cell::from_vectors(
[box_c.ax, box_c.ay, box_c.az],
[box_c.bx, box_c.by, box_c.bz],
[box_c.cx, box_c.cy, box_c.cz],
[box_c.ox, box_c.oy, box_c.oz],
)
.map_err(|e| {
set_error(&e.to_string());
1
})?;
let pts: &'a [[f64; 3]] = unsafe { std::slice::from_raw_parts(xyz.cast::<[f64; 3]>(), n) };
let mask_raw: Option<&'a [c_int]> = if mask.is_null() {
None
} else {
Some(unsafe { std::slice::from_raw_parts(mask, n) })
};
let hint = if cell_hint > 0.0 {
Some(cell_hint)
} else {
None
};
let key = PairKey {
xyz: pts,
simbox: box_c,
cutoff,
mask: mask_raw,
cell_hint: hint,
half: half != 0,
};
if let Some(found) = take_parked(&key) {
return Ok((key, found));
}
let mask_vec: Option<Vec<bool>> = mask_raw.map(|m| m.iter().map(|&v| v != 0).collect());
let found = with_threads(|| {
crate::pairs::in_pool(crate::pairs::hit_estimate(n, &sim, cutoff), || {
crate::pairs::search(pts, &sim, cutoff, mask_vec.as_deref(), hint, half != 0)
})
});
match found {
Ok(found) => Ok((key, found)),
Err(e) => Err(fail(e)),
}
}
#[derive(Clone, Copy)]
struct ColumnOut(*mut c_int, *mut c_int, *mut c_int, *mut f64);
unsafe impl Send for ColumnOut {}
impl ColumnOut {
fn get(self) -> (*mut c_int, *mut c_int, *mut c_int, *mut f64) {
(self.0, self.1, self.2, self.3)
}
}
#[derive(Clone, Copy)]
struct RowOut(*mut lc_pair);
unsafe impl Send for RowOut {}
impl RowOut {
fn get(self) -> *mut lc_pair {
self.0
}
}
struct PairKey<'a> {
xyz: &'a [[f64; 3]],
simbox: lc_cell,
cutoff: f64,
mask: Option<&'a [c_int]>,
cell_hint: Option<f64>,
half: bool,
}
struct ParkedPairs {
xyz: Vec<[f64; 3]>,
simbox: [u64; 12],
cutoff: u64,
mask: Option<Vec<bool>>,
cell_hint: Option<u64>,
half: bool,
found: crate::pairs::Found,
}
thread_local! {
#[allow(clippy::missing_const_for_thread_local)]
static PARKED_PAIRS: RefCell<Option<ParkedPairs>> = RefCell::new(None);
}
fn box_bits(c: &lc_cell) -> [u64; 12] {
[
c.ax.to_bits(),
c.ay.to_bits(),
c.az.to_bits(),
c.bx.to_bits(),
c.by.to_bits(),
c.bz.to_bits(),
c.cx.to_bits(),
c.cy.to_bits(),
c.cz.to_bits(),
c.ox.to_bits(),
c.oy.to_bits(),
c.oz.to_bits(),
]
}
fn same_bits(a: &[[f64; 3]], b: &[[f64; 3]]) -> bool {
a.len() == b.len()
&& a.iter().zip(b).all(|(p, q)| {
p[0].to_bits() == q[0].to_bits()
&& p[1].to_bits() == q[1].to_bits()
&& p[2].to_bits() == q[2].to_bits()
})
}
fn take_parked(key: &PairKey<'_>) -> Option<crate::pairs::Found> {
let parked = PARKED_PAIRS.with(|slot| slot.borrow_mut().take())?;
let mask_same = match (&parked.mask, key.mask) {
(None, None) => true,
(Some(a), Some(b)) => a.len() == b.len() && a.iter().zip(b).all(|(&x, &y)| x == (y != 0)),
_ => false,
};
let same = parked.half == key.half
&& parked.cutoff == key.cutoff.to_bits()
&& parked.cell_hint == key.cell_hint.map(f64::to_bits)
&& parked.simbox == box_bits(&key.simbox)
&& mask_same
&& same_bits(&parked.xyz, key.xyz);
if same {
Some(parked.found)
} else {
None
}
}
fn park(key: &PairKey<'_>, found: crate::pairs::Found) {
let parked = ParkedPairs {
xyz: key.xyz.to_vec(),
simbox: box_bits(&key.simbox),
cutoff: key.cutoff.to_bits(),
mask: key.mask.map(|m| m.iter().map(|&v| v != 0).collect()),
cell_hint: key.cell_hint.map(f64::to_bits),
half: key.half,
found,
};
PARKED_PAIRS.with(|slot| *slot.borrow_mut() = Some(parked));
}
#[allow(clippy::type_complexity)]
unsafe fn load_frame<'a>(
xyz: *const f64,
n: usize,
simbox: *const lc_cell,
mask: *const c_int,
cell_hint: f64,
) -> Result<(&'a [[f64; 3]], Cell, Option<Vec<bool>>, Option<f64>), c_int> {
if n == 0 {
return Err(fail(Error::Empty));
}
if xyz.is_null() || simbox.is_null() {
return Err(fail_msg("null pointer"));
}
if n > c_int::MAX as usize || n > (isize::MAX as usize) / 3 {
return Err(fail(Error::Overflow));
}
let box_c = unsafe { *simbox };
let sim = Cell::from_vectors(
[box_c.ax, box_c.ay, box_c.az],
[box_c.bx, box_c.by, box_c.bz],
[box_c.cx, box_c.cy, box_c.cz],
[box_c.ox, box_c.oy, box_c.oz],
)
.map_err(|err| fail(err.into()))?;
let pts: &'a [[f64; 3]] = unsafe { std::slice::from_raw_parts(xyz.cast::<[f64; 3]>(), n) };
let mask_vec = if mask.is_null() {
None
} else {
let raw = unsafe { std::slice::from_raw_parts(mask, n) };
Some(raw.iter().map(|&v| v != 0).collect())
};
let hint = if cell_hint > 0.0 {
Some(cell_hint)
} else {
None
};
Ok((pts, sim, mask_vec, hint))
}
fn write_grid_head(grid: &crate::CellGrid, out_nxyz: *mut c_int, out_width: *mut f64) {
if !out_nxyz.is_null() {
unsafe {
*out_nxyz = grid.nx;
*out_nxyz.add(1) = grid.ny;
*out_nxyz.add(2) = grid.nz;
}
}
if !out_width.is_null() {
unsafe {
*out_width = grid.bin_width[0];
*out_width.add(1) = grid.bin_width[1];
*out_width.add(2) = grid.bin_width[2];
}
}
}
#[no_mangle]
pub unsafe extern "C" fn lc_cell_grid(
xyz: *const f64,
n: usize,
simbox: *const lc_cell,
cutoff: f64,
mask: *const c_int,
cell_hint: f64,
out_nxyz: *mut c_int,
out_width: *mut f64,
out_weight: *mut u64,
cap: usize,
out_ncell: *mut usize,
) -> c_int {
if out_ncell.is_null() {
return fail_msg("null pointer");
}
let (pts, sim, mask_vec, hint) = match unsafe { load_frame(xyz, n, simbox, mask, cell_hint) } {
Ok(v) => v,
Err(rc) => return rc,
};
let grid = match with_threads(|| crate::cell_grid(pts, &sim, cutoff, mask_vec.as_deref(), hint))
{
Ok(grid) => grid,
Err(err) => return fail(err),
};
let ncell = grid.ncell();
unsafe { *out_ncell = ncell };
if out_weight.is_null() {
clear_error();
return 0;
}
if cap < ncell || out_nxyz.is_null() || out_width.is_null() {
return fail_msg("cell grid buffer is shorter than the cell count");
}
write_grid_head(&grid, out_nxyz, out_width);
unsafe {
std::ptr::copy_nonoverlapping(grid.weight.as_ptr(), out_weight, ncell);
}
clear_error();
0
}
#[no_mangle]
pub unsafe extern "C" fn lc_cell_graph(
xyz: *const f64,
n: usize,
simbox: *const lc_cell,
cutoff: f64,
mask: *const c_int,
cell_hint: f64,
out_nxyz: *mut c_int,
out_width: *mut f64,
out_weight: *mut u64,
out_offsets: *mut u32,
out_neighbor: *mut u32,
out_edge: *mut u64,
cap_weight: usize,
cap_arcs: usize,
out_ncell: *mut usize,
out_arcs: *mut usize,
) -> c_int {
if out_ncell.is_null() || out_arcs.is_null() {
return fail_msg("null pointer");
}
let (pts, sim, mask_vec, hint) = match unsafe { load_frame(xyz, n, simbox, mask, cell_hint) } {
Ok(v) => v,
Err(rc) => return rc,
};
let graph =
match with_threads(|| crate::cell_graph(pts, &sim, cutoff, mask_vec.as_deref(), hint)) {
Ok(graph) => graph,
Err(err) => return fail(err),
};
let ncell = graph.grid.ncell();
let arcs = graph.neighbor.len();
unsafe {
*out_ncell = ncell;
*out_arcs = arcs;
}
if out_weight.is_null() {
clear_error();
return 0;
}
if cap_weight < ncell
|| cap_arcs < arcs
|| out_nxyz.is_null()
|| out_width.is_null()
|| out_offsets.is_null()
|| out_neighbor.is_null()
|| out_edge.is_null()
{
return fail_msg("cell graph buffer is shorter than the graph");
}
write_grid_head(&graph.grid, out_nxyz, out_width);
unsafe {
std::ptr::copy_nonoverlapping(graph.grid.weight.as_ptr(), out_weight, ncell);
std::ptr::copy_nonoverlapping(graph.offsets.as_ptr(), out_offsets, ncell + 1);
if arcs > 0 {
std::ptr::copy_nonoverlapping(graph.neighbor.as_ptr(), out_neighbor, arcs);
std::ptr::copy_nonoverlapping(graph.edge_weight.as_ptr(), out_edge, arcs);
}
}
clear_error();
0
}
#[no_mangle]
pub unsafe extern "C" fn lc_partition(
xyz: *const f64,
n: usize,
simbox: *const lc_cell,
cutoff: f64,
mask: *const c_int,
cell_hint: f64,
parts: usize,
method: u8,
balance: f64,
device: c_int,
out_domain: *mut c_int,
cap: usize,
out_ncell: *mut usize,
) -> c_int {
if out_ncell.is_null() {
return fail_msg("null pointer");
}
if parts == 0 || parts > u32::MAX as usize {
return fail(Error::BadPartition);
}
let (pts, sim, mask_vec, hint) = match unsafe { load_frame(xyz, n, simbox, mask, cell_hint) } {
Ok(v) => v,
Err(rc) => return rc,
};
let method = match crate::partition::method_from_c(method) {
Ok(method) => method,
Err(err) => return fail(err),
};
let balance = if balance <= 0.0 { None } else { Some(balance) };
let request = crate::PartRequest {
parts: parts as u32,
method,
balance,
device: device != 0,
};
let assign = match with_threads(|| {
crate::partition(pts, &sim, cutoff, mask_vec.as_deref(), hint, request)
}) {
Ok(assign) => assign,
Err(err) => return fail(err),
};
unsafe { *out_ncell = assign.len() };
if out_domain.is_null() {
clear_error();
return 0;
}
if cap < assign.len() {
return fail_msg("partition buffer is shorter than the cell count");
}
for (i, &domain) in assign.iter().enumerate() {
if domain > c_int::MAX as u32 {
return fail(Error::Overflow);
}
unsafe { *out_domain.add(i) = domain as c_int };
}
clear_error();
0
}
#[no_mangle]
pub unsafe extern "C" fn lc_halo_width(
cutoff: f64,
depth: u32,
bin_width: *const f64,
out_width: *mut u32,
) -> c_int {
if bin_width.is_null() || out_width.is_null() {
return fail_msg("null pointer");
}
let width = unsafe { [*bin_width, *bin_width.add(1), *bin_width.add(2)] };
match crate::halo_width(cutoff, depth, width) {
Ok(radius) => {
unsafe {
*out_width = radius[0];
*out_width.add(1) = radius[1];
*out_width.add(2) = radius[2];
}
clear_error();
0
}
Err(err) => fail(err),
}
}
#[no_mangle]
pub unsafe extern "C" fn lc_halo(
nxyz: *const c_int,
assign: *const c_int,
ncell: usize,
domain: c_int,
width: *const u32,
out_ghost: *mut c_int,
cap: usize,
out_count: *mut usize,
) -> c_int {
if nxyz.is_null() || assign.is_null() || width.is_null() || out_count.is_null() {
return fail_msg("null pointer");
}
if domain < 0 {
return fail(Error::BadPartition);
}
let nxyz = unsafe { [*nxyz, *nxyz.add(1), *nxyz.add(2)] };
if nxyz[0] <= 0 || nxyz[1] <= 0 || nxyz[2] <= 0 {
return fail(Error::BadGraph);
}
let expect = (nxyz[0] as usize)
.saturating_mul(nxyz[1] as usize)
.saturating_mul(nxyz[2] as usize);
if expect != ncell {
return fail(Error::BadGraph);
}
let raw = unsafe { std::slice::from_raw_parts(assign, ncell) };
let mut owned = Vec::with_capacity(ncell);
for &v in raw {
if v < 0 {
return fail(Error::BadPartition);
}
owned.push(v as u32);
}
let grid = crate::CellGrid {
nx: nxyz[0],
ny: nxyz[1],
nz: nxyz[2],
bin_width: [0.0; 3],
weight: vec![0; ncell],
};
let radius = unsafe { [*width, *width.add(1), *width.add(2)] };
let ghosts = match with_threads(|| crate::halo(&grid, &owned, domain as u32, radius)) {
Ok(ghosts) => ghosts,
Err(err) => return fail(err),
};
unsafe { *out_count = ghosts.len() };
if out_ghost.is_null() {
clear_error();
return 0;
}
if cap < ghosts.len() {
return fail_msg("halo buffer is shorter than the ghost count");
}
for (i, &cell) in ghosts.iter().enumerate() {
unsafe { *out_ghost.add(i) = cell as c_int };
}
clear_error();
0
}
#[no_mangle]
pub unsafe extern "C" fn lc_mesh_cut(
xyz: *const f64,
n: usize,
simbox: *const lc_cell,
cutoff: f64,
mask: *const c_int,
cell_hint: f64,
parts: usize,
method: u8,
balance: f64,
device: c_int,
out_nxyz: *mut c_int,
out_width: *mut f64,
out_domain: *mut c_int,
out_point_cell: *mut c_int,
cap_cell: usize,
cap_point: usize,
out_ncell: *mut usize,
) -> c_int {
if out_ncell.is_null() {
return fail_msg("null pointer");
}
if parts == 0 || parts > u32::MAX as usize {
return fail(Error::BadPartition);
}
let (pts, sim, mask_vec, hint) = match unsafe { load_frame(xyz, n, simbox, mask, cell_hint) } {
Ok(v) => v,
Err(rc) => return rc,
};
let method = match crate::partition::method_from_c(method) {
Ok(method) => method,
Err(err) => return fail(err),
};
let request = crate::PartRequest {
parts: parts as u32,
method,
balance: if balance <= 0.0 { None } else { Some(balance) },
device: device != 0,
};
let cut = match with_threads(|| {
crate::mesh_cut(pts, &sim, cutoff, mask_vec.as_deref(), hint, request)
}) {
Ok(cut) => cut,
Err(err) => return fail(err),
};
let ncell = cut.assign.len();
unsafe { *out_ncell = ncell };
if out_domain.is_null() {
clear_error();
return 0;
}
if out_nxyz.is_null()
|| out_width.is_null()
|| out_point_cell.is_null()
|| cap_cell < ncell
|| cap_point < n
{
return fail_msg("mesh cut buffer is shorter than the cell count");
}
write_grid_head(&cut.grid, out_nxyz, out_width);
for (i, &domain) in cut.assign.iter().enumerate() {
if domain > c_int::MAX as u32 {
return fail(Error::Overflow);
}
unsafe { *out_domain.add(i) = domain as c_int };
}
for (i, &cell) in cut.point_cell.iter().enumerate() {
if cell > c_int::MAX as u32 {
return fail(Error::Overflow);
}
unsafe { *out_point_cell.add(i) = cell as c_int };
}
clear_error();
0
}
#[no_mangle]
pub unsafe extern "C" fn lc_partition_weights(
nxyz: *const c_int,
weight: *const u64,
ncell: usize,
parts: usize,
method: u8,
balance: f64,
out_domain: *mut c_int,
) -> c_int {
if nxyz.is_null() || weight.is_null() || out_domain.is_null() {
return fail_msg("null pointer");
}
if parts == 0 || parts > u32::MAX as usize {
return fail(Error::BadPartition);
}
let nxyz = unsafe { [*nxyz, *nxyz.add(1), *nxyz.add(2)] };
if nxyz[0] <= 0 || nxyz[1] <= 0 || nxyz[2] <= 0 {
return fail(Error::BadGraph);
}
let expect = (nxyz[0] as usize)
.saturating_mul(nxyz[1] as usize)
.saturating_mul(nxyz[2] as usize);
if expect != ncell {
return fail(Error::BadGraph);
}
let method = match crate::partition::method_from_c(method) {
Ok(method) => method,
Err(err) => return fail(err),
};
let raw = unsafe { std::slice::from_raw_parts(weight, ncell) };
let graph = crate::CellGraph {
grid: crate::CellGrid {
nx: nxyz[0],
ny: nxyz[1],
nz: nxyz[2],
bin_width: [1.0; 3],
weight: raw.to_vec(),
},
offsets: vec![0u32; ncell + 1],
neighbor: Vec::new(),
edge_weight: Vec::new(),
};
let request = crate::PartRequest {
parts: parts as u32,
method,
balance: if balance <= 0.0 { None } else { Some(balance) },
device: false,
};
let assign = match with_threads(|| crate::partition_graph(&graph, request)) {
Ok(assign) => assign,
Err(err) => return fail(err),
};
for (i, &domain) in assign.iter().enumerate() {
if domain > c_int::MAX as u32 {
return fail(Error::Overflow);
}
unsafe { *out_domain.add(i) = domain as c_int };
}
clear_error();
0
}
#[no_mangle]
pub unsafe extern "C" fn lc_within_reach(
xyz: *const f64,
n: usize,
lengths: *const f64,
nxyz: *const c_int,
assign: *const c_int,
ncell: usize,
point_cell: *const c_int,
hwidth: *const u32,
domain: c_int,
reach: f64,
out_hit: *mut c_int,
) -> c_int {
if xyz.is_null()
|| lengths.is_null()
|| nxyz.is_null()
|| assign.is_null()
|| point_cell.is_null()
|| hwidth.is_null()
|| out_hit.is_null()
|| domain < 0
{
return fail_msg("null pointer");
}
let pts: Vec<[f64; 3]> =
unsafe { std::slice::from_raw_parts(xyz.cast::<[f64; 3]>(), n) }.to_vec();
let lengths = unsafe { [*lengths, *lengths.add(1), *lengths.add(2)] };
let nxyz = unsafe { [*nxyz, *nxyz.add(1), *nxyz.add(2)] };
let hwidth = unsafe { [*hwidth, *hwidth.add(1), *hwidth.add(2)] };
let assign_raw = unsafe { std::slice::from_raw_parts(assign, ncell) };
let mut owned = Vec::with_capacity(ncell);
for &v in assign_raw {
if v < 0 {
return fail(Error::BadPartition);
}
owned.push(v as u32);
}
let cells_raw = unsafe { std::slice::from_raw_parts(point_cell, n) };
let mut cells = Vec::with_capacity(n);
for &v in cells_raw {
if v < 0 {
return fail(Error::BadPartition);
}
cells.push(v as u32);
}
let hit = match with_threads(|| {
crate::mark_reached(
&pts,
lengths,
nxyz,
&owned,
&cells,
hwidth,
domain as u32,
reach,
)
}) {
Ok(hit) => hit,
Err(err) => return fail(err),
};
for (i, &flag) in hit.iter().enumerate() {
unsafe { *out_hit.add(i) = flag as c_int };
}
clear_error();
0
}
#[no_mangle]
pub unsafe extern "C" fn lc_owned_mask(
nxyz: *const c_int,
assign: *const c_int,
ncell: usize,
point_cell: *const c_int,
n: usize,
domain: c_int,
width: *const u32,
out_hit: *mut c_int,
) -> c_int {
if nxyz.is_null()
|| assign.is_null()
|| point_cell.is_null()
|| width.is_null()
|| out_hit.is_null()
|| domain < 0
{
return fail_msg("null pointer");
}
let nxyz = unsafe { [*nxyz, *nxyz.add(1), *nxyz.add(2)] };
if nxyz[0] <= 0 || nxyz[1] <= 0 || nxyz[2] <= 0 {
return fail(Error::BadGraph);
}
let expect = (nxyz[0] as usize)
.saturating_mul(nxyz[1] as usize)
.saturating_mul(nxyz[2] as usize);
if expect != ncell {
return fail(Error::BadGraph);
}
let assign_raw = unsafe { std::slice::from_raw_parts(assign, ncell) };
let mut owned_assign = Vec::with_capacity(ncell);
let mut owned_cells = Vec::new();
for (cell, &v) in assign_raw.iter().enumerate() {
if v < 0 {
return fail(Error::BadPartition);
}
let domain_id = v as u32;
if domain_id == domain as u32 {
owned_cells.push(cell as u32);
}
owned_assign.push(domain_id);
}
let cells_raw = unsafe { std::slice::from_raw_parts(point_cell, n) };
let mut point_bins = Vec::with_capacity(n);
for &v in cells_raw {
if v < 0 || v as usize >= ncell {
return fail(Error::BadPartition);
}
point_bins.push(v as u32);
}
let width = unsafe { [*width, *width.add(1), *width.add(2)] };
let grid = crate::CellGrid {
nx: nxyz[0],
ny: nxyz[1],
nz: nxyz[2],
bin_width: [1.0; 3],
weight: vec![0; ncell],
};
let view = with_threads(|| {
crate::rank_mask(
&grid,
&owned_assign,
&point_bins,
&owned_cells,
domain as u32,
width,
)
});
for (i, &painted) in view.mask.iter().enumerate() {
let flag = if !painted {
0
} else if owned_assign[point_bins[i] as usize] == domain as u32 {
2
} else {
1
};
unsafe { *out_hit.add(i) = flag };
}
clear_error();
0
}