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
use crate::error::SpatialResult;
use crate::rtree::node::{Entry, Node, RTree, Rectangle};
use scirs2_core::ndarray::ArrayView1;
impl<T: Clone> RTree<T> {
/// Delete a data point from the R-tree
///
/// # Arguments
///
/// * `point` - The point coordinates to delete
/// * `data_predicate` - An optional function that takes a reference to the data and returns
/// true if it should be deleted. This is useful when multiple data points share the same coordinates.
///
/// # Returns
///
/// A `SpatialResult` containing true if a point was deleted, false otherwise
pub fn delete<F>(
&mut self,
point: &ArrayView1<f64>,
data_predicate: Option<F>,
) -> SpatialResult<bool>
where
F: Fn(&T) -> bool + Copy,
{
if point.len() != self.ndim() {
return Err(crate::error::SpatialError::DimensionError(format!(
"Point dimension {} does not match RTree dimension {}",
point.len(),
self.ndim()
)));
}
// Create a rectangle for the point
let mbr = Rectangle::from_point(point);
// Find the leaf node(s) containing the point
// Create a new empty root for swapping
let mut root = std::mem::take(&mut self.root);
let result = self.delete_internal(&mbr, &mut root, data_predicate)?;
self.root = root;
// If a point was deleted, decrement the size
if result {
self.decrement_size();
// If the root has only one child and it's not a leaf, make the child the new root
if !self.root._isleaf && self.root.size() == 1 {
if let Entry::NonLeaf { child, .. } = &self.root.entries[0] {
let new_root = (**child).clone();
self.root = new_root;
// Height is decremented here (would normally use self.height -= 1)
}
}
}
Ok(result)
}
/// Helper function to delete a point from a subtree
#[allow(clippy::type_complexity)]
fn delete_internal<F>(
&mut self,
mbr: &Rectangle,
node: &mut Node<T>,
data_predicate: Option<F>,
) -> SpatialResult<bool>
where
F: Fn(&T) -> bool + Copy,
{
// If this is a leaf node, look for the entry to delete
if node._isleaf {
let mut found_index = None;
for (i, entry) in node.entries.iter().enumerate() {
if let Entry::Leaf {
mbr: entry_mbr,
data,
..
} = entry
{
// Check if the MBRs match
if entry_mbr.min == mbr.min && entry_mbr.max == mbr.max {
// If a _predicate is provided, check it too
if let Some(ref pred) = data_predicate {
if pred(data) {
found_index = Some(i);
break;
}
} else {
// No predicate, just delete the first matching entry
found_index = Some(i);
break;
}
}
}
}
// If an entry was found, remove it
if let Some(index) = found_index {
node.entries.remove(index);
return Ok(true);
}
return Ok(false);
}
// For non-leaf nodes, find all child nodes that could contain the point
let mut deleted = false;
for i in 0..node.size() {
let entry_mbr = node.entries[i].mbr();
// Check if this entry's MBR intersects with the search MBR
if entry_mbr.intersects(mbr)? {
// Get the child node
if let Entry::NonLeaf { child, .. } = &mut node.entries[i] {
// Recursively delete from the child using raw pointers to avoid borrow issues
let child_ptr = Box::as_mut(child) as *mut Node<T>;
let result =
unsafe { self.delete_internal(mbr, &mut *child_ptr, data_predicate)? };
if result {
deleted = true;
// Check if the child node is underfull
if child.size() < self.min_entries && child.size() > 0 {
// Handle underfull child node
self.handle_underfull_node(node, i)?;
} else if child.size() == 0 {
// Remove empty child node
node.entries.remove(i);
} else {
// Update the MBR of the parent entry
if let Ok(Some(child_mbr)) = child.mbr() {
if let Entry::NonLeaf { mbr, .. } = &mut node.entries[i] {
*mbr = child_mbr;
}
}
}
break;
}
}
}
}
Ok(deleted)
}
/// Handle an underfull node by either merging it with a sibling or redistributing entries
fn handle_underfull_node(
&mut self,
parent: &mut Node<T>,
child_index: usize,
) -> SpatialResult<()> {
// Get the child node
let child: &Box<Node<T>> = match &parent.entries[child_index] {
Entry::NonLeaf { child, .. } => child,
Entry::Leaf { .. } => {
return Err(crate::error::SpatialError::ComputationError(
"Expected a non-leaf entry".into(),
))
}
};
// Find the best sibling to merge with
let mut best_sibling_index = None;
let mut min_merged_area = f64::MAX;
for i in 0..parent.size() {
if i == child_index {
continue;
}
// Get the sibling's MBR
let sibling_mbr = parent.entries[i].mbr();
// Get the child's MBR
let child_mbr = child
.mbr()
.unwrap_or_else(|_| Some(Rectangle::from_point(&Array1::zeros(self.ndim()).view())))
.unwrap_or_else(|| Rectangle::from_point(&Array1::zeros(self.ndim()).view()));
// Calculate the area of the merged MBR
let merged_mbr = child_mbr.enlarge(sibling_mbr)?;
let merged_area = merged_mbr.area();
if merged_area < min_merged_area {
min_merged_area = merged_area;
best_sibling_index = Some(i);
}
}
// If no sibling was found, return (this shouldn't happen)
let best_sibling_index = best_sibling_index.unwrap_or(0);
if best_sibling_index == child_index {
return Ok(());
}
// Get the sibling
let sibling: &Box<Node<T>> = match &parent.entries[best_sibling_index] {
Entry::NonLeaf { child, .. } => child,
Entry::Leaf { .. } => {
return Err(crate::error::SpatialError::ComputationError(
"Expected a non-leaf entry".into(),
))
}
};
// If the sibling has enough entries, we can redistribute
if sibling.size() > self.min_entries {
// Implement entry redistribution
// Get mutable references to both child and sibling
let (child_idx, sibling_idx) = if child_index < best_sibling_index {
(child_index, best_sibling_index)
} else {
(best_sibling_index, child_index)
};
// Extract entries from parent temporarily
let mut child_entry = parent.entries.remove(child_idx);
let mut sibling_entry = parent.entries.remove(if sibling_idx > child_idx {
sibling_idx - 1
} else {
sibling_idx
});
// Get mutable references to the nodes
let child_node: &mut Box<Node<T>> = match &mut child_entry {
Entry::NonLeaf { child, .. } => child,
Entry::Leaf { .. } => {
return Err(crate::error::SpatialError::ComputationError(
"Expected a non-leaf entry for child node".into(),
))
}
};
let sibling_node: &mut Box<Node<T>> = match &mut sibling_entry {
Entry::NonLeaf { child, .. } => child,
Entry::Leaf { .. } => {
return Err(crate::error::SpatialError::ComputationError(
"Expected a non-leaf entry for sibling node".into(),
))
}
};
// Calculate how many entries to move
let total_entries = child_node.size() + sibling_node.size();
let target_child_size = total_entries / 2;
// Move entries from sibling to child if child has fewer entries
while child_node.size() < target_child_size && !sibling_node.entries.is_empty() {
let entry = sibling_node.entries.remove(0);
child_node.entries.push(entry);
}
// Update MBRs
if let Ok(Some(child_mbr)) = child_node.mbr() {
if let Entry::NonLeaf { mbr, .. } = &mut child_entry {
*mbr = child_mbr;
}
}
if let Ok(Some(sibling_mbr)) = sibling_node.mbr() {
if let Entry::NonLeaf { mbr, .. } = &mut sibling_entry {
*mbr = sibling_mbr;
}
}
// Put entries back in parent
parent.entries.insert(child_idx, child_entry);
parent.entries.insert(
if sibling_idx > child_idx {
sibling_idx
} else {
sibling_idx + 1
},
sibling_entry,
);
Ok(())
} else {
// Otherwise, merge the nodes
// Remove both entries from parent
let (smaller_idx, larger_idx) = if child_index < best_sibling_index {
(child_index, best_sibling_index)
} else {
(best_sibling_index, child_index)
};
let mut child_entry = parent.entries.remove(smaller_idx);
let sibling_entry = parent.entries.remove(larger_idx - 1);
// Get the nodes
let child_node: &mut Box<Node<T>> = match &mut child_entry {
Entry::NonLeaf { child, .. } => child,
Entry::Leaf { .. } => {
return Err(crate::error::SpatialError::ComputationError(
"Expected a non-leaf entry for child node".into(),
))
}
};
let sibling_node: Box<Node<T>> = match sibling_entry {
Entry::NonLeaf { child, .. } => child,
Entry::Leaf { .. } => {
return Err(crate::error::SpatialError::ComputationError(
"Expected a non-leaf entry for sibling node".into(),
))
}
};
// Move all entries from sibling to child
for entry in sibling_node.entries {
child_node.entries.push(entry);
}
// Update MBR of merged node
if let Ok(Some(merged_mbr)) = child_node.mbr() {
if let Entry::NonLeaf { mbr, .. } = &mut child_entry {
*mbr = merged_mbr;
}
}
// Put the merged node back
parent.entries.insert(smaller_idx, child_entry);
// If parent is now underfull and is not the root, it needs handling too
// This would be handled by the caller
Ok(())
}
}
}
use scirs2_core::ndarray::Array1;
#[cfg(test)]
mod tests {
use super::*;
use scirs2_core::ndarray::array;
#[test]
fn test_rtree_delete() {
// Create a new R-tree
let mut rtree: RTree<i32> = RTree::new(2, 2, 4).expect("Operation failed");
// Insert some points
let points = vec![
(array![0.0, 0.0], 0),
(array![1.0, 0.0], 1),
(array![0.0, 1.0], 2),
(array![1.0, 1.0], 3),
(array![0.5, 0.5], 4),
];
for (point, value) in points {
rtree.insert(point, value).expect("Operation failed");
}
// Delete a point
let result = rtree
.delete::<fn(&i32) -> bool>(&array![0.5, 0.5].view(), None)
.expect("Operation failed");
assert!(result);
// Check the size
assert_eq!(rtree.size(), 4);
// Try to delete a point that doesn't exist
let result = rtree
.delete::<fn(&i32) -> bool>(&array![2.0, 2.0].view(), None)
.expect("Operation failed");
assert!(!result);
// Check the size
assert_eq!(rtree.size(), 4);
// Delete all remaining points
let result = rtree
.delete::<fn(&i32) -> bool>(&array![0.0, 0.0].view(), None)
.expect("Operation failed");
assert!(result);
let result = rtree
.delete::<fn(&i32) -> bool>(&array![1.0, 0.0].view(), None)
.expect("Operation failed");
assert!(result);
let result = rtree
.delete::<fn(&i32) -> bool>(&array![0.0, 1.0].view(), None)
.expect("Operation failed");
assert!(result);
let result = rtree
.delete::<fn(&i32) -> bool>(&array![1.0, 1.0].view(), None)
.expect("Operation failed");
assert!(result);
// Check the size
assert_eq!(rtree.size(), 0);
assert!(rtree.is_empty());
}
}