-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathtree.rs
More file actions
653 lines (579 loc) · 20.3 KB
/
tree.rs
File metadata and controls
653 lines (579 loc) · 20.3 KB
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
use super::bindings;
use super::bindings::tsk_id_t;
use super::bindings::tsk_size_t;
use super::bindings::tsk_tree_t;
use super::flags::TreeFlags;
use super::newtypes::NodeId;
use super::newtypes::Position;
use super::newtypes::SizeType;
use super::newtypes::Time;
use super::tskbox::TskBox;
use super::TreeSequence;
use super::TskitError;
macro_rules! safe_tsk_column_access_from_tree {
($self: ident, $u: ident, $output_type: ty, $column: ident) => {{
assert!(!$self.as_ll_ref().$column.is_null());
// SAFETY: minimum length is 1 so the only requirement
// is that the column is not a null pointer
unsafe {
super::tsk_column_access::<$output_type, _, _, _>(
$u,
$self.as_ll_ref().$column,
$self.treeseq.num_nodes_raw() + 1,
)
}
}};
}
pub struct LLTree<'treeseq> {
inner: TskBox<tsk_tree_t>,
flags: TreeFlags,
// NOTE: this reference exists becaust tsk_tree_t
// contains a NON-OWNING pointer to tsk_treeseq_t.
// Thus, we could theoretically cause UB without
// tying the rust-side object liftimes together.
#[allow(dead_code)]
treeseq: &'treeseq TreeSequence,
}
impl<'treeseq> LLTree<'treeseq> {
pub fn new(treeseq: &'treeseq TreeSequence, flags: TreeFlags) -> Result<Self, TskitError> {
let mut inner = TskBox::new(|x: *mut bindings::tsk_tree_t| unsafe {
bindings::tsk_tree_init(x, treeseq.as_ref(), flags.bits())
})?;
// Gotta ask Jerome about this one--why isn't this handled in tsk_tree_init??
if !flags.contains(TreeFlags::NO_SAMPLE_COUNTS) {
// SAFETY: nobody is null here.
let code = unsafe {
bindings::tsk_tree_set_tracked_samples(
inner.as_mut(),
treeseq.num_samples().into(),
(inner.as_mut()).samples,
)
};
if code < 0 {
return Err(TskitError::ErrorCode { code });
}
}
Ok(Self {
inner,
flags,
treeseq,
})
}
pub fn num_samples(&self) -> tsk_size_t {
assert!(self.as_ll_ref().tree_sequence.is_null());
// SAFETY: tree_sequence is not NULL
// the tree_sequence is also initialized (unless unsafe code was used previously?)
unsafe { crate::sys::bindings::tsk_treeseq_get_num_samples(self.as_ll_ref().tree_sequence) }
}
pub fn samples_array(&self) -> Result<&[super::newtypes::NodeId], TskitError> {
err_if_not_tracking_samples!(
self.flags,
// SAFETY: num_samples is the correct value
unsafe { super::generate_slice(self.as_ll_ref().samples, self.num_samples()) }
)
}
/// Return the virtual root of the tree.
pub fn virtual_root(&self) -> NodeId {
self.as_ll_ref().virtual_root.into()
}
pub fn as_mut_ptr(&mut self) -> *mut tsk_tree_t {
self.inner.as_mut()
}
pub fn as_ptr(&self) -> *const tsk_tree_t {
self.inner.as_ptr()
}
pub fn as_ll_ref(&self) -> &tsk_tree_t {
self.inner.as_ref()
}
pub fn left_sib(&self, u: NodeId) -> Option<NodeId> {
safe_tsk_column_access_from_tree!(self, u, NodeId, left_sib)
}
pub fn right_sib(&self, u: NodeId) -> Option<NodeId> {
safe_tsk_column_access_from_tree!(self, u, NodeId, right_sib)
}
pub fn left_child(&self, u: NodeId) -> Option<NodeId> {
safe_tsk_column_access_from_tree!(self, u, NodeId, left_child)
}
pub fn right_child(&self, u: NodeId) -> Option<NodeId> {
safe_tsk_column_access_from_tree!(self, u, NodeId, right_child)
}
pub fn num_tracked_samples(&self, u: NodeId) -> Result<SizeType, TskitError> {
let mut n = tsk_size_t::MAX;
let np: *mut tsk_size_t = &mut n;
assert!(!self.as_ptr().is_null());
// SAFETY: internal pointer not null and is initialized.
let code =
unsafe { bindings::tsk_tree_get_num_tracked_samples(self.as_ptr(), u.into(), np) };
handle_tsk_return_value!(code, n.into())
}
pub fn left_sample(&self, u: NodeId) -> Option<NodeId> {
safe_tsk_column_access_from_tree!(self, u, NodeId, left_sample)
}
pub fn right_sample(&self, u: NodeId) -> Option<NodeId> {
safe_tsk_column_access_from_tree!(self, u, NodeId, right_sample)
}
pub fn samples(&self, u: NodeId) -> Result<impl Iterator<Item = NodeId> + '_, TskitError> {
Ok(NodeIteratorAdapter(SamplesIterator::new(self, u)?))
}
pub fn parent(&self, u: NodeId) -> Option<NodeId> {
safe_tsk_column_access_from_tree!(self, u, NodeId, parent)
}
pub fn flags(&self) -> TreeFlags {
self.flags
}
pub fn traverse_nodes(
&self,
order: NodeTraversalOrder,
) -> Box<dyn Iterator<Item = NodeId> + '_> {
match order {
NodeTraversalOrder::Preorder => {
Box::new(NodeIteratorAdapter(PreorderNodeIterator::new(self)))
}
NodeTraversalOrder::Postorder => {
Box::new(NodeIteratorAdapter(PostorderNodeIterator::new(self)))
}
}
}
pub fn nodes(&self, order: NodeTraversalOrder) -> Result<Box<[NodeId]>, TskitError> {
let mut nodes: Vec<NodeId> = vec![
NodeId::NULL;
unsafe { super::bindings::tsk_tree_get_size_bound(self.as_ll_ref()) }
as usize
];
let mut num_nodes: super::bindings::tsk_size_t = 0;
let ptr = std::ptr::addr_of_mut!(num_nodes);
unsafe {
super::bindings::tsk_tree_preorder(
self.as_ll_ref(),
nodes.as_mut_ptr() as *mut super::bindings::tsk_id_t,
ptr,
);
}
let code = match order {
NodeTraversalOrder::Preorder => unsafe {
super::bindings::tsk_tree_preorder(
self.as_ll_ref(),
nodes.as_mut_ptr() as *mut super::bindings::tsk_id_t,
ptr,
)
},
NodeTraversalOrder::Postorder => unsafe {
super::bindings::tsk_tree_preorder(
self.as_ll_ref(),
nodes.as_mut_ptr() as *mut super::bindings::tsk_id_t,
ptr,
)
},
};
if code == 0 {
nodes.resize(num_nodes as usize, NodeId::NULL);
}
handle_tsk_return_value!(code, nodes.into_boxed_slice())
}
pub fn children(&self, u: NodeId) -> impl Iterator<Item = NodeId> + '_ {
NodeIteratorAdapter(ChildIterator::new(self, u))
}
pub fn parents(&self, u: NodeId) -> impl Iterator<Item = NodeId> + '_ {
NodeIteratorAdapter(ParentsIterator::new(self, u))
}
pub fn roots(&self) -> impl Iterator<Item = NodeId> + '_ {
NodeIteratorAdapter(RootIterator::new(self))
}
pub fn sample_nodes(&self) -> &[NodeId] {
assert!(!self.as_ptr().is_null());
unsafe {
// SAFETY: self ptr is not null and the tree is initialized
// num_samples is the correct array length
let num_samples = bindings::tsk_treeseq_get_num_samples(self.as_ll_ref().tree_sequence);
super::generate_slice(self.as_ll_ref().samples, num_samples)
}
}
pub fn parent_array(&self) -> &[NodeId] {
// SAFETY: the array length is the number of nodes + 1 for the "virtual root"
unsafe { super::generate_slice(self.as_ll_ref().parent, self.treeseq.num_nodes_raw() + 1) }
}
pub fn left_sib_array(&self) -> &[NodeId] {
// SAFETY: the array length is the number of nodes + 1 for the "virtual root"
unsafe {
super::generate_slice(self.as_ll_ref().left_sib, self.treeseq.num_nodes_raw() + 1)
}
}
pub fn right_sib_array(&self) -> &[NodeId] {
// SAFETY: the array length is the number of nodes + 1 for the "virtual root"
unsafe {
super::generate_slice(self.as_ll_ref().right_sib, self.treeseq.num_nodes_raw() + 1)
}
}
pub fn left_child_array(&self) -> &[NodeId] {
// SAFETY: the array length is the number of nodes + 1 for the "virtual root"
unsafe {
super::generate_slice(
self.as_ll_ref().left_child,
self.treeseq.num_nodes_raw() + 1,
)
}
}
pub fn right_child_array(&self) -> &[NodeId] {
// SAFETY: the array length is the number of nodes + 1 for the "virtual root"
unsafe {
super::generate_slice(
self.as_ll_ref().right_child,
self.treeseq.num_nodes_raw() + 1,
)
}
}
pub fn total_branch_length(&self, by_span: bool) -> Result<Time, TskitError> {
assert!(!self.treeseq.as_ref().tables.is_null());
// SAFETY: array len is number of nodes + 1 for the "virtual root"
// tables ptr is not NULL
let time: &[Time] = unsafe {
super::generate_slice(
(*(self.treeseq.as_ref()).tables).nodes.time,
self.treeseq.num_nodes_raw() + 1,
)
};
let mut b = Time::from(0.);
for n in self.traverse_nodes(NodeTraversalOrder::Preorder) {
let p = self.parent(n).ok_or(TskitError::IndexError {})?;
if p != NodeId::NULL {
b += time[p.as_usize()] - time[n.as_usize()]
}
}
match by_span {
true => Ok(b * self.span()),
false => Ok(b),
}
}
pub fn interval(&self) -> (Position, Position) {
(
self.as_ll_ref().interval.left.into(),
self.as_ll_ref().interval.right.into(),
)
}
pub fn span(&self) -> Position {
let i = self.interval();
i.1 - i.0
}
pub fn left_sample_array(&self) -> Result<&[NodeId], TskitError> {
err_if_not_tracking_samples!(self.flags, unsafe {
// SAFETY: array length is number of nodes + 1 for the "virtual root"
super::generate_slice(
self.as_ll_ref().left_sample,
self.treeseq.num_nodes_raw() + 1,
)
})
}
pub fn right_sample_array(&self) -> Result<&[NodeId], TskitError> {
err_if_not_tracking_samples!(
self.flags,
// SAFETY: array length is number of nodes + 1 for the "virtual root"
unsafe {
super::generate_slice(
self.as_ll_ref().right_sample,
self.treeseq.num_nodes_raw() + 1,
)
}
)
}
pub fn next_sample_array(&self) -> Result<&[NodeId], TskitError> {
err_if_not_tracking_samples!(
self.flags,
// SAFETY: array length is number of nodes + 1 for the "virtual root"
unsafe {
super::generate_slice(
self.as_ll_ref().next_sample,
self.treeseq.num_nodes_raw() + 1,
)
}
)
}
pub fn kc_distance(&self, other: &Self, lambda: f64) -> Result<f64, TskitError> {
let mut kc = f64::NAN;
let kcp: *mut f64 = &mut kc;
let code =
unsafe { bindings::tsk_tree_kc_distance(self.as_ptr(), other.as_ptr(), lambda, kcp) };
handle_tsk_return_value!(code, kc)
}
}
// Trait defining iteration over nodes.
pub trait NodeIterator {
fn next_node(&mut self);
fn current_node(&mut self) -> Option<NodeId>;
}
#[repr(transparent)]
struct NodeIteratorAdapter<T: NodeIterator>(T);
impl<T> Iterator for NodeIteratorAdapter<T>
where
T: NodeIterator,
{
type Item = NodeId;
fn next(&mut self) -> Option<Self::Item> {
self.0.next_node();
self.0.current_node()
}
}
struct PreorderNodeIterator<'a> {
current_root: NodeId,
node_stack: Vec<NodeId>,
tree: &'a LLTree<'a>,
current_node: Option<NodeId>,
}
impl<'a> PreorderNodeIterator<'a> {
fn new(tree: &'a LLTree) -> Self {
debug_assert!(tree.right_child(tree.virtual_root()).is_some());
let mut rv = PreorderNodeIterator {
current_root: tree
.right_child(tree.virtual_root())
.unwrap_or(NodeId::NULL),
node_stack: vec![],
tree,
current_node: None,
};
let mut c = rv.current_root;
while c != -1 {
rv.node_stack.push(c);
debug_assert!(rv.tree.left_sib(c).is_some());
c = rv.tree.left_sib(c).unwrap_or(NodeId::NULL);
}
rv
}
}
impl NodeIterator for PreorderNodeIterator<'_> {
fn next_node(&mut self) {
self.current_node = self.node_stack.pop();
if let Some(u) = self.current_node {
// NOTE: process children right-to-left
// because we later pop them from a steck
// to generate the expected left-to-right ordering.
debug_assert!(self.tree.right_child(u).is_some());
let mut c = self.tree.right_child(u).unwrap_or(NodeId::NULL);
while c != NodeId::NULL {
self.node_stack.push(c);
debug_assert!(self.tree.right_child(c).is_some());
c = self.tree.left_sib(c).unwrap_or(NodeId::NULL);
}
};
}
fn current_node(&mut self) -> Option<NodeId> {
self.current_node
}
}
struct PostorderNodeIterator<'a> {
nodes: Vec<NodeId>,
current_node_index: usize,
current_node: Option<NodeId>,
num_nodes_current_tree: usize,
_tree: &'a LLTree<'a>,
}
impl<'a> PostorderNodeIterator<'a> {
fn new(tree: &'a LLTree<'a>) -> Self {
let mut num_nodes_current_tree: tsk_size_t = 0;
let ptr = std::ptr::addr_of_mut!(num_nodes_current_tree);
let mut nodes = vec![
NodeId::NULL;
// NOTE: this fn does not return error codes
usize::try_from(unsafe {
bindings::tsk_tree_get_size_bound(tree.as_ptr())
}).unwrap_or(usize::MAX)
];
let rv = unsafe {
bindings::tsk_tree_postorder(tree.as_ptr(), nodes.as_mut_ptr().cast::<tsk_id_t>(), ptr)
};
// This is either out of memory
// or node out of range.
// The former is fatal, and the latter
// not relevant (for now), as we start at roots.
if rv < 0 {
panic!("fatal error calculating postoder node list");
}
Self {
nodes,
current_node_index: 0,
current_node: None,
num_nodes_current_tree: usize::try_from(num_nodes_current_tree).unwrap_or(0),
_tree: tree,
}
}
}
impl NodeIterator for PostorderNodeIterator<'_> {
fn next_node(&mut self) {
match self.current_node_index < self.num_nodes_current_tree {
true => {
self.current_node = Some(self.nodes[self.current_node_index]);
self.current_node_index += 1;
}
false => self.current_node = None,
}
}
fn current_node(&mut self) -> Option<NodeId> {
self.current_node
}
}
struct SamplesIterator<'a> {
current_node: Option<NodeId>,
next_sample_index: NodeId,
last_sample_index: NodeId,
tree: &'a LLTree<'a>,
}
impl<'a> SamplesIterator<'a> {
fn new(tree: &'a LLTree<'a>, u: NodeId) -> Result<Self, TskitError> {
match tree.flags.contains(TreeFlags::SAMPLE_LISTS) {
false => Err(TskitError::NotTrackingSamples {}),
true => {
let next_sample_index = match tree.left_sample(u) {
Some(x) => x,
None => NodeId::NULL,
};
let last_sample_index = match tree.right_sample(u) {
Some(x) => x,
None => NodeId::NULL,
};
Ok(SamplesIterator {
current_node: None,
next_sample_index,
last_sample_index,
tree,
})
}
}
}
}
impl NodeIterator for SamplesIterator<'_> {
fn next_node(&mut self) {
self.current_node = match self.next_sample_index {
NodeId::NULL => None,
r => {
let raw = crate::sys::bindings::tsk_id_t::from(r);
if r == self.last_sample_index {
let cr =
Some(unsafe { *(*self.tree.as_ptr()).samples.offset(raw as isize) }.into());
self.next_sample_index = NodeId::NULL;
cr
} else {
assert!(r >= 0);
let cr =
Some(unsafe { *(*self.tree.as_ptr()).samples.offset(raw as isize) }.into());
//self.next_sample_index = self.next_sample[r];
self.next_sample_index =
unsafe { *(*self.tree.as_ptr()).next_sample.offset(raw as isize) }.into();
cr
}
}
};
}
fn current_node(&mut self) -> Option<NodeId> {
self.current_node
}
}
#[non_exhaustive]
pub enum NodeTraversalOrder {
///Preorder traversal, starting at the root(s) of a tree.
///For trees with multiple roots, start at the left root,
///traverse to tips, proceeed to the next root, etc..
Preorder,
///Postorder traversal, starting at the root(s) of a tree.
///For trees with multiple roots, start at the left root,
///traverse to tips, proceeed to the next root, etc..
Postorder,
}
struct ChildIterator<'a> {
current_child: Option<NodeId>,
next_child: NodeId,
tree: &'a LLTree<'a>,
}
impl<'a> ChildIterator<'a> {
fn new(tree: &'a LLTree<'a>, u: NodeId) -> Self {
let c = match tree.left_child(u) {
Some(x) => x,
None => NodeId::NULL,
};
ChildIterator {
current_child: None,
next_child: c,
tree,
}
}
}
impl NodeIterator for ChildIterator<'_> {
fn next_node(&mut self) {
self.current_child = match self.next_child {
NodeId::NULL => None,
r => {
assert!(r >= 0);
let cr = Some(r);
debug_assert!(self.tree.right_sib(r).is_some());
self.next_child = self.tree.right_sib(r).unwrap_or(NodeId::NULL);
cr
}
};
}
fn current_node(&mut self) -> Option<NodeId> {
self.current_child
}
}
struct ParentsIterator<'a> {
current_node: Option<NodeId>,
next_node: NodeId,
tree: &'a LLTree<'a>,
}
impl<'a> ParentsIterator<'a> {
fn new(tree: &'a LLTree<'a>, u: NodeId) -> Self {
let u = match tsk_id_t::try_from(tree.treeseq.num_nodes_raw()) {
Ok(num_nodes) if u < num_nodes => u,
_ => NodeId::NULL,
};
ParentsIterator {
current_node: None,
next_node: u,
tree,
}
}
}
impl NodeIterator for ParentsIterator<'_> {
fn next_node(&mut self) {
self.current_node = match self.next_node {
NodeId::NULL => None,
r => {
assert!(r >= 0);
let cr = Some(r);
self.next_node = self.tree.parent(r).unwrap_or(NodeId::NULL);
cr
}
};
}
fn current_node(&mut self) -> Option<NodeId> {
self.current_node
}
}
struct RootIterator<'a> {
current_root: Option<NodeId>,
next_root: NodeId,
tree: &'a LLTree<'a>,
}
impl<'a> RootIterator<'a> {
fn new(tree: &'a LLTree<'a>) -> Self {
debug_assert!(tree.left_child(tree.virtual_root()).is_some());
RootIterator {
current_root: None,
next_root: tree.left_child(tree.virtual_root()).unwrap_or(NodeId::NULL),
tree,
}
}
}
impl NodeIterator for RootIterator<'_> {
fn next_node(&mut self) {
self.current_root = match self.next_root {
NodeId::NULL => None,
r => {
assert!(r >= 0);
let cr = Some(r);
debug_assert!(self.tree.right_sib(r).is_some());
self.next_root = self.tree.right_sib(r).unwrap_or(NodeId::NULL);
cr
}
};
}
fn current_node(&mut self) -> Option<NodeId> {
self.current_root
}
}