1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
//! Point-cloud thinning algorithms: grid (voxel), random (LCG), Poisson disk.
//!
//! Point-cloud thinning is the task of reducing the cardinality of a 3D point
//! set while preserving some structural property of the cloud. Three classical
//! strategies are provided here:
//!
//! - **Grid (voxel) thinning** ([`thin_grid`]) partitions space into cubic
//! voxels of side `cell_size` and keeps the *first* point that falls into
//! each voxel (in input order). This produces a roughly uniform sub-sample
//! at the resolution of the voxel grid and is the standard approach used by
//! PDAL's `filters.sample` and CloudCompare's "subsample with octree".
//! - **Random thinning** ([`thin_random`]) uniformly draws `target_count`
//! indices without replacement via a deterministic Fisher-Yates shuffle.
//! The shuffle is driven by a linear congruential generator (LCG) using
//! Knuth's MMIX constants — this satisfies the project policy of *no
//! `rand`-crate dependency* while remaining reproducible across runs and
//! platforms.
//! - **Poisson-disk thinning** ([`thin_poisson_disk`]) implements Bridson's
//! spatial-hash dart-throwing in 3D: every candidate point is accepted only
//! if no previously kept point lies within `min_distance` of it. The spatial
//! hash uses cubic buckets of side `min_distance`, so each acceptance test
//! examines at most the 27 neighbouring buckets — giving expected O(N)
//! runtime, an order of magnitude faster than a naive O(N^2) sweep.
//!
//! All three operators are deterministic functions of their inputs (the random
//! and Poisson-disk variants additionally take a `seed`), preserve input order
//! in their output and return owned `Vec<ThinPoint3>` so the caller may freely
//! mutate the result. Thinning statistics ([`ThinningStats`]) can be obtained
//! in one call via [`thin_with_stats`].
//!
//! # Examples
//!
//! ```
//! use oxigdal_algorithms::raster::{ThinPoint3, ThinningMethod, thin_with_stats};
//!
//! let points = vec![
//! ThinPoint3::new(0.0, 0.0, 0.0),
//! ThinPoint3::new(0.1, 0.2, 0.3),
//! ThinPoint3::new(5.0, 5.0, 5.0),
//! ];
//! let (kept, stats) = thin_with_stats(
//! &points,
//! ThinningMethod::Grid { cell_size: 1.0 },
//! );
//! assert_eq!(stats.input_count, 3);
//! assert_eq!(stats.kept_count, kept.len());
//! ```
use HashMap;
// ---------------------------------------------------------------------------
// Public types
// ---------------------------------------------------------------------------
/// A 3D sample point used as input to point-cloud thinning operators.
///
/// `ThinPoint3` is intentionally a Plain-Old-Data struct: it carries no
/// auxiliary attributes (intensity, classification, …) because the thinning
/// operators only depend on the geometric coordinates. Callers that need to
/// preserve attributes typically build a parallel `Vec<Attr>` indexed in the
/// same order as their `Vec<ThinPoint3>` and re-index it using the order of
/// the returned point vector.
/// Selection of thinning algorithm and its parameters.
///
/// This enum is the input to [`thin_with_stats`]; each variant carries the
/// parameters needed by exactly one of the public thinning functions.
/// Summary statistics for a single thinning invocation.
// ---------------------------------------------------------------------------
// Deterministic LCG (no `rand` crate dependency)
// ---------------------------------------------------------------------------
/// One step of Knuth's MMIX 64-bit linear congruential generator.
///
/// `x_{n+1} = a * x_n + c` with `a = 6364136223846793005` and
/// `c = 1442695040888963407`. Both constants are taken from Knuth's *Art of
/// Computer Programming* Vol. 2 §3.3.4, Table 1, line 26 ("MMIX") and yield a
/// full period of 2^64. Wrapping arithmetic is intentional: modular reduction
/// modulo 2^64 is part of the LCG definition.
/// In-place Fisher-Yates shuffle driven by [`lcg_next`].
///
/// The top 32 bits of the LCG state are used to select the swap target, since
/// the low-order bits of a power-of-two-modulus LCG have short periods (this
/// is a well-known weakness of LCGs documented by L'Ecuyer 1990 and others).
/// The `seed.wrapping_add(1)` step prevents the degenerate fixed point at
/// `state == 0`, which would otherwise collapse the shuffle to the identity.
// ---------------------------------------------------------------------------
// Grid (voxel) thinning
// ---------------------------------------------------------------------------
/// Grid (voxel) thinning: keep one point per cubic voxel of side `cell_size`.
///
/// The voxel containing a point `(x, y, z)` is identified by the integer
/// triple `(floor(x / s), floor(y / s), floor(z / s))` where `s == cell_size`.
/// The *first* point (in input order) that lands in each voxel is kept; later
/// arrivals are silently discarded. This is the same convention used by
/// PDAL's `filters.sample` and is preferred over "voxel centroid" thinning
/// when the caller needs to preserve original point identities (for example
/// to carry classification or RGB attributes through the thinning step).
///
/// Edge cases:
///
/// - Empty input returns an empty `Vec`.
/// - `cell_size <= 0.0` returns a copy of the input (no thinning).
/// - Points with non-finite coordinates are bucketed by `floor(NaN) as i64`,
/// which the standard library defines as `i64::MIN` for NaN — so all NaN
/// points map into the same degenerate voxel and only the first is kept.
///
/// # Examples
///
/// ```
/// use oxigdal_algorithms::raster::{ThinPoint3, thin_grid};
///
/// // Three points in the same unit voxel collapse to one.
/// let pts = vec![
/// ThinPoint3::new(0.1, 0.1, 0.1),
/// ThinPoint3::new(0.5, 0.5, 0.5),
/// ThinPoint3::new(0.9, 0.9, 0.9),
/// ];
/// let kept = thin_grid(&pts, 1.0);
/// assert_eq!(kept.len(), 1);
/// assert_eq!(kept[0], ThinPoint3::new(0.1, 0.1, 0.1));
/// ```
/// Map a point to its containing voxel under voxel side `cell_size`.
// ---------------------------------------------------------------------------
// Random thinning
// ---------------------------------------------------------------------------
/// Random thinning: keep `target_count` points selected uniformly without
/// replacement via a deterministic Fisher-Yates shuffle.
///
/// The shuffle is driven by an internal LCG (`lcg_next`) rather than the
/// `rand` crate, in keeping with the project's *no `rand`* dependency policy.
/// Identical `seed` values produce identical outputs across runs and across
/// platforms (the LCG state is a `u64` and only `wrapping_*` arithmetic is
/// used). Output points are returned in input order — the shuffle is applied
/// to an index vector, the first `target_count` indices are retained, and the
/// final point vector is materialised in the original order.
///
/// Edge cases:
///
/// - Empty input returns an empty `Vec`.
/// - `target_count >= points.len()` returns a copy of the input (no thinning).
/// - `target_count == 0` returns an empty `Vec`.
///
/// # Examples
///
/// ```
/// use oxigdal_algorithms::raster::{ThinPoint3, thin_random};
///
/// let pts: Vec<_> = (0..100)
/// .map(|i| ThinPoint3::new(i as f64, 0.0, 0.0))
/// .collect();
/// let a = thin_random(&pts, 10, 0xC0FFEE);
/// let b = thin_random(&pts, 10, 0xC0FFEE);
/// assert_eq!(a, b); // deterministic for a given seed
/// assert_eq!(a.len(), 10);
/// ```
// ---------------------------------------------------------------------------
// Poisson-disk thinning
// ---------------------------------------------------------------------------
/// Poisson-disk thinning: keep a maximal greedy subset such that every pair
/// of kept points is at least `min_distance` apart in 3D Euclidean distance.
///
/// This is the spatial-hash variant of Bridson's 2007 dart-throwing
/// algorithm specialised to the case where the candidate pool is a fixed,
/// pre-existing point set (so the "active list" reduces to the shuffled
/// input order). The spatial hash uses cubic buckets of side `min_distance`:
/// any kept point within `min_distance` of a candidate must lie in one of the
/// 27 buckets adjacent to the candidate's own bucket (including the
/// candidate's bucket itself), so each acceptance test inspects at most 27
/// buckets of constant expected occupancy — yielding expected `O(N)`
/// runtime on uniformly distributed inputs.
///
/// The input order is randomised by an LCG-driven Fisher-Yates shuffle
/// (see `lcg_shuffle`) before greedy acceptance, so identical `seed`
/// values produce identical outputs while avoiding the directional bias
/// of always favouring early input points. Output points are returned in
/// original input order: after the greedy pass the kept indices are
/// sorted ascending and the point vector is materialised from that order.
///
/// Edge cases:
///
/// - Empty input returns an empty `Vec`.
/// - `min_distance <= 0.0` returns a copy of the input (no thinning).
///
/// # Complexity
///
/// Expected `O(N)` time and `O(N)` extra space (the spatial hash and kept-index
/// vector together). Worst case (all points colliding into one bucket) is
/// `O(N^2)`, but this requires pathological clustering at the bucket scale.
///
/// # Examples
///
/// ```
/// use oxigdal_algorithms::raster::{ThinPoint3, thin_poisson_disk};
///
/// // Eight points along a line, separated by 0.1: at min_distance=0.25 we
/// // keep one in three (roughly).
/// let pts: Vec<_> = (0..8)
/// .map(|i| ThinPoint3::new(0.1 * i as f64, 0.0, 0.0))
/// .collect();
/// let kept = thin_poisson_disk(&pts, 0.25, 42);
/// assert!(kept.len() < pts.len());
/// // Every pair is at least 0.25 apart.
/// for (i, p) in kept.iter().enumerate() {
/// for q in &kept[i + 1..] {
/// let d = ((p.x - q.x).powi(2) + (p.y - q.y).powi(2) + (p.z - q.z).powi(2)).sqrt();
/// assert!(d >= 0.25);
/// }
/// }
/// ```
// ---------------------------------------------------------------------------
// Dispatcher with stats
// ---------------------------------------------------------------------------
/// Dispatch [`ThinningMethod`] and return both the thinned point set and a
/// [`ThinningStats`] summary.
///
/// This is the recommended entry point for callers that need to report on
/// how aggressive the thinning was, or that want to switch algorithms based
/// on configuration without duplicating the dispatching boilerplate.
///
/// # Examples
///
/// ```
/// use oxigdal_algorithms::raster::{ThinPoint3, ThinningMethod, thin_with_stats};
///
/// let pts: Vec<_> = (0..1000)
/// .map(|i| ThinPoint3::new(i as f64, 0.0, 0.0))
/// .collect();
/// let (kept, stats) = thin_with_stats(
/// &pts,
/// ThinningMethod::Random { target_count: 100, seed: 7 },
/// );
/// assert_eq!(stats.input_count, 1000);
/// assert_eq!(stats.kept_count, 100);
/// assert!((stats.reduction_ratio - 0.9).abs() < 1e-12);
/// assert_eq!(kept.len(), 100);
/// ```
// ---------------------------------------------------------------------------
// Unit tests
// ---------------------------------------------------------------------------