linnet/tree/
child_vec.rs

1use std::fmt::Write;
2
3use itertools::Itertools;
4
5use crate::half_edge::subgraph::{subset::SubSet, Inclusion, ModifySubSet, SubSetLike};
6
7use super::{
8    child_pointer::{PCNode, ParentChildStore},
9    iterato::{BfsIter, PreorderIter},
10    parent_pointer::{PPNode, ParentId, ParentPointerStore},
11    ForestError, ForestNodeStore, ForestNodeStoreAncestors, ForestNodeStoreBfs,
12    ForestNodeStoreDown, ForestNodeStorePreorder, RootId, TreeNodeId,
13};
14
15/// A node in the ChildVecStore. It contains a PPNode plus an ordered vector of children.
16#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18#[cfg_attr(feature = "bincode", derive(bincode::Encode, bincode::Decode))]
19pub struct CVNode<V> {
20    pub parent_pointer: PPNode<V>,
21    pub children: Vec<TreeNodeId>,
22}
23impl<V> CVNode<V> {
24    pub fn shift(&mut self, root: RootId, nodes: TreeNodeId) {
25        self.parent_pointer.shift(root, nodes);
26        for c in &mut self.children {
27            c.0 += nodes.0;
28        }
29    }
30
31    pub fn debug_display(
32        &self,
33        writer: &mut impl std::fmt::Write,
34        draw_data: &mut impl FnMut(Option<&V>) -> Option<String>,
35    ) {
36        write!(writer, "children:").unwrap();
37        for child in &self.children {
38            write!(writer, "{child},").unwrap();
39        }
40        self.parent_pointer.debug_display(writer, draw_data);
41    }
42
43    pub fn forget<U>(&self) -> CVNode<U> {
44        CVNode {
45            parent_pointer: self.parent_pointer.forget(),
46            children: self.children.clone(),
47        }
48    }
49}
50
51/// The ChildVecStore itself.
52#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
53#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
54#[cfg_attr(feature = "bincode", derive(bincode::Encode, bincode::Decode))]
55pub struct ChildVecStore<V> {
56    pub nodes: Vec<CVNode<V>>,
57}
58
59//
60// Indexing implementations, similar to ParentChildStore/ParentPointerStore.
61//
62impl<V> std::ops::Index<&TreeNodeId> for ChildVecStore<V> {
63    type Output = ParentId;
64    fn index(&self, index: &TreeNodeId) -> &Self::Output {
65        &self.nodes[index.0].parent_pointer.parent
66    }
67}
68
69impl<V> std::ops::Index<TreeNodeId> for ChildVecStore<V> {
70    type Output = Option<V>;
71    fn index(&self, index: TreeNodeId) -> &Self::Output {
72        &self.nodes[index.0].parent_pointer.data
73    }
74}
75
76impl<V> std::ops::IndexMut<TreeNodeId> for ChildVecStore<V> {
77    fn index_mut(&mut self, index: TreeNodeId) -> &mut Self::Output {
78        &mut self.nodes[index.0].parent_pointer.data
79    }
80}
81
82impl<V> FromIterator<CVNode<V>> for ChildVecStore<V> {
83    fn from_iter<I: IntoIterator<Item = CVNode<V>>>(iter: I) -> Self {
84        ChildVecStore {
85            nodes: iter.into_iter().collect(),
86        }
87    }
88}
89
90//
91// Implement the ForestNodeStore trait for ChildVecStore:
92//
93impl<V> ForestNodeStore for ChildVecStore<V> {
94    type NodeData = V;
95    type Store<T> = ChildVecStore<T>;
96    fn debug_draw(
97        &self,
98        mut node_display: impl FnMut(Option<&Self::NodeData>) -> Option<String>,
99    ) -> String {
100        // fn debug_draw(&self, node_display: impl FnMut()) -> String {
101        let mut output = String::new();
102        writeln!(output, "Number of nodes:{}", self.n_nodes()).unwrap();
103
104        // Recursive helper function - structure remains the same, handles sub-trees
105        fn draw_subtree_recursive<W: Write, V>(
106            f: &mut W,                                                  // Output writer
107            nodes: &ChildVecStore<V>,                                   // Node store access
108            node_id: TreeNodeId,                                        // Current node to draw
109            prefix: &str,        // Current line prefix (e.g., "  │   ")
110            is_last_child: bool, // Is this the last child of its parent?
111            format_node: &mut impl FnMut(Option<&V>) -> Option<String>, // Mutable reference to node formatter closure
112            seen: &mut SubSet<TreeNodeId>,
113        ) -> Result<(), std::fmt::Error> {
114            // Determine the connector shape based on whether it's the last child
115            let connector = if is_last_child {
116                "└── "
117            } else {
118                "├── "
119            };
120
121            write!(f, "{prefix}{connector}{node_id}:")?;
122            nodes.nodes[node_id.0].debug_display(f, format_node);
123
124            seen.sub(node_id);
125            // Prepare the prefix for the children of this node
126            let child_prefix = format!("{}{}", prefix, if is_last_child { "    " } else { "│   " });
127
128            let children: Vec<_> = nodes.iter_children(node_id).collect();
129            let num_children = children.len();
130            for (i, child_id) in children.into_iter().enumerate() {
131                seen.sub(child_id);
132                // Recurse: pass the new prefix and whether this child is the last one
133                draw_subtree_recursive(
134                    f,
135                    nodes,
136                    child_id,
137                    &child_prefix,
138                    i == num_children - 1,
139                    format_node,
140                    seen,
141                )?;
142            }
143            Ok(())
144        } // End of helper fn definition
145
146        let mut seen: SubSet<TreeNodeId> = !SubSet::empty(self.n_nodes());
147
148        while let Some(next) = seen.included_iter().next() {
149            let root_id = self.root_node(next);
150            // println!("{}", root_id);
151
152            seen.sub(root_id);
153
154            seen.sub(next);
155
156            let node_line_prefix = "  ";
157
158            write!(output, "{node_line_prefix}{root_id}:").unwrap();
159            self.nodes[root_id.0].debug_display(&mut output, &mut node_display);
160
161            let children: Vec<_> = self
162                .iter_children(root_id)
163                .inspect(|a| {
164                    seen.sub(*a);
165                })
166                .collect();
167            let num_children = children.len();
168
169            for (i, child_id) in children.into_iter().enumerate() {
170                seen.sub(child_id);
171                let _ = draw_subtree_recursive(
172                    &mut output,
173                    self,
174                    child_id,
175                    node_line_prefix, // Prefix aligns the connector itself
176                    i == num_children - 1,
177                    &mut node_display,
178                    &mut seen,
179                );
180            }
181
182            let _ = writeln!(output);
183        }
184
185        output
186    }
187
188    fn validate(&self) -> Result<Vec<(RootId, TreeNodeId)>, super::ForestError> {
189        let mut roots = vec![];
190        let mut seen: SubSet<TreeNodeId> = SubSet::full(self.n_nodes());
191
192        while let Some(next) = seen.included_iter().next() {
193            let current = next;
194            seen.sub(next);
195
196            if ParentId::Node(current) == self.parent(current) {
197                return Err(ForestError::SelfLoopPP(current));
198            }
199            if ParentId::PointingRoot(current) == self.parent(current) {
200                return Err(ForestError::SelfLoopPP(current));
201            }
202            let mut parents: SubSet<TreeNodeId> = SubSet::empty(self.n_nodes());
203            for p in self.iter_ancestors(current) {
204                if parents.includes(&p) {
205                    return Err(ForestError::CyclicPP);
206                }
207                parents.add(p);
208            }
209            let mut children: SubSet<TreeNodeId> = SubSet::empty(self.n_nodes());
210
211            for c in self.iter_preorder(current) {
212                if children.includes(&c) {
213                    return Err(ForestError::CyclicCP);
214                }
215                children.add(c);
216            }
217            for c in self.iter_children(current) {
218                if let ParentId::Node(n) = self[&c] {
219                    if n != current {
220                        return Err(ForestError::WrongPP(current));
221                    }
222                }
223            }
224            let root_id = self.root_node(current);
225            let root = self.root(root_id);
226
227            roots.push((root, root_id));
228        }
229
230        Ok(roots)
231    }
232
233    fn set_root(&mut self, a: TreeNodeId, root: RootId) {
234        let rootx = self.root_node(a);
235        self.nodes[rootx.0].parent_pointer.parent = ParentId::Root(root);
236    }
237
238    fn forgetful_map<U>(&self) -> Self::Store<U> {
239        ChildVecStore {
240            nodes: self.nodes.iter().map(CVNode::forget).collect(),
241        }
242    }
243
244    fn n_nodes(&self) -> usize {
245        self.nodes.len()
246    }
247
248    fn set_node_data(&mut self, data: Self::NodeData, node_id: TreeNodeId) -> Option<V> {
249        let old = self.nodes[node_id.0].parent_pointer.data.take();
250        self.nodes[node_id.0].parent_pointer.data = Some(data);
251        old
252    }
253
254    fn split_off(&mut self, at: TreeNodeId) -> Self {
255        println!("Boundary: {at}");
256        println!("{}", self.debug_draw(|_| None));
257        let mut roots = vec![];
258        for mut current in self.iter_node_id() {
259            while let ParentId::Node(p) = self[&current] {
260                let mut newp = p;
261                println!("parent {newp} of current {current}");
262                let mut crosses_boundary = false;
263                let mut split_root = false;
264                while !((newp < at) ^ (current >= at)) {
265                    crosses_boundary = true;
266                    // the pointer crosses the splitting boundary, we need to find a new pointer.
267                    println!("New parent {newp} and current {current} on opposite sides of the boundary {at}");
268
269                    match self[&newp] {
270                        ParentId::Node(next) => {
271                            newp = next;
272                        }
273                        ParentId::Root(_) => {
274                            split_root = true;
275                            break;
276                        }
277                        ParentId::PointingRoot(next) => {
278                            newp = next;
279                        }
280                    }
281                }
282
283                if crosses_boundary {
284                    // The seach for a new parent within the boundary, has ended at a root, so the root_node is outside the boundary.
285                    if split_root {
286                        if let ParentId::Root(r) = self[&newp] {
287                            // set current to now be the root, and original root to point here.
288
289                            self.nodes[newp.0].parent_pointer.parent =
290                                ParentId::PointingRoot(current);
291                            self.nodes[current.0].parent_pointer.parent =
292                                ParentId::PointingRoot(newp);
293
294                            let pos_in_children =
295                                self.iter_children(newp).find_position(|a| *a == current);
296                            if let Some((pos, _)) = pos_in_children {
297                                self.nodes[newp.0].children.swap_remove(pos);
298                            }
299                            roots.push((r, newp, current));
300
301                            println!("Turning {current} into pointing root pointing to {newp}, and {newp} into pointing root pointing to {current}");
302                        }
303                    } else {
304                        self.reparent(newp, current);
305                        println!("making {newp} the new parent of {current}")
306                    }
307                }
308
309                current = p
310            }
311        }
312
313        for (r, n1, n2) in roots {
314            self.nodes[n1.0].parent_pointer.parent = ParentId::Root(r);
315            self.nodes[n2.0].parent_pointer.parent = ParentId::Root(r);
316        }
317
318        println!("{}", self.debug_draw(|_| None));
319        for n in self.iter_node_id() {
320            if n >= at {
321                println!("Shifting children of {n}");
322                for n in &mut self.nodes[n.0].children {
323                    print!("child {n}->");
324                    n.0 -= at.0;
325                    println!("{n}");
326                }
327
328                println!("Shifting parents of {n}");
329                if let ParentId::Node(n) = &mut self.nodes[n.0].parent_pointer.parent {
330                    print!("parent {n}->");
331                    n.0 -= at.0;
332                    println!("{n}");
333                }
334            }
335
336            if let ParentId::PointingRoot(rp) = self[&n] {
337                let root = self[&rp];
338                self.nodes[n.0].parent_pointer.parent = root;
339            }
340        }
341        let extracte_nodes = self.nodes.split_off(at.0);
342
343        println!("{}", self.debug_draw(|_| None));
344        Self {
345            nodes: extracte_nodes,
346        }
347    }
348
349    fn extend(&mut self, other: Self, shift_roots_by: RootId) {
350        let nodeshift = TreeNodeId(self.nodes.len());
351        self.nodes.extend(other.nodes.into_iter().map(|mut r| {
352            r.shift(shift_roots_by, nodeshift);
353            r
354        }));
355    }
356    fn reparent(&mut self, parent: TreeNodeId, child: TreeNodeId) {
357        // First remove child pointer of old parent:
358        let old_parent = self.parent(child);
359        if let ParentId::Node(old_parent) = old_parent {
360            if old_parent == parent {
361                return;
362            }
363
364            let pos_in_children = self
365                .iter_children(old_parent)
366                .find_position(|a| *a == child);
367            if let Some((pos, _)) = pos_in_children {
368                self.nodes[old_parent.0].children.swap_remove(pos);
369            }
370        }
371        self.nodes[child.0].parent_pointer.parent = ParentId::Node(parent);
372        self.nodes[parent.0].children.push(child);
373    }
374
375    fn swap(&mut self, a: TreeNodeId, b: TreeNodeId) {
376        println!("Swapping {a} <-> {b}");
377        if a == b {
378            return;
379        }
380
381        // println!("{}", self.debug_draw(|_| None));
382        // println!("swapping {a} <-> {b}");
383        // Before modifying the parent pointers of the children, we save them.
384        let parent_a = self.parent(a);
385        let parent_b = self.parent(b);
386
387        // Now modify the parent pointers of the children.
388        {
389            let (bef, after) = self.nodes.split_at_mut(a.0);
390            let (anode, after) = after.split_first_mut().unwrap();
391
392            for c in &anode.children {
393                if *c <= a {
394                    if let Some(child) = bef.get_mut(c.0) {
395                        // println!("{}", b);
396                        if let ParentId::Node(pp) = &mut child.parent_pointer.parent {
397                            if *pp == a {
398                                *pp = b;
399                            }
400                        }
401                    }
402                } else if let Some(child) = after.get_mut(c.0 - (a.0 + 1)) {
403                    if let ParentId::Node(pp) = &mut child.parent_pointer.parent {
404                        if *pp == a {
405                            *pp = b;
406                        }
407                    }
408                }
409            }
410        }
411        {
412            let (bef, after) = self.nodes.split_at_mut(b.0);
413            let (bnode, after) = after.split_first_mut().unwrap();
414
415            for c in &bnode.children {
416                if *c <= b {
417                    if let Some(child) = bef.get_mut(c.0) {
418                        if let ParentId::Node(pp) = &mut child.parent_pointer.parent {
419                            if *pp == b {
420                                *pp = a;
421                            }
422                        }
423                    }
424                } else if let Some(child) = after.get_mut(c.0 - b.0 - 1) {
425                    if let ParentId::Node(pp) = &mut child.parent_pointer.parent {
426                        if *pp == b {
427                            *pp = a;
428                        }
429                    }
430                }
431            }
432        }
433
434        println!("SS");
435
436        //Now we modify the child pointers of the parents. Here a swap is dangerous as we could have that parent(a) = parent(b)
437        if parent_b == parent_a {
438            let dummya = TreeNodeId(self.n_nodes());
439            let dummyb = TreeNodeId(self.n_nodes() + 1);
440            if let ParentId::Node(parent_a) = parent_a {
441                for c in &mut self.nodes[parent_a.0].children {
442                    if *c == a {
443                        *c = dummya;
444                    } else if *c == b {
445                        *c = dummyb
446                    }
447                }
448                for c in &mut self.nodes[parent_a.0].children {
449                    if *c == dummya {
450                        *c = b;
451                    } else if *c == dummyb {
452                        *c = a;
453                    }
454                }
455            }
456        } else {
457            // it is safe to swap directly
458            if let ParentId::Node(parent_b) = parent_b {
459                for c in &mut self.nodes[parent_b.0].children {
460                    if *c == b {
461                        *c = a;
462                        break;
463                    }
464                }
465            }
466
467            if let ParentId::Node(parent_a) = parent_a {
468                for c in &mut self.nodes[parent_a.0].children {
469                    if *c == a {
470                        *c = b;
471                        break;
472                    }
473                }
474            }
475        }
476
477        println!("SSSS");
478        self.nodes.swap(a.0, b.0);
479        #[cfg(test)]
480        self.panicing_validate();
481    }
482
483    fn to_store(self) -> Self::Store<Self::NodeData> {
484        self
485    }
486
487    fn from_store(store: Self::Store<Self::NodeData>) -> Self {
488        store
489    }
490
491    fn iter_nodes(&self) -> impl Iterator<Item = (TreeNodeId, Option<&Self::NodeData>)> {
492        self.nodes
493            .iter()
494            .enumerate()
495            .map(|(i, node)| (TreeNodeId(i), node.parent_pointer.data.as_ref()))
496    }
497
498    fn add_root(&mut self, data: Self::NodeData, root_id: RootId) -> TreeNodeId {
499        let node_id = TreeNodeId(self.nodes.len());
500        self.nodes.push(CVNode {
501            parent_pointer: PPNode::root(data, root_id),
502            children: Vec::new(),
503        });
504        node_id
505    }
506
507    fn add_child(&mut self, data: Self::NodeData, parent: TreeNodeId) -> TreeNodeId {
508        let node_id = TreeNodeId(self.nodes.len());
509        self.nodes.push(CVNode {
510            parent_pointer: PPNode::child(data, parent),
511            children: Vec::new(),
512        });
513        // Add this child to its parent's list.
514        self.nodes[parent.0].children.push(node_id);
515        node_id
516    }
517
518    fn add_dataless_child(&mut self, parent: TreeNodeId) -> TreeNodeId {
519        let node_id = TreeNodeId(self.nodes.len());
520        self.nodes.push(CVNode {
521            parent_pointer: PPNode::dataless_child(parent),
522            children: Vec::new(),
523        });
524        // Add this child to its parent's list.
525        self.nodes[parent.0].children.push(node_id);
526        node_id
527    }
528
529    fn map<F, U>(self, mut transform: F) -> Self::Store<U>
530    where
531        F: FnMut(Self::NodeData) -> U,
532    {
533        let nodes = self
534            .nodes
535            .into_iter()
536            .map(|node| CVNode {
537                parent_pointer: node.parent_pointer.map(&mut transform),
538                children: node.children, // children remain the same id values.
539            })
540            .collect();
541        ChildVecStore { nodes }
542    }
543
544    fn map_ref<F, U>(&self, mut transform: F) -> Self::Store<U>
545    where
546        F: FnMut(&Self::NodeData) -> U,
547    {
548        let nodes = self
549            .nodes
550            .iter()
551            .map(|node| CVNode {
552                parent_pointer: node.parent_pointer.map_ref(&mut transform),
553                children: node.children.clone(),
554            })
555            .collect();
556        ChildVecStore { nodes }
557    }
558}
559
560impl<V> ForestNodeStoreDown for ChildVecStore<V> {
561    fn iter_leaves(&self) -> impl Iterator<Item = TreeNodeId> {
562        self.nodes.iter().enumerate().filter_map(|(i, node)| {
563            if node.children.is_empty() {
564                Some(TreeNodeId(i))
565            } else {
566                None
567            }
568        })
569    }
570
571    fn iter_children(&self, node_id: TreeNodeId) -> impl Iterator<Item = TreeNodeId> {
572        // Clone the children vector (or borrow as iterator) – they are stored in order.
573        self.nodes[node_id.0].children.clone().into_iter()
574    }
575}
576
577impl<V> ForestNodeStorePreorder for ChildVecStore<V> {
578    type Iterator<'a>
579        = PreorderIter<'a, Self>
580    where
581        Self: 'a;
582    fn iter_preorder(&self, start: TreeNodeId) -> Self::Iterator<'_> {
583        // Use the generic PreorderIter helper
584        PreorderIter::new(self, start)
585    }
586}
587impl<V> ForestNodeStoreBfs for ChildVecStore<V> {
588    fn iter_bfs(&self, start: TreeNodeId) -> impl Iterator<Item = TreeNodeId> + '_ {
589        // Use the generic BfsIter helper
590        BfsIter::new(self, start)
591    }
592}
593//
594// Conversions
595//
596
597// 1. Conversion from ParentPointerStore to ChildVecStore.
598//    In a ParentPointerStore, the nodes only have a PPNode (with parent pointer and data).
599//    To build the children vector, we iterate over all nodes and add each node as a child
600//    of its parent if applicable.
601impl<V> From<ParentPointerStore<V>> for ChildVecStore<V> {
602    fn from(pp_store: ParentPointerStore<V>) -> Self {
603        let n = pp_store.nodes.len();
604        let mut some_pp = pp_store.map(|a| Some(a));
605        let mut nodes = Vec::with_capacity(n);
606        for pp in some_pp.nodes.iter_mut() {
607            let data = pp.data.take().flatten();
608            let parent_pointer = PPNode {
609                data,
610                parent: pp.parent,
611            };
612            nodes.push(CVNode {
613                parent_pointer,
614                children: vec![],
615            });
616        }
617
618        for (i, pp) in some_pp.nodes.iter().enumerate() {
619            if let ParentId::Node(n) = pp.parent {
620                nodes[n.0].children.push(TreeNodeId(i));
621            }
622        }
623
624        ChildVecStore { nodes }
625    }
626}
627
628// 2. Conversion from ParentChildStore to ChildVecStore.
629//    The ParentChildStore stores child pointers via cyclic neighbor links. We can recover
630//    an ordered children vector by using its provided methods.
631impl<V> From<ParentChildStore<V>> for ChildVecStore<V> {
632    fn from(pc_store: ParentChildStore<V>) -> Self {
633        let n = pc_store.nodes.len();
634        let mut some_pc = pc_store.map(|a| a);
635        let mut nodes = Vec::with_capacity(n);
636        for nid in (0..n).map(TreeNodeId) {
637            let data = some_pc[nid].take();
638            let parent_pointer = PPNode {
639                data,
640                parent: some_pc.nodes[nid.0].parent_pointer.parent,
641            };
642
643            let children = some_pc.iter_children(nid).collect();
644
645            nodes.push(CVNode {
646                parent_pointer,
647                children,
648            });
649        }
650
651        ChildVecStore { nodes }
652    }
653}
654
655// 3. Conversion from ChildVecStore to ParentPointerStore.
656//    This conversion simply drops the children vector and keeps only the PPNode.
657impl<V> From<ChildVecStore<V>> for ParentPointerStore<V> {
658    fn from(store: ChildVecStore<V>) -> Self {
659        store
660            .nodes
661            .into_iter()
662            .map(|cv_node| cv_node.parent_pointer)
663            .collect()
664    }
665}
666
667// 4. Conversion from ChildVecStore to ParentChildStore.
668//    Here we build a PCNode from each CVNode. For each node, if its children vec is non-empty,
669//    we set its 'child' field to the first child, and, for each child, we compute neighbor links
670//    (cyclically) using the ordering in the vector.
671impl<V> From<ChildVecStore<V>> for ParentChildStore<V> {
672    fn from(store: ChildVecStore<V>) -> Self {
673        let n = store.nodes.len();
674        let mut some_store = store.map(|a| Some(a));
675        let mut nodes = Vec::with_capacity(n);
676
677        for nid in (0..n).map(TreeNodeId) {
678            let data = some_store.nodes[nid.0].parent_pointer.data.take().flatten();
679            let parent_pointer = PPNode {
680                data,
681                parent: some_store.nodes[nid.0].parent_pointer.parent,
682            };
683
684            let child = some_store.nodes[nid.0].children.iter().cloned().next();
685
686            nodes.push(PCNode {
687                parent_pointer,
688                child,
689                neighbor_left: nid,
690                neighbor_right: nid,
691            });
692        }
693
694        for node in some_store.nodes.iter() {
695            let len = node.children.len();
696            for (j, &child) in node.children.iter().enumerate() {
697                let left = node.children[(j + len - 1) % len];
698                let right = node.children[(j + 1) % len];
699                nodes[child.0].neighbor_left = left;
700                nodes[child.0].neighbor_right = right;
701            }
702        }
703
704        ParentChildStore { nodes }
705    }
706}
707
708#[cfg(test)]
709mod test {
710    // use super::*;
711
712    #[test]
713    fn swap() {}
714}