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
use crate::bindings as ll_bindings;
use crate::{tsk_id_t, tsk_size_t, ProvenanceId, TskitError};
#[cfg_attr(
feature = "provenance",
doc = r##"
# Examples
## For table collections
```
use tskit::provenance::Provenance;
let mut tables = tskit::TableCollection::new(1000.).unwrap();
tables.add_provenance(&String::from("Some provenance")).unwrap();
// Get reference to the table
let prov_ref = tables.provenances();
// Get the first row
let row_0 = prov_ref.row(0).unwrap();
assert_eq!(row_0.record, "Some provenance");
// Get the first record
let record_0 = prov_ref.record(0).unwrap();
assert_eq!(record_0, row_0.record);
// Get the first time stamp
let timestamp = prov_ref.timestamp(0).unwrap();
assert_eq!(timestamp, row_0.timestamp);
// You can get the `chrono::DateTime` object back from the `String`:
let dt = chrono::DateTime::parse_from_rfc3339(×tamp).unwrap();
// You can get specific time types back, too:
use core::str::FromStr;
let dt_utc = chrono::DateTime::<chrono::Utc>::from_str(×tamp).unwrap();
let dt_local = chrono::DateTime::<chrono::Local>::from_str(×tamp).unwrap();
println!("local = {}", dt_local);
// Provenance transfers to the tree sequences
let treeseq = tables.tree_sequence(tskit::TreeSequenceFlags::BUILD_INDEXES).unwrap();
assert_eq!(treeseq.provenances().record(0).unwrap(), "Some provenance");
// We can still compare to row_0 because it is a copy of the row data:
assert_eq!(treeseq.provenances().record(0).unwrap(), row_0.record);
```
## For tree sequences
```
use tskit::provenance::Provenance;
let mut tables = tskit::TableCollection::new(1000.).unwrap();
let mut treeseq = tables.tree_sequence(tskit::TreeSequenceFlags::BUILD_INDEXES).unwrap();
treeseq.add_provenance(&String::from("All your provenance r belong 2 us.")).unwrap();
let prov_ref = treeseq.provenances();
let row_0 = prov_ref.row(0).unwrap();
assert_eq!(row_0.record, "All your provenance r belong 2 us.");
let record_0 = prov_ref.record(0).unwrap();
assert_eq!(record_0, row_0.record);
let timestamp = prov_ref.timestamp(0).unwrap();
assert_eq!(timestamp, row_0.timestamp);
let dt = chrono::DateTime::parse_from_rfc3339(×tamp).unwrap();
use core::str::FromStr;
let dt_utc = chrono::DateTime::<chrono::Utc>::from_str(×tamp).unwrap();
let dt_local = chrono::DateTime::<chrono::Local>::from_str(×tamp).unwrap();
println!("local = {}", dt_local);
```
"##
)]
pub trait Provenance: crate::TableAccess {
fn add_provenance(&mut self, record: &str) -> Result<ProvenanceId, TskitError>;
fn provenances(&self) -> ProvenanceTable;
fn provenances_iter(&self) -> ProvenanceTableIterator {
crate::table_iterator::make_table_iterator::<ProvenanceTable>(self.provenances())
}
}
#[derive(Eq)]
pub struct ProvenanceTableRow {
pub id: ProvenanceId,
pub timestamp: String,
pub record: String,
}
impl PartialEq for ProvenanceTableRow {
fn eq(&self, other: &Self) -> bool {
self.id == other.id && self.timestamp == other.timestamp && self.record == other.record
}
}
impl std::fmt::Display for ProvenanceTableRow {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
f,
"id: {}, timestamp: {}, record: {}",
self.id, self.timestamp, self.record,
)
}
}
fn make_provenance_table_row(table: &ProvenanceTable, pos: tsk_id_t) -> Option<ProvenanceTableRow> {
if pos < table.num_rows() as tsk_id_t {
Some(ProvenanceTableRow {
id: pos.into(),
timestamp: table.timestamp(pos).unwrap(),
record: table.record(pos).unwrap(),
})
} else {
None
}
}
type ProvenanceTableRefIterator<'a> = crate::table_iterator::TableIterator<&'a ProvenanceTable<'a>>;
type ProvenanceTableIterator<'a> = crate::table_iterator::TableIterator<ProvenanceTable<'a>>;
impl<'a> Iterator for ProvenanceTableRefIterator<'a> {
type Item = ProvenanceTableRow;
fn next(&mut self) -> Option<Self::Item> {
let rv = make_provenance_table_row(self.table, self.pos);
self.pos += 1;
rv
}
}
impl<'a> Iterator for ProvenanceTableIterator<'a> {
type Item = ProvenanceTableRow;
fn next(&mut self) -> Option<Self::Item> {
let rv = make_provenance_table_row(&self.table, self.pos);
self.pos += 1;
rv
}
}
pub struct ProvenanceTable<'a> {
table_: &'a ll_bindings::tsk_provenance_table_t,
}
impl<'a> ProvenanceTable<'a> {
pub(crate) fn new_from_table(provenances: &'a ll_bindings::tsk_provenance_table_t) -> Self {
ProvenanceTable {
table_: provenances,
}
}
pub fn num_rows(&'a self) -> ll_bindings::tsk_size_t {
self.table_.num_rows
}
pub fn timestamp<P: Into<ProvenanceId> + Copy>(&'a self, row: P) -> Result<String, TskitError> {
match unsafe_tsk_ragged_char_column_access!(
row.into().0,
0,
self.num_rows(),
self.table_.timestamp,
self.table_.timestamp_offset,
self.table_.timestamp_length
) {
Ok(Some(string)) => Ok(string),
Ok(None) => Err(crate::TskitError::ValueError {
got: String::from("None"),
expected: String::from("String"),
}),
Err(e) => Err(e),
}
}
pub fn record<P: Into<ProvenanceId> + Copy>(&'a self, row: P) -> Result<String, TskitError> {
match unsafe_tsk_ragged_char_column_access!(
row.into().0,
0,
self.num_rows(),
self.table_.record,
self.table_.record_offset,
self.table_.record_length
) {
Ok(Some(string)) => Ok(string),
Ok(None) => Ok(String::from("")),
Err(e) => Err(e),
}
}
pub fn row<P: Into<ProvenanceId> + Copy>(
&'a self,
row: P,
) -> Result<ProvenanceTableRow, TskitError> {
if row.into() < 0 {
Err(TskitError::IndexError)
} else {
match make_provenance_table_row(self, row.into().0) {
Some(x) => Ok(x),
None => Err(TskitError::IndexError),
}
}
}
pub fn iter(&self) -> ProvenanceTableRefIterator {
crate::table_iterator::make_table_iterator::<&ProvenanceTable<'a>>(self)
}
}
#[cfg(test)]
mod test_provenance_tables {
use super::*;
use crate::test_fixtures::make_empty_table_collection;
use Provenance;
#[test]
fn test_empty_record_string() {
let mut tables = make_empty_table_collection(1.0);
let s = String::from("");
let row_id = tables.add_provenance(&s).unwrap();
let _ = tables.provenances().row(row_id).unwrap();
tables.build_index().unwrap();
let mut ts = tables
.tree_sequence(crate::TreeSequenceFlags::default())
.unwrap();
let row_id = ts.add_provenance(&s).unwrap();
let _ = ts.provenances().row(row_id).unwrap();
}
#[test]
fn test_add_rows() {
let records = vec!["banana".to_string(), "split".to_string()];
let mut tables = make_empty_table_collection(1.);
for (i, r) in records.iter().enumerate() {
let row_id = tables.add_provenance(r).unwrap();
assert!(row_id == ProvenanceId(i as crate::tsk_id_t));
assert_eq!(tables.provenances().record(row_id).unwrap(), *r);
}
assert_eq!(tables.provenances().num_rows() as usize, records.len());
for (i, row) in tables.provenances_iter().enumerate() {
assert_eq!(records[i], row.record);
}
for (i, row) in tables.provenances().iter().enumerate() {
assert_eq!(records[i], row.record);
}
assert!(tables.provenances().row(0).unwrap() == tables.provenances().row(0).unwrap());
assert!(tables.provenances().row(0).unwrap() != tables.provenances().row(1).unwrap());
}
}