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
use std::collections::VecDeque;

use necsim_core_bond::NonNegativeF64;
use tskit::{
    IndividualFlags, IndividualId, NodeFlags, NodeId, TableOutputOptions, TableSortOptions,
    TreeSequenceFlags,
};

use necsim_core::{landscape::IndexedLocation, lineage::GlobalLineageReference};

use super::{
    metadata::GlobalLineageMetadata, TskitTreeReporter, TSK_SEQUENCE_MAX, TSK_SEQUENCE_MIN,
};

impl TskitTreeReporter {
    pub(super) fn store_individual_origin(
        &mut self,
        reference: &GlobalLineageReference,
        location: &IndexedLocation,
    ) {
        self.origins.insert(reference.clone(), location.clone());
    }

    pub(super) fn store_individual_speciation(
        &mut self,
        parent: &GlobalLineageReference,
        time: NonNegativeF64,
    ) {
        // Resolve the actual parent, irrespective of duplicate individuals
        let mut parent = parent;
        while let Some(parent_parent) = self.parents.get(parent) {
            parent = parent_parent;
        }
        let parent = parent.clone();

        // Insert the speciating parent lineage, then store its successors, too
        if let Some((parent_individual, parent_node)) = self.store_lineage(&parent, time, None) {
            self.store_children_of_parent(&parent, parent_individual, parent_node);
        }
    }

    pub(super) fn store_individual_coalescence(
        &mut self,
        child: &GlobalLineageReference,
        parent: &GlobalLineageReference,
        time: NonNegativeF64,
    ) {
        // Resolve the actual child, irrespective of duplicate individuals
        let mut child = child;
        while let Some(child_parent) = self.parents.get(child) {
            child = child_parent;
        }
        let child = child.clone();

        // Resolve the actual parent, irrespective of duplicate individuals
        let mut parent = parent;
        while let Some(parent_parent) = self.parents.get(parent) {
            parent = parent_parent;
        }
        let parent = parent.clone();

        self.parents.insert(child.clone(), parent.clone());

        if let Some((parent_individual, parent_node)) = self.tskit_ids.get(&parent).copied() {
            // The parent has already been inserted
            //  -> immediately store child and its successors
            if let Some((child_individual, child_node)) =
                self.store_lineage(&child, time, Some((parent_individual, parent_node)))
            {
                self.store_children_of_parent(&child, child_individual, child_node);
            }
        } else {
            // The parent has not been inserted yet
            //  -> postpone insertion and remember the child
            self.children.entry(parent).or_default().push((child, time));
        }
    }

    pub(super) fn store_provenance(&mut self) -> Result<(), String> {
        // Capture and record the provenance information inside the table
        let provenance =
            crate::provenance::TskitProvenance::try_new().map_err(|err| err.to_string())?;
        let provenance_json = serde_json::to_string(&provenance).map_err(|err| err.to_string())?;

        self.table
            .add_provenance(&provenance_json)
            .map_err(|err| err.to_string())
            .map(|_| ())
    }

    pub(super) fn output_tree_sequence(mut self) {
        self.table.full_sort(TableSortOptions::NONE).unwrap();

        // Output the tree sequence to the specified `output` file
        self.table
            .tree_sequence(TreeSequenceFlags::BUILD_INDEXES)
            .unwrap()
            .dump(&self.output, TableOutputOptions::NONE)
            .unwrap();
    }
}

impl TskitTreeReporter {
    /// Store a lineage as a `tskit` individual and birth node, optionally with
    /// a parent relationship
    fn store_lineage(
        &mut self,
        reference: &GlobalLineageReference,
        time: NonNegativeF64,
        parent: Option<(IndividualId, NodeId)>,
    ) -> Option<(IndividualId, NodeId)> {
        let origin = self.origins.remove(reference)?;
        let location = [
            f64::from(origin.location().x()),
            f64::from(origin.location().y()),
            f64::from(origin.index()),
        ];
        let metadata = GlobalLineageMetadata::new(reference);
        let parents = if let Some((parent_individual, _parent_node)) = &parent {
            std::slice::from_ref(parent_individual)
        } else {
            &[]
        };

        // Insert the lineage as an individual
        let individual_id = self
            .table
            .add_individual_with_metadata(IndividualFlags::empty(), location, parents, metadata)
            .unwrap();

        // Create corresponding node
        let node_id = self
            .table
            .add_node_with_metadata(
                NodeFlags::new_sample(),
                time.get(),
                tskit::PopulationId::NULL,
                individual_id,
                metadata,
            )
            .unwrap();

        if let Some((_parent_individual, parent_node)) = parent {
            // Add the parent-child relation between the nodes
            self.table
                .add_edge(TSK_SEQUENCE_MIN, TSK_SEQUENCE_MAX, parent_node, node_id)
                .unwrap();
        }

        // Store the individual and node for potential late coalescences
        self.tskit_ids
            .insert(reference.clone(), (individual_id, node_id));

        Some((individual_id, node_id))
    }

    /// Store all the children lineages of the parent lineage
    ///  as `tskit` individuals with birth nodes
    fn store_children_of_parent(
        &mut self,
        parent: &GlobalLineageReference,
        parent_individual: IndividualId,
        parent_node: NodeId,
    ) {
        let mut stack = VecDeque::from(vec![(parent.clone(), parent_individual, parent_node)]);

        // Iteratively insert the parent's successors in breadth first order
        while let Some((parent, parent_individual, parent_node)) = stack.pop_front() {
            if let Some(children) = self.children.remove(&parent) {
                for (child, time) in children {
                    // Insert the coalesced child lineage
                    if let Some((child_individual, child_node)) =
                        self.store_lineage(&child, time, Some((parent_individual, parent_node)))
                    {
                        stack.push_back((child, child_individual, child_node));
                    }
                }
            }
        }
    }
}