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
use crate::bindings as ll_bindings;
use crate::metadata;
use crate::NodeFlags;
use crate::SizeType;
use crate::Time;
use crate::{tsk_id_t, TskitError};
use crate::{IndividualId, NodeId, PopulationId};
use ll_bindings::{tsk_node_table_free, tsk_node_table_init};

/// Row of a [`NodeTable`]
pub struct NodeTableRow {
    pub id: NodeId,
    pub time: Time,
    pub flags: NodeFlags,
    pub population: PopulationId,
    pub individual: IndividualId,
    pub metadata: Option<Vec<u8>>,
}

impl PartialEq for NodeTableRow {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
            && self.flags == other.flags
            && self.population == other.population
            && self.individual == other.individual
            && crate::util::partial_cmp_equal(&self.time, &other.time)
            && self.metadata == other.metadata
    }
}

fn make_node_table_row(table: &NodeTable, pos: tsk_id_t) -> Option<NodeTableRow> {
    if let Ok(p) = crate::SizeType::try_from(pos) {
        if p < table.num_rows() {
            let table_ref = table.table_;
            Some(NodeTableRow {
                id: pos.into(),
                time: table.time(pos).unwrap(),
                flags: table.flags(pos).unwrap(),
                population: table.population(pos).unwrap(),
                individual: table.individual(pos).unwrap(),
                metadata: table_row_decode_metadata!(table, table_ref, pos).map(|m| m.to_vec()),
            })
        } else {
            None
        }
    } else {
        None
    }
}

pub(crate) type NodeTableRefIterator<'a> = crate::table_iterator::TableIterator<&'a NodeTable<'a>>;
pub(crate) type NodeTableIterator<'a> = crate::table_iterator::TableIterator<NodeTable<'a>>;

impl<'a> Iterator for NodeTableRefIterator<'a> {
    type Item = NodeTableRow;

    fn next(&mut self) -> Option<Self::Item> {
        let rv = make_node_table_row(self.table, self.pos);
        self.pos += 1;
        rv
    }
}

impl<'a> Iterator for NodeTableIterator<'a> {
    type Item = crate::node_table::NodeTableRow;

    fn next(&mut self) -> Option<Self::Item> {
        let rv = make_node_table_row(&self.table, self.pos);
        self.pos += 1;
        rv
    }
}

/// An immtable view of a node table.
///
/// These are not created directly.
/// Instead, use [`TableAccess::nodes`](crate::TableAccess::nodes)
/// to get a reference to an existing node table;
pub struct NodeTable<'a> {
    table_: &'a ll_bindings::tsk_node_table_t,
}

impl<'a> NodeTable<'a> {
    pub(crate) fn new_from_table(nodes: &'a ll_bindings::tsk_node_table_t) -> Self {
        NodeTable { table_: nodes }
    }

    /// Return the number of rows
    pub fn num_rows(&'a self) -> SizeType {
        self.table_.num_rows.into()
    }

    /// Return the ``time`` value from row ``row`` of the table.
    ///
    /// # Errors
    ///
    /// Will return [``IndexError``](crate::TskitError::IndexError)
    /// if ``row`` is out of range.
    pub fn time<N: Into<NodeId> + Copy>(&'a self, row: N) -> Result<Time, TskitError> {
        match unsafe_tsk_column_access!(row.into().0, 0, self.num_rows(), self.table_.time) {
            Ok(t) => Ok(t.into()),
            Err(e) => Err(e),
        }
    }

    /// Return the ``flags`` value from row ``row`` of the table.
    ///
    /// # Errors
    ///
    /// Will return [``IndexError``](crate::TskitError::IndexError)
    /// if ``row`` is out of range.
    pub fn flags<N: Into<NodeId> + Copy>(&'a self, row: N) -> Result<NodeFlags, TskitError> {
        match unsafe_tsk_column_access!(row.into().0, 0, self.num_rows(), self.table_.flags) {
            Ok(f) => Ok(NodeFlags::from(f)),
            Err(e) => Err(e),
        }
    }

    /// Mutable access to node flags.
    pub fn flags_array_mut(&mut self) -> &mut [NodeFlags] {
        unsafe {
            std::slice::from_raw_parts_mut(
                self.table_.flags.cast::<NodeFlags>(),
                usize::try_from(self.table_.num_rows).unwrap(),
            )
        }
    }

    /// Mutable access to node times.
    pub fn time_array_mut(&mut self) -> &mut [Time] {
        unsafe {
            std::slice::from_raw_parts_mut(
                self.table_.time.cast::<Time>(),
                usize::try_from(self.table_.num_rows).unwrap(),
            )
        }
    }

    /// Return the ``population`` value from row ``row`` of the table.
    ///
    /// # Errors
    ///
    /// Will return [``IndexError``](crate::TskitError::IndexError)
    /// if ``row`` is out of range.
    pub fn population<N: Into<NodeId> + Copy>(
        &'a self,
        row: N,
    ) -> Result<PopulationId, TskitError> {
        unsafe_tsk_column_access!(
            row.into().0,
            0,
            self.num_rows(),
            self.table_.population,
            PopulationId
        )
    }

    /// Return the ``population`` value from row ``row`` of the table.
    ///
    /// # Errors
    ///
    /// Will return [``IndexError``](crate::TskitError::IndexError)
    /// if ``row`` is out of range.
    pub fn deme<N: Into<NodeId> + Copy>(&'a self, row: N) -> Result<PopulationId, TskitError> {
        self.population(row)
    }

    /// Return the ``individual`` value from row ``row`` of the table.
    ///
    /// # Errors
    ///
    /// Will return [``IndexError``](crate::TskitError::IndexError)
    /// if ``row`` is out of range.
    pub fn individual<N: Into<NodeId> + Copy>(
        &'a self,
        row: N,
    ) -> Result<IndividualId, TskitError> {
        unsafe_tsk_column_access!(
            row.into().0,
            0,
            self.num_rows(),
            self.table_.individual,
            IndividualId
        )
    }

    pub fn metadata<T: metadata::MetadataRoundtrip>(
        &'a self,
        row: NodeId,
    ) -> Result<Option<T>, TskitError> {
        let table_ref = self.table_;
        let buffer = metadata_to_vector!(self, table_ref, row.0)?;
        decode_metadata_row!(T, buffer)
    }

    /// Return an iterator over rows of the table.
    /// The value of the iterator is [`NodeTableRow`].
    pub fn iter(&self) -> impl Iterator<Item = NodeTableRow> + '_ {
        crate::table_iterator::make_table_iterator::<&NodeTable<'a>>(self)
    }

    /// Return row `r` of the table.
    ///
    /// # Parameters
    ///
    /// * `r`: the row id.
    ///
    /// # Errors
    ///
    /// [`TskitError::IndexError`] if `r` is out of range.
    pub fn row<N: Into<NodeId> + Copy>(&self, r: N) -> Result<NodeTableRow, TskitError> {
        let ri = r.into();
        if ri < 0 {
            return Err(crate::TskitError::IndexError);
        }
        table_row_access!(ri.0, self, make_node_table_row)
    }

    /// Obtain a vector containing the indexes ("ids")
    /// of all nodes for which [`crate::TSK_NODE_IS_SAMPLE`]
    /// is `true`.
    pub fn samples_as_vector(&self) -> Vec<NodeId> {
        let mut samples: Vec<NodeId> = vec![];
        for row in self.iter() {
            if row.flags.contains(NodeFlags::IS_SAMPLE) {
                samples.push(row.id);
            }
        }
        samples
    }

    /// Obtain a vector containing the indexes ("ids") of all nodes
    /// satisfying a certain criterion.
    pub fn create_node_id_vector(
        &self,
        mut f: impl FnMut(&crate::NodeTableRow) -> bool,
    ) -> Vec<NodeId> {
        let mut samples: Vec<NodeId> = vec![];
        for row in self.iter() {
            if f(&row) {
                samples.push(row.id);
            }
        }
        samples
    }
}

build_owned_table_type!(
    /// A standalone node table that owns its data.
    ///
    /// # Examples
    ///
    /// ```
    /// use tskit::OwnedNodeTable;
    ///
    /// let mut nodes = OwnedNodeTable::default();
    /// let rowid = nodes.add_row(0, 1.1, -1, -1).unwrap();
    /// assert_eq!(rowid, 0);
    /// assert_eq!(nodes.num_rows(), 1);
    /// ```
    ///
    /// An example with metadata.
    /// This requires the cargo feature `"derive"` for `tskit`.
    ///
    /// ```
    /// # #[cfg(any(feature="doc", feature="derive"))] {
    /// use tskit::OwnedNodeTable;
    ///
    /// #[derive(serde::Serialize,
    ///          serde::Deserialize,
    ///          tskit::metadata::NodeMetadata)]
    /// #[serializer("serde_json")]
    /// struct NodeMetadata {
    ///     value: i32,
    /// }
    ///
    /// let metadata = NodeMetadata{value: 42};
    ///
    /// let mut nodes = OwnedNodeTable::default();
    ///
    /// let rowid = nodes.add_row_with_metadata(0, 1., -1, -1, &metadata).unwrap();
    /// assert_eq!(rowid, 0);
    ///
    /// if let Some(decoded) = nodes.metadata::<NodeMetadata>(rowid).unwrap() {
    ///     assert_eq!(decoded.value, 42);
    /// } else {
    ///     panic!("hmm...we expected some metadata!");
    /// }
    ///
    /// # }
    /// ```
    => OwnedNodeTable,
    NodeTable,
    tsk_node_table_t,
    tsk_node_table_init,
    tsk_node_table_free,
    ll_bindings::tsk_node_table_clear
);

impl OwnedNodeTable {
    node_table_add_row!(=> add_row, self, (*self.table));
    node_table_add_row_with_metadata!(=> add_row_with_metadata, self, (*self.table));
}

#[cfg(test)]
mod test_owned_node_table {
    use super::*;

    #[test]
    fn test_add_row() {
        let mut nodes = OwnedNodeTable::default();
        let rowid = nodes.add_row(0, 1.1, -1, -1).unwrap();
        assert_eq!(rowid, 0);
        assert_eq!(nodes.num_rows(), 1);
    }
}