Struct tskit::TableCollection
source · pub struct TableCollection { /* private fields */ }
Expand description
A table collection.
This is a thin wrapper around the C type
tsk_table_collection_t
.
See also
Examples
let mut tables = tskit::TableCollection::new(100.).unwrap();
assert_eq!(tables.sequence_length(), 100.);
// Adding edges:
let rv = tables.add_edge(0., 53., 1, 11).unwrap();
// Add node:
let rv = tables.add_node(0, 3.2, tskit::PopulationId::NULL, tskit::IndividualId::NULL).unwrap();
// Get immutable reference to edge table
let edges = tables.edges();
assert_eq!(edges.num_rows(), 1);
// Get immutable reference to node table
let nodes = tables.nodes();
assert_eq!(nodes.num_rows(), 1);
Implementations§
source§impl TableCollection
impl TableCollection
sourcepub fn new<P: Into<Position>>(sequence_length: P) -> Result<Self, TskitError>
pub fn new<P: Into<Position>>(sequence_length: P) -> Result<Self, TskitError>
Create a new table collection with a sequence length.
Examples
let tables = tskit::TableCollection::new(55.0).unwrap();
Negative sequence lengths are errors:
let tables = tskit::TableCollection::new(-55.0).unwrap();
Examples found in repository?
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
pub fn new_from_file(filename: impl AsRef<str>) -> Result<Self, TskitError> {
// Arbitrary sequence_length.
let mut tables = match TableCollection::new(1.0) {
Ok(t) => t,
Err(e) => return Err(e),
};
let c_str = std::ffi::CString::new(filename.as_ref()).map_err(|_| {
TskitError::LibraryError("call to ffi::CString::new failed".to_string())
})?;
let rv = unsafe {
ll_bindings::tsk_table_collection_load(
tables.as_mut_ptr(),
c_str.as_ptr(),
ll_bindings::TSK_NO_INIT,
)
};
handle_tsk_return_value!(rv, tables)
}
sourcepub fn new_from_file(filename: impl AsRef<str>) -> Result<Self, TskitError>
pub fn new_from_file(filename: impl AsRef<str>) -> Result<Self, TskitError>
Load a table collection from a file.
Examples
The function is generic over references to str
:
let tables = tskit::TableCollection::new_from_file("trees.file").unwrap();
let filename = String::from("trees.file");
// Pass filename by reference
let tables = tskit::TableCollection::new_from_file(&filename).unwrap();
// Move filename
let tables = tskit::TableCollection::new_from_file(filename).unwrap();
// Boxed String are an unlikely use case, but can be made to work:
let filename = Box::new(String::from("trees.file"));
let tables = tskit::TableCollection::new_from_file(&*filename.as_ref()).unwrap();
Panics
This function allocates a CString
to pass the file name to the C API.
A panic will occur if the system runs out of memory.
sourcepub fn sequence_length(&self) -> Position
pub fn sequence_length(&self) -> Position
Length of the sequence/“genome”.
Examples
let tables = tskit::TableCollection::new(100.).unwrap();
assert_eq!(tables.sequence_length(), 100.0);
sourcepub fn add_edge<L, R, P, C>(
&mut self,
left: L,
right: R,
parent: P,
child: C
) -> Result<EdgeId, TskitError>where
L: Into<Position>,
R: Into<Position>,
P: Into<NodeId>,
C: Into<NodeId>,
pub fn add_edge<L, R, P, C>(
&mut self,
left: L,
right: R,
parent: P,
child: C
) -> Result<EdgeId, TskitError>where
L: Into<Position>,
R: Into<Position>,
P: Into<NodeId>,
C: Into<NodeId>,
Add a row to the edge table
Examples
// left, right, parent, child
match tables.add_edge(0., 53., 1, 11) {
// This is the first edge, so its id will be
// zero (0).
Ok(edge_id) => assert_eq!(edge_id, 0),
Err(e) => panic!("{:?}", e),
}
You may also use Position
and NodeId
as inputs.
let left = tskit::Position::from(0.0);
let right = tskit::Position::from(53.0);
let parent = tskit::NodeId::from(1);
let child = tskit::NodeId::from(11);
match tables.add_edge(left, right, parent, child) {
Ok(edge_id) => assert_eq!(edge_id, 0),
Err(e) => panic!("{:?}", e),
}
Adding invalid data is allowed at this point:
assert!(tables.add_edge(0., 53.,
tskit::NodeId::NULL,
tskit::NodeId::NULL).is_ok());
See TableCollection::check_integrity
for how to catch these data model
violations.
sourcepub fn add_edge_with_metadata<L, R, P, C, M>(
&mut self,
left: L,
right: R,
parent: P,
child: C,
metadata: &M
) -> Result<EdgeId, TskitError>where
L: Into<Position>,
R: Into<Position>,
P: Into<NodeId>,
C: Into<NodeId>,
M: EdgeMetadata,
pub fn add_edge_with_metadata<L, R, P, C, M>(
&mut self,
left: L,
right: R,
parent: P,
child: C,
metadata: &M
) -> Result<EdgeId, TskitError>where
L: Into<Position>,
R: Into<Position>,
P: Into<NodeId>,
C: Into<NodeId>,
M: EdgeMetadata,
sourcepub fn add_individual<F, L, P>(
&mut self,
flags: F,
location: L,
parents: P
) -> Result<IndividualId, TskitError>where
F: Into<IndividualFlags>,
L: IndividualLocation,
P: IndividualParents,
pub fn add_individual<F, L, P>(
&mut self,
flags: F,
location: L,
parents: P
) -> Result<IndividualId, TskitError>where
F: Into<IndividualFlags>,
L: IndividualLocation,
P: IndividualParents,
Add a row to the individual table
Examples
No flags, location, nor parents
tables.add_individual(0, None, None).unwrap();
No flags, a 3d location, no parents
tables.add_individual(0, &[-0.5, 0.3, 10.0], None).unwrap();
No flags, no location, two parents
tables.add_individual(0, None, &[1, 11]);
sourcepub fn add_individual_with_metadata<F, L, P, M>(
&mut self,
flags: F,
location: L,
parents: P,
metadata: &M
) -> Result<IndividualId, TskitError>where
F: Into<IndividualFlags>,
L: IndividualLocation,
P: IndividualParents,
M: IndividualMetadata,
pub fn add_individual_with_metadata<F, L, P, M>(
&mut self,
flags: F,
location: L,
parents: P,
metadata: &M
) -> Result<IndividualId, TskitError>where
F: Into<IndividualFlags>,
L: IndividualLocation,
P: IndividualParents,
M: IndividualMetadata,
sourcepub fn add_migration<LEFT, RIGHT, N, SOURCE, DEST, T>(
&mut self,
span: (LEFT, RIGHT),
node: N,
source_dest: (SOURCE, DEST),
time: T
) -> Result<MigrationId, TskitError>where
LEFT: Into<Position>,
RIGHT: Into<Position>,
N: Into<NodeId>,
SOURCE: Into<PopulationId>,
DEST: Into<PopulationId>,
T: Into<Time>,
pub fn add_migration<LEFT, RIGHT, N, SOURCE, DEST, T>(
&mut self,
span: (LEFT, RIGHT),
node: N,
source_dest: (SOURCE, DEST),
time: T
) -> Result<MigrationId, TskitError>where
LEFT: Into<Position>,
RIGHT: Into<Position>,
N: Into<NodeId>,
SOURCE: Into<PopulationId>,
DEST: Into<PopulationId>,
T: Into<Time>,
sourcepub fn add_migration_with_metadata<LEFT, RIGHT, N, SOURCE, DEST, T, M>(
&mut self,
span: (LEFT, RIGHT),
node: N,
source_dest: (SOURCE, DEST),
time: T,
metadata: &M
) -> Result<MigrationId, TskitError>where
LEFT: Into<Position>,
RIGHT: Into<Position>,
N: Into<NodeId>,
SOURCE: Into<PopulationId>,
DEST: Into<PopulationId>,
T: Into<Time>,
M: MigrationMetadata,
pub fn add_migration_with_metadata<LEFT, RIGHT, N, SOURCE, DEST, T, M>(
&mut self,
span: (LEFT, RIGHT),
node: N,
source_dest: (SOURCE, DEST),
time: T,
metadata: &M
) -> Result<MigrationId, TskitError>where
LEFT: Into<Position>,
RIGHT: Into<Position>,
N: Into<NodeId>,
SOURCE: Into<PopulationId>,
DEST: Into<PopulationId>,
T: Into<Time>,
M: MigrationMetadata,
Add a row with optional metadata to the migration table
Examples
See metadata
for more details about required
trait implementations.
Those details have been omitted from this example.
let metadata = MigrationMetadata{x: 1};
assert!(tables.add_migration_with_metadata((0.5, 100.0),
3,
(0, 1),
53.5,
&metadata).is_ok());
Warnings
Migration tables are not currently supported by tree sequence simplification.
sourcepub fn add_node<F, T, P, I>(
&mut self,
flags: F,
time: T,
population: P,
individual: I
) -> Result<NodeId, TskitError>where
F: Into<NodeFlags>,
T: Into<Time>,
P: Into<PopulationId>,
I: Into<IndividualId>,
pub fn add_node<F, T, P, I>(
&mut self,
flags: F,
time: T,
population: P,
individual: I
) -> Result<NodeId, TskitError>where
F: Into<NodeFlags>,
T: Into<Time>,
P: Into<PopulationId>,
I: Into<IndividualId>,
Add a row to the node table
sourcepub fn add_node_with_metadata<F, T, P, I, M>(
&mut self,
flags: F,
time: T,
population: P,
individual: I,
metadata: &M
) -> Result<NodeId, TskitError>where
F: Into<NodeFlags>,
T: Into<Time>,
P: Into<PopulationId>,
I: Into<IndividualId>,
M: NodeMetadata,
pub fn add_node_with_metadata<F, T, P, I, M>(
&mut self,
flags: F,
time: T,
population: P,
individual: I,
metadata: &M
) -> Result<NodeId, TskitError>where
F: Into<NodeFlags>,
T: Into<Time>,
P: Into<PopulationId>,
I: Into<IndividualId>,
M: NodeMetadata,
sourcepub fn add_site<P>(
&mut self,
position: P,
ancestral_state: Option<&[u8]>
) -> Result<SiteId, TskitError>where
P: Into<Position>,
pub fn add_site<P>(
&mut self,
position: P,
ancestral_state: Option<&[u8]>
) -> Result<SiteId, TskitError>where
P: Into<Position>,
Add a row to the site table
sourcepub fn add_site_with_metadata<P, M>(
&mut self,
position: P,
ancestral_state: Option<&[u8]>,
metadata: &M
) -> Result<SiteId, TskitError>where
P: Into<Position>,
M: SiteMetadata,
pub fn add_site_with_metadata<P, M>(
&mut self,
position: P,
ancestral_state: Option<&[u8]>,
metadata: &M
) -> Result<SiteId, TskitError>where
P: Into<Position>,
M: SiteMetadata,
Add a row with optional metadata to the site table
Examples
See metadata
for more details about required
trait implementations.
Those details have been omitted from this example.
let metadata = SiteMetadata{x: 1};
assert!(tables.add_site_with_metadata(tskit::Position::from(111.0),
Some(&[111]),
&metadata).is_ok());
sourcepub fn add_mutation<S, N, P, T>(
&mut self,
site: S,
node: N,
parent: P,
time: T,
derived_state: Option<&[u8]>
) -> Result<MutationId, TskitError>where
S: Into<SiteId>,
N: Into<NodeId>,
P: Into<MutationId>,
T: Into<Time>,
pub fn add_mutation<S, N, P, T>(
&mut self,
site: S,
node: N,
parent: P,
time: T,
derived_state: Option<&[u8]>
) -> Result<MutationId, TskitError>where
S: Into<SiteId>,
N: Into<NodeId>,
P: Into<MutationId>,
T: Into<Time>,
Add a row to the mutation table.
sourcepub fn add_mutation_with_metadata<S, N, P, T, M>(
&mut self,
site: S,
node: N,
parent: P,
time: T,
derived_state: Option<&[u8]>,
metadata: &M
) -> Result<MutationId, TskitError>where
S: Into<SiteId>,
N: Into<NodeId>,
P: Into<MutationId>,
T: Into<Time>,
M: MutationMetadata,
pub fn add_mutation_with_metadata<S, N, P, T, M>(
&mut self,
site: S,
node: N,
parent: P,
time: T,
derived_state: Option<&[u8]>,
metadata: &M
) -> Result<MutationId, TskitError>where
S: Into<SiteId>,
N: Into<NodeId>,
P: Into<MutationId>,
T: Into<Time>,
M: MutationMetadata,
Add a row with optional metadata to the mutation table.
Examples
See metadata
for more details about required
trait implementations.
Those details have been omitted from this example.
let metadata = MutationMetadata{x: 1};
assert!(tables.add_mutation_with_metadata(0, 0, 0, 100.0, None,
&metadata).is_ok());
sourcepub fn add_population(&mut self) -> Result<PopulationId, TskitError>
pub fn add_population(&mut self) -> Result<PopulationId, TskitError>
sourcepub fn add_population_with_metadata<M>(
&mut self,
metadata: &M
) -> Result<PopulationId, TskitError>where
M: PopulationMetadata,
pub fn add_population_with_metadata<M>(
&mut self,
metadata: &M
) -> Result<PopulationId, TskitError>where
M: PopulationMetadata,
sourcepub fn build_index(&mut self) -> TskReturnValue
pub fn build_index(&mut self) -> TskReturnValue
Build the “input” and “output” indexes for the edge table.
Note
The C API
call behind this takes a flags
argument
that is currently unused. A future release may break API
here if the C
library is updated to use flags.
sourcepub fn is_indexed(&self) -> bool
pub fn is_indexed(&self) -> bool
Return true
if tables are indexed.
Examples found in repository?
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
pub fn edge_insertion_order(&self) -> Option<&[EdgeId]> {
if self.is_indexed() {
Some(unsafe {
std::slice::from_raw_parts(
(*self.as_ptr()).indexes.edge_insertion_order as *const EdgeId,
usize::try_from((*self.as_ptr()).indexes.num_edges).ok()?,
)
})
} else {
None
}
}
/// If `self.is_indexed()` is `true`, return a non-owning
/// slice containing the edge removal order.
/// Otherwise, return `None`.
pub fn edge_removal_order(&self) -> Option<&[EdgeId]> {
if self.is_indexed() {
Some(unsafe {
std::slice::from_raw_parts(
(*self.as_ptr()).indexes.edge_removal_order as *const EdgeId,
usize::try_from((*self.as_ptr()).indexes.num_edges).ok()?,
)
})
} else {
None
}
}
sourcepub fn edge_insertion_order(&self) -> Option<&[EdgeId]>
pub fn edge_insertion_order(&self) -> Option<&[EdgeId]>
If self.is_indexed()
is true
, return a non-owning
slice containing the edge insertion order.
Otherwise, return None
.
sourcepub fn edge_removal_order(&self) -> Option<&[EdgeId]>
pub fn edge_removal_order(&self) -> Option<&[EdgeId]>
If self.is_indexed()
is true
, return a non-owning
slice containing the edge removal order.
Otherwise, return None
.
sourcepub fn sort<O: Into<TableSortOptions>>(
&mut self,
start: &Bookmark,
options: O
) -> TskReturnValue
pub fn sort<O: Into<TableSortOptions>>(
&mut self,
start: &Bookmark,
options: O
) -> TskReturnValue
sourcepub fn full_sort<O: Into<TableSortOptions>>(
&mut self,
options: O
) -> TskReturnValue
pub fn full_sort<O: Into<TableSortOptions>>(
&mut self,
options: O
) -> TskReturnValue
Fully sort all tables.
Implemented via a call to sort
.
Details
This function only sorts the tables that have a strict sortedness
requirement according to the tskit
data
model.
These tables are:
- edges
- mutations
- sites
For some use cases it is desirable to have the individual table
sorted so that parents appear before offspring. See
topological_sort_individuals
.
sourcepub fn topological_sort_individuals<O: Into<IndividualTableSortOptions>>(
&mut self,
options: O
) -> TskReturnValue
pub fn topological_sort_individuals<O: Into<IndividualTableSortOptions>>(
&mut self,
options: O
) -> TskReturnValue
Sorts the individual table in place, so that parents come before children, and the parent column is remapped as required. Node references to individuals are also updated.
This function is needed because neither sort
nor
full_sort
sorts
the individual table!
Examples
// Parent comes AFTER the child
let mut tables = tskit::TableCollection::new(1.0).unwrap();
let i0 = tables.add_individual(0, None, &[1]).unwrap();
assert_eq!(i0, 0);
let i1 = tables.add_individual(0, None, None).unwrap();
assert_eq!(i1, 1);
let n0 = tables.add_node(0, 0.0, -1, i1).unwrap();
assert_eq!(n0, 0);
let n1 = tables.add_node(0, 1.0, -1, i0).unwrap();
assert_eq!(n1, 1);
// Testing for valid individual order will Err:
match tables.check_integrity(tskit::TableIntegrityCheckFlags::CHECK_INDIVIDUAL_ORDERING) {
Ok(_) => panic!("expected Err"),
Err(_) => (),
};
// The standard sort doesn't fix the Err...:
tables.full_sort(tskit::TableSortOptions::default()).unwrap();
match tables.check_integrity(tskit::TableIntegrityCheckFlags::CHECK_INDIVIDUAL_ORDERING) {
Ok(_) => panic!("expected Err"),
Err(_) => (),
};
// ... so we need to intentionally sort the individuals.
let _ = tables.topological_sort_individuals(tskit::IndividualTableSortOptions::default()).unwrap();
tables.check_integrity(tskit::TableIntegrityCheckFlags::CHECK_INDIVIDUAL_ORDERING).unwrap();
Errors
Will return an error code if the underlying C
function returns an error.
sourcepub fn dump<O: Into<TableOutputOptions>>(
&self,
filename: &str,
options: O
) -> TskReturnValue
pub fn dump<O: Into<TableOutputOptions>>(
&self,
filename: &str,
options: O
) -> TskReturnValue
Dump the table collection to file.
Panics
This function allocates a CString
to pass the file name to the C API.
A panic will occur if the system runs out of memory.
sourcepub fn clear<O: Into<TableClearOptions>>(&mut self, options: O) -> TskReturnValue
pub fn clear<O: Into<TableClearOptions>>(&mut self, options: O) -> TskReturnValue
Clear the contents of all tables. Does not release memory. Memory will be released when the object goes out of scope.
sourcepub fn equals<O: Into<TableEqualityOptions>>(
&self,
other: &TableCollection,
options: O
) -> bool
pub fn equals<O: Into<TableEqualityOptions>>(
&self,
other: &TableCollection,
options: O
) -> bool
Return true
if self
contains the same
data as other
, and false
otherwise.
sourcepub fn deepcopy(&self) -> Result<TableCollection, TskitError>
pub fn deepcopy(&self) -> Result<TableCollection, TskitError>
Return a “deep” copy of the tables.
sourcepub fn tree_sequence(
self,
flags: TreeSequenceFlags
) -> Result<TreeSequence, TskitError>
pub fn tree_sequence(
self,
flags: TreeSequenceFlags
) -> Result<TreeSequence, TskitError>
Return a crate::TreeSequence
based on the tables.
This function will raise errors if tables are not sorted,
not indexed, or invalid in any way.
sourcepub fn simplify<N: Into<NodeId>, O: Into<SimplificationOptions>>(
&mut self,
samples: &[N],
options: O,
idmap: bool
) -> Result<Option<&[NodeId]>, TskitError>
pub fn simplify<N: Into<NodeId>, O: Into<SimplificationOptions>>(
&mut self,
samples: &[N],
options: O,
idmap: bool
) -> Result<Option<&[NodeId]>, TskitError>
Simplify tables in place.
Parameters
samples
: a slice containing non-null node ids. The tables are simplified with respect to the ancestry of these nodes.options
: ASimplificationOptions
bit field controlling the behavior of simplification.idmap
: iftrue
, the return value contains a vector equal in length to the input node table. For each input node, this vector either contains the node’s new index orNodeId::NULL
if the input node is not part of the simplified history.
sourcepub fn check_integrity(&self, flags: TableIntegrityCheckFlags) -> TskReturnValue
pub fn check_integrity(&self, flags: TableIntegrityCheckFlags) -> TskReturnValue
Validate the contents of the table collection
Parameters
flags
is an instance of TableIntegrityCheckFlags
Return value
0
upon success, or an error code.
However, if flags
contains TableIntegrityCheckFlags::CHECK_TREES
,
and no error is returned, then the return value is the number
of trees.
Note
Creating a crate::TreeSequence
from a table collection will automatically
run an integrity check.
See TableCollection::tree_sequence
.
Examples
There are many ways for a table colletion to be invalid. These examples are just the tip of the iceberg.
let mut tables = tskit::TableCollection::new(10.0).unwrap();
// Right position is > sequence_length
tables.add_edge(0.0, 11.0, 0, 0);
tables.check_integrity(tskit::TableIntegrityCheckFlags::default()).unwrap();
// Left position is < 0.0
tables.add_edge(-1., 10.0, 0, 0);
tables.check_integrity(tskit::TableIntegrityCheckFlags::default()).unwrap();
// Edges cannot have null node ids
tables.add_edge(0., 10.0, tskit::NodeId::NULL, 0);
tables.check_integrity(tskit::TableIntegrityCheckFlags::default()).unwrap();
sourcepub fn add_provenance(
&mut self,
record: &str
) -> Result<ProvenanceId, TskitError>
pub fn add_provenance(
&mut self,
record: &str
) -> Result<ProvenanceId, TskitError>
Add provenance record with a time stamp.
All implementation of this trait provided by tskit
use
an ISO 8601
format time stamp
written using the RFC 3339
specification.
This formatting approach has been the most straightforward method
for supporting round trips to/from a crate::provenance::ProvenanceTable
.
The implementations used here use the humantime
crate.
Parameters
record
: the provenance record
Examples
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 `humantime::Timestamp` object back from the `String`:
use core::str::FromStr;
let timestamp_string = humantime::Timestamp::from_str(×tamp).unwrap();
// 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);
sourcepub fn set_edges(&mut self, edges: &OwningEdgeTable) -> TskReturnValue
pub fn set_edges(&mut self, edges: &OwningEdgeTable) -> TskReturnValue
Set the edge table from an OwningEdgeTable
Errors
Any errors from the C API propagate.
Example
let mut tables = tskit::TableCollection::new(1.0).unwrap();
let mut edges = tskit::OwningEdgeTable::default();
edges.add_row(0., 1., 0, 12).unwrap();
tables.set_edges(&edges).unwrap();
assert_eq!(tables.edges().num_rows(), 1);
assert_eq!(tables.edges().child(0).unwrap(), 12);
sourcepub fn set_nodes(&mut self, nodes: &OwningNodeTable) -> TskReturnValue
pub fn set_nodes(&mut self, nodes: &OwningNodeTable) -> TskReturnValue
Set the node table from an OwningNodeTable
Errors
Any errors from the C API propagate.
Example
let mut tables = tskit::TableCollection::new(1.0).unwrap();
let mut nodes = tskit::OwningNodeTable::default();
nodes.add_row(0, 10.0, -1, -1).unwrap();
tables.set_nodes(&nodes).unwrap();
assert_eq!(tables.nodes().num_rows(), 1);
assert_eq!(tables.nodes().time(0).unwrap(), 10.0);
sourcepub fn set_sites(&mut self, sites: &OwningSiteTable) -> TskReturnValue
pub fn set_sites(&mut self, sites: &OwningSiteTable) -> TskReturnValue
Set the site table from an OwningSiteTable
Errors
Any errors from the C API propagate.
Example
let mut tables = tskit::TableCollection::new(1.0).unwrap();
let mut sites = tskit::OwningSiteTable::default();
sites.add_row(11.0, None).unwrap();
tables.set_sites(&sites).unwrap();
assert_eq!(tables.sites().num_rows(), 1);
assert_eq!(tables.sites().position(0).unwrap(), 11.0);
sourcepub fn set_mutations(
&mut self,
mutations: &OwningMutationTable
) -> TskReturnValue
pub fn set_mutations(
&mut self,
mutations: &OwningMutationTable
) -> TskReturnValue
Set the mutation table from an OwningMutationTable
Errors
Any errors from the C API propagate.
Example
let mut tables = tskit::TableCollection::new(1.0).unwrap();
let mut mutations = tskit::OwningMutationTable::default();
mutations.add_row(14, 12, -1, 11.3, None).unwrap();
tables.set_mutations(&mutations).unwrap();
assert_eq!(tables.mutations().num_rows(), 1);
assert_eq!(tables.mutations().site(0).unwrap(), 14);
sourcepub fn set_individuals(
&mut self,
individuals: &OwningIndividualTable
) -> TskReturnValue
pub fn set_individuals(
&mut self,
individuals: &OwningIndividualTable
) -> TskReturnValue
Set the individual table from an OwningIndividualTable
Errors
Any errors from the C API propagate.
Example
let mut tables = tskit::TableCollection::new(1.0).unwrap();
let mut individuals = tskit::OwningIndividualTable::default();
individuals.add_row(0, [0.1, 10.0], None).unwrap();
tables.set_individuals(&individuals).unwrap();
assert_eq!(tables.individuals().num_rows(), 1);
let expected = vec![tskit::Location::from(0.1), tskit::Location::from(10.0)];
assert_eq!(tables.individuals().location(0), Some(expected.as_slice()));
sourcepub fn set_migrations(
&mut self,
migrations: &OwningMigrationTable
) -> TskReturnValue
pub fn set_migrations(
&mut self,
migrations: &OwningMigrationTable
) -> TskReturnValue
Set the migration table from an OwningMigrationTable
Errors
Any errors from the C API propagate.
Example
let mut tables = tskit::TableCollection::new(1.0).unwrap();
let mut migrations = tskit::OwningMigrationTable::default();
migrations.add_row((0.25, 0.37), 1, (0, 1), 111.0).unwrap();
tables.set_migrations(&migrations).unwrap();
assert_eq!(tables.migrations().num_rows(), 1);
assert_eq!(tables.migrations().time(0).unwrap(), 111.0);
sourcepub fn set_populations(
&mut self,
populations: &OwningPopulationTable
) -> TskReturnValue
pub fn set_populations(
&mut self,
populations: &OwningPopulationTable
) -> TskReturnValue
Set the population table from an OwningPopulationTable
Errors
Any errors from the C API propagate.
Example
let mut tables = tskit::TableCollection::new(1.0).unwrap();
let mut populations = tskit::OwningPopulationTable::default();
populations.add_row().unwrap();
tables.set_populations(&populations).unwrap();
assert_eq!(tables.populations().num_rows(), 1);
sourcepub fn set_provenances(
&mut self,
provenances: &OwningProvenanceTable
) -> TskReturnValue
Available on crate feature provenance
only.
pub fn set_provenances(
&mut self,
provenances: &OwningProvenanceTable
) -> TskReturnValue
provenance
only.Set the provenance table from an
OwningProvenanceTable
Errors
Any errors from the C API propagate.
Example
let mut tables = tskit::TableCollection::new(1.0).unwrap();
let mut provenances = tskit::provenance::OwningProvenanceTable::default();
provenances.add_row("I like pancakes").unwrap();
tables.set_provenances(&provenances).unwrap();
assert_eq!(tables.provenances().num_rows(), 1);
assert_eq!(tables.provenances().record(0).unwrap(), "I like pancakes");
sourcepub fn individuals(&self) -> &IndividualTable
pub fn individuals(&self) -> &IndividualTable
Get reference to the IndividualTable
.
sourcepub fn migrations(&self) -> &MigrationTable
pub fn migrations(&self) -> &MigrationTable
Get reference to the MigrationTable
.
sourcepub fn mutations(&self) -> &MutationTable
pub fn mutations(&self) -> &MutationTable
Get reference to the MutationTable
.
sourcepub fn populations(&self) -> &PopulationTable
pub fn populations(&self) -> &PopulationTable
Get reference to the PopulationTable
.
sourcepub fn provenances(&self) -> &ProvenanceTable
Available on crate feature provenance
only.
pub fn provenances(&self) -> &ProvenanceTable
provenance
only.Get reference to the ProvenanceTable
sourcepub fn individuals_iter(&self) -> impl Iterator<Item = IndividualTableRow> + '_
pub fn individuals_iter(&self) -> impl Iterator<Item = IndividualTableRow> + '_
Return an iterator over the individuals.
sourcepub fn nodes_iter(&self) -> impl Iterator<Item = NodeTableRow> + '_
pub fn nodes_iter(&self) -> impl Iterator<Item = NodeTableRow> + '_
Return an iterator over the nodes.
sourcepub fn edges_iter(&self) -> impl Iterator<Item = EdgeTableRow> + '_
pub fn edges_iter(&self) -> impl Iterator<Item = EdgeTableRow> + '_
Return an iterator over the edges.
sourcepub fn migrations_iter(&self) -> impl Iterator<Item = MigrationTableRow> + '_
pub fn migrations_iter(&self) -> impl Iterator<Item = MigrationTableRow> + '_
Return an iterator over the migrations.
sourcepub fn mutations_iter(&self) -> impl Iterator<Item = MutationTableRow> + '_
pub fn mutations_iter(&self) -> impl Iterator<Item = MutationTableRow> + '_
Return an iterator over the mutations.
sourcepub fn populations_iter(&self) -> impl Iterator<Item = PopulationTableRow> + '_
pub fn populations_iter(&self) -> impl Iterator<Item = PopulationTableRow> + '_
Return an iterator over the populations.
sourcepub fn sites_iter(&self) -> impl Iterator<Item = SiteTableRow> + '_
pub fn sites_iter(&self) -> impl Iterator<Item = SiteTableRow> + '_
Return an iterator over the sites.
sourcepub fn provenances_iter(&self) -> impl Iterator<Item = ProvenanceTableRow> + '_
Available on crate feature provenance
only.
pub fn provenances_iter(&self) -> impl Iterator<Item = ProvenanceTableRow> + '_
provenance
only.Return an iterator over provenances
sourcepub fn samples_as_vector(&self) -> Vec<NodeId>
pub fn samples_as_vector(&self) -> Vec<NodeId>
Obtain a vector containing the indexes (“ids”)
of all nodes for which crate::TSK_NODE_IS_SAMPLE
is true
.
The provided implementation dispatches to
crate::NodeTable::samples_as_vector
.
sourcepub fn create_node_id_vector(
&self,
f: impl FnMut(&NodeTableRow) -> bool
) -> Vec<NodeId>
pub fn create_node_id_vector(
&self,
f: impl FnMut(&NodeTableRow) -> bool
) -> Vec<NodeId>
Obtain a vector containing the indexes (“ids”) of all nodes satisfying a certain criterion.
The provided implementation dispatches to
crate::NodeTable::create_node_id_vector
.
Parameters
f
: a function. The function is passed the current table collection and eachcrate::node_table::NodeTableRow
. Iff
returnstrue
, the index of that row is included in the return value.
Examples
Get all nodes with time > 0.0:
let mut tables = tskit::TableCollection::new(100.).unwrap();
tables
.add_node(tskit::TSK_NODE_IS_SAMPLE, 0.0, tskit::PopulationId::NULL,
tskit::IndividualId::NULL)
.unwrap();
tables
.add_node(tskit::TSK_NODE_IS_SAMPLE, 1.0, tskit::PopulationId::NULL,
tskit::IndividualId::NULL)
.unwrap();
let samples = tables.create_node_id_vector(
|row: &tskit::NodeTableRow| row.time > 0.,
);
assert_eq!(samples[0], 1);
sourcepub fn as_ptr(&self) -> *const tsk_table_collection_t
pub fn as_ptr(&self) -> *const tsk_table_collection_t
Pointer to the low-level C type.
Examples found in repository?
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 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848
pub fn sequence_length(&self) -> Position {
unsafe { (*self.as_ptr()).sequence_length }.into()
}
edge_table_add_row!(
/// Add a row to the edge table
///
/// # Examples
///
/// ```
/// # let mut tables = tskit::TableCollection::new(100.).unwrap();
///
/// // left, right, parent, child
/// match tables.add_edge(0., 53., 1, 11) {
/// // This is the first edge, so its id will be
/// // zero (0).
/// Ok(edge_id) => assert_eq!(edge_id, 0),
/// Err(e) => panic!("{:?}", e),
/// }
/// ```
///
/// You may also use [`Position`] and [`NodeId`] as inputs.
///
/// ```
/// # let mut tables = tskit::TableCollection::new(100.).unwrap();
/// let left = tskit::Position::from(0.0);
/// let right = tskit::Position::from(53.0);
/// let parent = tskit::NodeId::from(1);
/// let child = tskit::NodeId::from(11);
/// match tables.add_edge(left, right, parent, child) {
/// Ok(edge_id) => assert_eq!(edge_id, 0),
/// Err(e) => panic!("{:?}", e),
/// }
/// ```
///
/// Adding invalid data is allowed at this point:
///
/// ```
/// # let mut tables = tskit::TableCollection::new(100.).unwrap();
/// assert!(tables.add_edge(0., 53.,
/// tskit::NodeId::NULL,
/// tskit::NodeId::NULL).is_ok());
/// # assert!(tables.check_integrity(tskit::TableIntegrityCheckFlags::default()).is_err());
/// ```
///
/// See [`TableCollection::check_integrity`] for how to catch these data model
/// violations.
=> add_edge, self, &mut(*self.as_mut_ptr()).edges);
edge_table_add_row_with_metadata!(
/// Add a row with optional metadata to the edge table
///
/// # Examples
///
/// See [`metadata`](crate::metadata) for more details about required
/// trait implementations.
/// Those details have been omitted from this example.
///
/// ```
/// # #[cfg(feature = "derive")] {
/// # let mut tables = tskit::TableCollection::new(100.).unwrap();
/// # #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::EdgeMetadata)]
/// # #[serializer("serde_json")]
/// # struct EdgeMetadata {
/// # x: i32,
/// # }
/// let metadata = EdgeMetadata{x: 1};
/// assert!(tables.add_edge_with_metadata(0., 53., 1, 11, &metadata).is_ok());
/// # }
/// ```
=> add_edge_with_metadata, self, &mut(*self.as_mut_ptr()).edges);
individual_table_add_row!(
/// Add a row to the individual table
///
/// # Examples
///
/// ## No flags, location, nor parents
///
/// ```
/// #
/// # let mut tables = tskit::TableCollection::new(1.0).unwrap();
/// tables.add_individual(0, None, None).unwrap();
/// # assert!(tables.individuals().location(0).is_none());
/// # assert!(tables.individuals().parents(0).is_none());
/// ```
///
/// ## No flags, a 3d location, no parents
///
/// ```
/// #
/// # let mut tables = tskit::TableCollection::new(1.0).unwrap();
/// tables.add_individual(0, &[-0.5, 0.3, 10.0], None).unwrap();
/// # match tables.individuals().location(0) {
/// # Some(loc) => loc.iter().zip([-0.5, 0.3, 10.0].iter()).for_each(|(a,b)| assert_eq!(a, b)),
/// # None => panic!("expected a location"),
/// # }
/// ```
///
/// ## No flags, no location, two parents
/// ```
/// # let mut tables = tskit::TableCollection::new(1.0).unwrap();
/// #
/// tables.add_individual(0, None, &[1, 11]);
/// # match tables.individuals().parents(0) {
/// # Some(parents) => parents.iter().zip([1, 11].iter()).for_each(|(a,b)| assert_eq!(a, b)),
/// # None => panic!("expected parents"),
/// # }
/// ```
=> add_individual, self, &mut (*self.as_mut_ptr()).individuals);
individual_table_add_row_with_metadata!(
/// Add a row with metadata to the individual table
///
/// # Examples
///
/// See [`metadata`](crate::metadata) for more details about required
/// trait implementations.
/// Those details have been omitted from this example.
///
/// ```
/// # #[cfg(feature = "derive")] {
///
/// # let mut tables = tskit::TableCollection::new(100.).unwrap();
/// # #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::IndividualMetadata)]
/// # #[serializer("serde_json")]
/// # struct IndividualMetadata {
/// # x: i32,
/// # }
/// let metadata = IndividualMetadata{x: 1};
/// assert!(tables.add_individual_with_metadata(0, None, None,
/// &metadata).is_ok());
/// # let decoded = tables.individuals().metadata::<IndividualMetadata>(0.into()).unwrap().unwrap();
/// # assert_eq!(decoded.x, 1);
/// # }
=> add_individual_with_metadata, self, &mut (*self.as_mut_ptr()).individuals);
migration_table_add_row!(
/// Add a row to the migration table
///
/// # Warnings
///
/// Migration tables are not currently supported
/// by tree sequence simplification.
/// # Examples
///
/// ```
/// # let mut tables = tskit::TableCollection::new(100.).unwrap();
/// assert!(tables.add_migration((0.5, 100.0),
/// 3,
/// (0, 1),
/// 53.5).is_ok());
/// ```
=> add_migration, self, &mut (*self.as_mut_ptr()).migrations);
migration_table_add_row_with_metadata!(
/// Add a row with optional metadata to the migration table
///
/// # Examples
///
/// See [`metadata`](crate::metadata) for more details about required
/// trait implementations.
/// Those details have been omitted from this example.
///
/// ```
/// # #[cfg(feature = "derive")] {
/// # let mut tables = tskit::TableCollection::new(100.).unwrap();
/// # #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::MigrationMetadata)]
/// # #[serializer("serde_json")]
/// # struct MigrationMetadata {
/// # x: i32,
/// # }
/// let metadata = MigrationMetadata{x: 1};
/// assert!(tables.add_migration_with_metadata((0.5, 100.0),
/// 3,
/// (0, 1),
/// 53.5,
/// &metadata).is_ok());
/// # }
/// ```
///
/// # Warnings
///
/// Migration tables are not currently supported
/// by tree sequence simplification.
=> add_migration_with_metadata, self, &mut (*self.as_mut_ptr()).migrations);
node_table_add_row!(
/// Add a row to the node table
=> add_node, self, &mut (*self.as_mut_ptr()).nodes);
node_table_add_row_with_metadata!(
/// Add a row with optional metadata to the node table
///
/// # Examples
///
/// See [`metadata`](crate::metadata) for more details about required
/// trait implementations.
/// Those details have been omitted from this example.
///
/// ```
/// # #[cfg(feature = "derive")] {
/// # let mut tables = tskit::TableCollection::new(100.).unwrap();
/// # #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::NodeMetadata)]
/// # #[serializer("serde_json")]
/// # struct NodeMetadata {
/// # x: i32,
/// # }
/// let metadata = NodeMetadata{x: 1};
/// assert!(tables.add_node_with_metadata(0, 0.0, -1, -1, &metadata).is_ok());
/// # }
/// ```
=> add_node_with_metadata, self, &mut (*self.as_mut_ptr()).nodes);
site_table_add_row!(
/// Add a row to the site table
=> add_site, self, &mut (*self.as_mut_ptr()).sites);
site_table_add_row_with_metadata!(
/// Add a row with optional metadata to the site table
///
/// # Examples
///
/// See [`metadata`](crate::metadata) for more details about required
/// trait implementations.
/// Those details have been omitted from this example.
///
/// ```
/// # #[cfg(feature = "derive")] {
/// # let mut tables = tskit::TableCollection::new(100.).unwrap();
/// # #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::SiteMetadata)]
/// # #[serializer("serde_json")]
/// # struct SiteMetadata {
/// # x: i32,
/// # }
/// let metadata = SiteMetadata{x: 1};
/// assert!(tables.add_site_with_metadata(tskit::Position::from(111.0),
/// Some(&[111]),
/// &metadata).is_ok());
/// # }
/// ```
=> add_site_with_metadata, self, &mut (*self.as_mut_ptr()).sites);
mutation_table_add_row!(
/// Add a row to the mutation table.
=> add_mutation, self, &mut (*self.as_mut_ptr()).mutations);
mutation_table_add_row_with_metadata!(
/// Add a row with optional metadata to the mutation table.
///
/// # Examples
///
/// See [`metadata`](crate::metadata) for more details about required
/// trait implementations.
/// Those details have been omitted from this example.
///
/// ```
/// # #[cfg(feature = "derive")] {
/// # let mut tables = tskit::TableCollection::new(100.).unwrap();
/// # #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::MutationMetadata)]
/// # #[serializer("serde_json")]
/// # struct MutationMetadata {
/// # x: i32,
/// # }
/// let metadata = MutationMetadata{x: 1};
/// assert!(tables.add_mutation_with_metadata(0, 0, 0, 100.0, None,
/// &metadata).is_ok());
/// # }
/// ```
=> add_mutation_with_metadata, self, &mut (*self.as_mut_ptr()).mutations);
population_table_add_row!(
/// Add a row to the population_table
///
/// # Examples
///
/// ```
/// # let mut tables = tskit::TableCollection::new(55.0).unwrap();
/// tables.add_population().unwrap();
/// ```
=> add_population, self, &mut (*self.as_mut_ptr()).populations);
population_table_add_row_with_metadata!(
/// Add a row with optional metadata to the population_table
///
/// # Examples
///
/// See [`metadata`](crate::metadata) for more details about required
/// trait implementations.
/// Those details have been omitted from this example.
///
/// ```
/// # #[cfg(feature = "derive")] {
/// # let mut tables = tskit::TableCollection::new(100.).unwrap();
/// # #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::PopulationMetadata)]
/// # #[serializer("serde_json")]
/// # struct PopulationMetadata {
/// # x: i32,
/// # }
/// let metadata = PopulationMetadata{x: 1};
/// assert!(tables.add_population_with_metadata(&metadata).is_ok());
/// # }
=> add_population_with_metadata, self, &mut (*self.as_mut_ptr()).populations);
/// Build the "input" and "output"
/// indexes for the edge table.
///
/// # Note
///
/// The `C API` call behind this takes a `flags` argument
/// that is currently unused. A future release may break `API`
/// here if the `C` library is updated to use flags.
pub fn build_index(&mut self) -> TskReturnValue {
let rv = unsafe { ll_bindings::tsk_table_collection_build_index(self.as_mut_ptr(), 0) };
handle_tsk_return_value!(rv)
}
/// Return `true` if tables are indexed.
pub fn is_indexed(&self) -> bool {
unsafe { ll_bindings::tsk_table_collection_has_index(self.as_ptr(), 0) }
}
/// If `self.is_indexed()` is `true`, return a non-owning
/// slice containing the edge insertion order.
/// Otherwise, return `None`.
pub fn edge_insertion_order(&self) -> Option<&[EdgeId]> {
if self.is_indexed() {
Some(unsafe {
std::slice::from_raw_parts(
(*self.as_ptr()).indexes.edge_insertion_order as *const EdgeId,
usize::try_from((*self.as_ptr()).indexes.num_edges).ok()?,
)
})
} else {
None
}
}
/// If `self.is_indexed()` is `true`, return a non-owning
/// slice containing the edge removal order.
/// Otherwise, return `None`.
pub fn edge_removal_order(&self) -> Option<&[EdgeId]> {
if self.is_indexed() {
Some(unsafe {
std::slice::from_raw_parts(
(*self.as_ptr()).indexes.edge_removal_order as *const EdgeId,
usize::try_from((*self.as_ptr()).indexes.num_edges).ok()?,
)
})
} else {
None
}
}
/// Sort the tables.
/// The [``bookmark``](crate::types::Bookmark) can
/// be used to affect where sorting starts from for each table.
///
/// # Details
///
/// See [`full_sort`](crate::TableCollection::full_sort)
/// for more details about which tables are sorted.
pub fn sort<O: Into<TableSortOptions>>(
&mut self,
start: &Bookmark,
options: O,
) -> TskReturnValue {
let rv = unsafe {
ll_bindings::tsk_table_collection_sort(
self.as_mut_ptr(),
&start.offsets,
options.into().bits(),
)
};
handle_tsk_return_value!(rv)
}
/// Fully sort all tables.
/// Implemented via a call to [``sort``](crate::TableCollection::sort).
///
/// # Details
///
/// This function only sorts the tables that have a strict sortedness
/// requirement according to the `tskit` [data
/// model](https://tskit.dev/tskit/docs/stable/data-model.html).
///
/// These tables are:
///
/// * edges
/// * mutations
/// * sites
///
/// For some use cases it is desirable to have the individual table
/// sorted so that parents appear before offspring. See
/// [``topological_sort_individuals``](crate::TableCollection::topological_sort_individuals).
pub fn full_sort<O: Into<TableSortOptions>>(&mut self, options: O) -> TskReturnValue {
let b = Bookmark::new();
self.sort(&b, options)
}
/// Sorts the individual table in place, so that parents come before children,
/// and the parent column is remapped as required. Node references to individuals
/// are also updated.
///
/// This function is needed because neither [``sort``](crate::TableCollection::sort) nor
/// [``full_sort``](crate::TableCollection::full_sort) sorts
/// the individual table!
///
/// # Examples
///
/// ```
/// // Parent comes AFTER the child
/// let mut tables = tskit::TableCollection::new(1.0).unwrap();
/// let i0 = tables.add_individual(0, None, &[1]).unwrap();
/// assert_eq!(i0, 0);
/// let i1 = tables.add_individual(0, None, None).unwrap();
/// assert_eq!(i1, 1);
/// let n0 = tables.add_node(0, 0.0, -1, i1).unwrap();
/// assert_eq!(n0, 0);
/// let n1 = tables.add_node(0, 1.0, -1, i0).unwrap();
/// assert_eq!(n1, 1);
///
/// // Testing for valid individual order will Err:
/// match tables.check_integrity(tskit::TableIntegrityCheckFlags::CHECK_INDIVIDUAL_ORDERING) {
/// Ok(_) => panic!("expected Err"),
/// Err(_) => (),
/// };
///
/// // The standard sort doesn't fix the Err...:
/// tables.full_sort(tskit::TableSortOptions::default()).unwrap();
/// match tables.check_integrity(tskit::TableIntegrityCheckFlags::CHECK_INDIVIDUAL_ORDERING) {
/// Ok(_) => panic!("expected Err"),
/// Err(_) => (),
/// };
///
/// // ... so we need to intentionally sort the individuals.
/// let _ = tables.topological_sort_individuals(tskit::IndividualTableSortOptions::default()).unwrap();
/// tables.check_integrity(tskit::TableIntegrityCheckFlags::CHECK_INDIVIDUAL_ORDERING).unwrap();
/// ```
///
/// # Errors
///
/// Will return an error code if the underlying `C` function returns an error.
pub fn topological_sort_individuals<O: Into<IndividualTableSortOptions>>(
&mut self,
options: O,
) -> TskReturnValue {
let rv = unsafe {
ll_bindings::tsk_table_collection_individual_topological_sort(
self.as_mut_ptr(),
options.into().bits(),
)
};
handle_tsk_return_value!(rv)
}
/// Dump the table collection to file.
///
/// # Panics
///
/// This function allocates a `CString` to pass the file name to the C API.
/// A panic will occur if the system runs out of memory.
pub fn dump<O: Into<TableOutputOptions>>(&self, filename: &str, options: O) -> TskReturnValue {
let c_str = std::ffi::CString::new(filename).map_err(|_| {
TskitError::LibraryError("call to ffi::CString::new failed".to_string())
})?;
let rv = unsafe {
ll_bindings::tsk_table_collection_dump(
self.as_ptr(),
c_str.as_ptr(),
options.into().bits(),
)
};
handle_tsk_return_value!(rv)
}
/// Clear the contents of all tables.
/// Does not release memory.
/// Memory will be released when the object goes out
/// of scope.
pub fn clear<O: Into<TableClearOptions>>(&mut self, options: O) -> TskReturnValue {
let rv = unsafe {
ll_bindings::tsk_table_collection_clear(self.as_mut_ptr(), options.into().bits())
};
handle_tsk_return_value!(rv)
}
/// Free all memory allocated on the C side.
/// Not public b/c not very safe.
#[allow(dead_code)]
fn free(&mut self) -> TskReturnValue {
let rv = unsafe { ll_bindings::tsk_table_collection_free(self.as_mut_ptr()) };
handle_tsk_return_value!(rv)
}
/// Return ``true`` if ``self`` contains the same
/// data as ``other``, and ``false`` otherwise.
pub fn equals<O: Into<TableEqualityOptions>>(
&self,
other: &TableCollection,
options: O,
) -> bool {
unsafe {
ll_bindings::tsk_table_collection_equals(
self.as_ptr(),
other.as_ptr(),
options.into().bits(),
)
}
}
/// Return a "deep" copy of the tables.
pub fn deepcopy(&self) -> Result<TableCollection, TskitError> {
// The output is UNINITIALIZED tables,
// else we leak memory
let mut inner = uninit_table_collection();
let rv = unsafe { ll_bindings::tsk_table_collection_copy(self.as_ptr(), &mut *inner, 0) };
// SAFETY: we just initialized it.
// The C API doesn't free NULL pointers.
handle_tsk_return_value!(rv, unsafe { Self::new_from_mbox(inner)? })
}
/// Return a [`crate::TreeSequence`] based on the tables.
/// This function will raise errors if tables are not sorted,
/// not indexed, or invalid in any way.
pub fn tree_sequence(
self,
flags: TreeSequenceFlags,
) -> Result<crate::TreeSequence, TskitError> {
crate::TreeSequence::new(self, flags)
}
/// Simplify tables in place.
///
/// # Parameters
///
/// * `samples`: a slice containing non-null node ids.
/// The tables are simplified with respect to the ancestry
/// of these nodes.
/// * `options`: A [`SimplificationOptions`] bit field controlling
/// the behavior of simplification.
/// * `idmap`: if `true`, the return value contains a vector equal
/// in length to the input node table. For each input node,
/// this vector either contains the node's new index or [`NodeId::NULL`]
/// if the input node is not part of the simplified history.
pub fn simplify<N: Into<NodeId>, O: Into<SimplificationOptions>>(
&mut self,
samples: &[N],
options: O,
idmap: bool,
) -> Result<Option<&[NodeId]>, TskitError> {
if idmap {
self.idmap.resize(
usize::try_from(self.views.nodes().num_rows())?,
NodeId::NULL,
);
}
let rv = unsafe {
ll_bindings::tsk_table_collection_simplify(
self.as_mut_ptr(),
samples.as_ptr().cast::<tsk_id_t>(),
samples.len() as tsk_size_t,
options.into().bits(),
match idmap {
true => self.idmap.as_mut_ptr().cast::<tsk_id_t>(),
false => std::ptr::null_mut(),
},
)
};
handle_tsk_return_value!(
rv,
match idmap {
true => Some(&self.idmap),
false => None,
}
)
}
/// Validate the contents of the table collection
///
/// # Parameters
///
/// `flags` is an instance of [`TableIntegrityCheckFlags`]
///
/// # Return value
///
/// `0` upon success, or an error code.
/// However, if `flags` contains [`TableIntegrityCheckFlags::CHECK_TREES`],
/// and no error is returned, then the return value is the number
/// of trees.
///
/// # Note
///
/// Creating a [`crate::TreeSequence`] from a table collection will automatically
/// run an integrity check.
/// See [`TableCollection::tree_sequence`].
///
/// # Examples
///
/// There are many ways for a table colletion to be invalid.
/// These examples are just the tip of the iceberg.
///
/// ```should_panic
/// let mut tables = tskit::TableCollection::new(10.0).unwrap();
/// // Right position is > sequence_length
/// tables.add_edge(0.0, 11.0, 0, 0);
/// tables.check_integrity(tskit::TableIntegrityCheckFlags::default()).unwrap();
/// ```
///
/// ```should_panic
/// # let mut tables = tskit::TableCollection::new(10.0).unwrap();
/// // Left position is < 0.0
/// tables.add_edge(-1., 10.0, 0, 0);
/// tables.check_integrity(tskit::TableIntegrityCheckFlags::default()).unwrap();
/// ```
///
/// ```should_panic
/// # let mut tables = tskit::TableCollection::new(10.0).unwrap();
/// // Edges cannot have null node ids
/// tables.add_edge(0., 10.0, tskit::NodeId::NULL, 0);
/// tables.check_integrity(tskit::TableIntegrityCheckFlags::default()).unwrap();
/// ```
pub fn check_integrity(&self, flags: TableIntegrityCheckFlags) -> TskReturnValue {
let rv = unsafe {
ll_bindings::tsk_table_collection_check_integrity(self.as_ptr(), flags.bits())
};
handle_tsk_return_value!(rv)
}
sourcepub fn as_mut_ptr(&mut self) -> *mut tsk_table_collection_t
pub fn as_mut_ptr(&mut self) -> *mut tsk_table_collection_t
Mutable pointer to the low-level C type.
Examples found in repository?
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 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
fn drop(&mut self) {
let rv = unsafe { tsk_table_collection_free(self.as_mut_ptr()) };
assert_eq!(rv, 0);
}
}
/// Returns a pointer to an uninitialized tsk_table_collection_t
pub(crate) fn uninit_table_collection() -> MBox<ll_bindings::tsk_table_collection_t> {
let temp = unsafe {
libc::malloc(std::mem::size_of::<ll_bindings::tsk_table_collection_t>())
as *mut ll_bindings::tsk_table_collection_t
};
let nonnull = match std::ptr::NonNull::<ll_bindings::tsk_table_collection_t>::new(temp) {
Some(x) => x,
None => panic!("out of memory"),
};
unsafe { MBox::from_non_null_raw(nonnull) }
}
impl TableCollection {
/// Create a new table collection with a sequence length.
///
/// # Examples
///
/// ```
/// let tables = tskit::TableCollection::new(55.0).unwrap();
/// ```
///
/// Negative sequence lengths are errors:
///
/// ```{should_panic}
/// let tables = tskit::TableCollection::new(-55.0).unwrap();
/// ```
pub fn new<P: Into<Position>>(sequence_length: P) -> Result<Self, TskitError> {
let sequence_length = sequence_length.into();
if sequence_length <= 0. {
return Err(TskitError::ValueError {
got: f64::from(sequence_length).to_string(),
expected: "sequence_length >= 0.0".to_string(),
});
}
let mut mbox = uninit_table_collection();
let rv = unsafe { ll_bindings::tsk_table_collection_init(&mut *mbox, 0) };
if rv < 0 {
return Err(crate::error::TskitError::ErrorCode { code: rv });
}
let views = crate::table_views::TableViews::new_from_mbox_table_collection(&mut mbox)?;
// AHA?
assert!(std::ptr::eq(
&mbox.as_ref().edges as *const ll_bindings::tsk_edge_table_t,
views.edges().as_ref() as *const ll_bindings::tsk_edge_table_t
));
let mut tables = Self {
inner: mbox,
idmap: vec![],
views,
};
unsafe {
(*tables.as_mut_ptr()).sequence_length = f64::from(sequence_length);
}
Ok(tables)
}
/// # Safety
///
/// It is possible that the mbox's inner pointer has not be run through
/// tsk_table_collection_init, meaning that it is in an uninitialized state.
/// Or, it may be initialized and about to be used in a part of the C API
/// requiring an uninitialized table collection.
/// Consult the C API docs before using!
pub(crate) unsafe fn new_from_mbox(
mbox: MBox<ll_bindings::tsk_table_collection_t>,
) -> Result<Self, TskitError> {
let mut mbox = mbox;
let views = crate::table_views::TableViews::new_from_mbox_table_collection(&mut mbox)?;
Ok(Self {
inner: mbox,
idmap: vec![],
views,
})
}
pub(crate) fn into_raw(self) -> Result<*mut ll_bindings::tsk_table_collection_t, TskitError> {
let mut tables = self;
// rust won't let use move inner out b/c this type implements Drop.
// So we have to replace the existing pointer with a new one.
let table_ptr = unsafe {
libc::malloc(std::mem::size_of::<ll_bindings::tsk_table_collection_t>())
as *mut ll_bindings::tsk_table_collection_t
};
let rv = unsafe { ll_bindings::tsk_table_collection_init(table_ptr, 0) };
let mut temp = unsafe { MBox::from_raw(table_ptr) };
std::mem::swap(&mut temp, &mut tables.inner);
handle_tsk_return_value!(rv, MBox::into_raw(temp))
}
/// Load a table collection from a file.
///
/// # Examples
///
/// The function is generic over references to `str`:
///
/// ```
/// # let empty_tables = tskit::TableCollection::new(100.).unwrap();
/// # empty_tables.dump("trees.file", tskit::TableOutputOptions::default()).unwrap();
/// let tables = tskit::TableCollection::new_from_file("trees.file").unwrap();
///
/// let filename = String::from("trees.file");
/// // Pass filename by reference
/// let tables = tskit::TableCollection::new_from_file(&filename).unwrap();
///
/// // Move filename
/// let tables = tskit::TableCollection::new_from_file(filename).unwrap();
///
/// // Boxed String are an unlikely use case, but can be made to work:
/// let filename = Box::new(String::from("trees.file"));
/// let tables = tskit::TableCollection::new_from_file(&*filename.as_ref()).unwrap();
/// # std::fs::remove_file("trees.file").unwrap();
/// ```
///
/// # Panics
///
/// This function allocates a `CString` to pass the file name to the C API.
/// A panic will occur if the system runs out of memory.
pub fn new_from_file(filename: impl AsRef<str>) -> Result<Self, TskitError> {
// Arbitrary sequence_length.
let mut tables = match TableCollection::new(1.0) {
Ok(t) => t,
Err(e) => return Err(e),
};
let c_str = std::ffi::CString::new(filename.as_ref()).map_err(|_| {
TskitError::LibraryError("call to ffi::CString::new failed".to_string())
})?;
let rv = unsafe {
ll_bindings::tsk_table_collection_load(
tables.as_mut_ptr(),
c_str.as_ptr(),
ll_bindings::TSK_NO_INIT,
)
};
handle_tsk_return_value!(rv, tables)
}
/// Length of the sequence/"genome".
/// # Examples
///
/// ```
/// let tables = tskit::TableCollection::new(100.).unwrap();
/// assert_eq!(tables.sequence_length(), 100.0);
/// ```
pub fn sequence_length(&self) -> Position {
unsafe { (*self.as_ptr()).sequence_length }.into()
}
edge_table_add_row!(
/// Add a row to the edge table
///
/// # Examples
///
/// ```
/// # let mut tables = tskit::TableCollection::new(100.).unwrap();
///
/// // left, right, parent, child
/// match tables.add_edge(0., 53., 1, 11) {
/// // This is the first edge, so its id will be
/// // zero (0).
/// Ok(edge_id) => assert_eq!(edge_id, 0),
/// Err(e) => panic!("{:?}", e),
/// }
/// ```
///
/// You may also use [`Position`] and [`NodeId`] as inputs.
///
/// ```
/// # let mut tables = tskit::TableCollection::new(100.).unwrap();
/// let left = tskit::Position::from(0.0);
/// let right = tskit::Position::from(53.0);
/// let parent = tskit::NodeId::from(1);
/// let child = tskit::NodeId::from(11);
/// match tables.add_edge(left, right, parent, child) {
/// Ok(edge_id) => assert_eq!(edge_id, 0),
/// Err(e) => panic!("{:?}", e),
/// }
/// ```
///
/// Adding invalid data is allowed at this point:
///
/// ```
/// # let mut tables = tskit::TableCollection::new(100.).unwrap();
/// assert!(tables.add_edge(0., 53.,
/// tskit::NodeId::NULL,
/// tskit::NodeId::NULL).is_ok());
/// # assert!(tables.check_integrity(tskit::TableIntegrityCheckFlags::default()).is_err());
/// ```
///
/// See [`TableCollection::check_integrity`] for how to catch these data model
/// violations.
=> add_edge, self, &mut(*self.as_mut_ptr()).edges);
edge_table_add_row_with_metadata!(
/// Add a row with optional metadata to the edge table
///
/// # Examples
///
/// See [`metadata`](crate::metadata) for more details about required
/// trait implementations.
/// Those details have been omitted from this example.
///
/// ```
/// # #[cfg(feature = "derive")] {
/// # let mut tables = tskit::TableCollection::new(100.).unwrap();
/// # #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::EdgeMetadata)]
/// # #[serializer("serde_json")]
/// # struct EdgeMetadata {
/// # x: i32,
/// # }
/// let metadata = EdgeMetadata{x: 1};
/// assert!(tables.add_edge_with_metadata(0., 53., 1, 11, &metadata).is_ok());
/// # }
/// ```
=> add_edge_with_metadata, self, &mut(*self.as_mut_ptr()).edges);
individual_table_add_row!(
/// Add a row to the individual table
///
/// # Examples
///
/// ## No flags, location, nor parents
///
/// ```
/// #
/// # let mut tables = tskit::TableCollection::new(1.0).unwrap();
/// tables.add_individual(0, None, None).unwrap();
/// # assert!(tables.individuals().location(0).is_none());
/// # assert!(tables.individuals().parents(0).is_none());
/// ```
///
/// ## No flags, a 3d location, no parents
///
/// ```
/// #
/// # let mut tables = tskit::TableCollection::new(1.0).unwrap();
/// tables.add_individual(0, &[-0.5, 0.3, 10.0], None).unwrap();
/// # match tables.individuals().location(0) {
/// # Some(loc) => loc.iter().zip([-0.5, 0.3, 10.0].iter()).for_each(|(a,b)| assert_eq!(a, b)),
/// # None => panic!("expected a location"),
/// # }
/// ```
///
/// ## No flags, no location, two parents
/// ```
/// # let mut tables = tskit::TableCollection::new(1.0).unwrap();
/// #
/// tables.add_individual(0, None, &[1, 11]);
/// # match tables.individuals().parents(0) {
/// # Some(parents) => parents.iter().zip([1, 11].iter()).for_each(|(a,b)| assert_eq!(a, b)),
/// # None => panic!("expected parents"),
/// # }
/// ```
=> add_individual, self, &mut (*self.as_mut_ptr()).individuals);
individual_table_add_row_with_metadata!(
/// Add a row with metadata to the individual table
///
/// # Examples
///
/// See [`metadata`](crate::metadata) for more details about required
/// trait implementations.
/// Those details have been omitted from this example.
///
/// ```
/// # #[cfg(feature = "derive")] {
///
/// # let mut tables = tskit::TableCollection::new(100.).unwrap();
/// # #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::IndividualMetadata)]
/// # #[serializer("serde_json")]
/// # struct IndividualMetadata {
/// # x: i32,
/// # }
/// let metadata = IndividualMetadata{x: 1};
/// assert!(tables.add_individual_with_metadata(0, None, None,
/// &metadata).is_ok());
/// # let decoded = tables.individuals().metadata::<IndividualMetadata>(0.into()).unwrap().unwrap();
/// # assert_eq!(decoded.x, 1);
/// # }
=> add_individual_with_metadata, self, &mut (*self.as_mut_ptr()).individuals);
migration_table_add_row!(
/// Add a row to the migration table
///
/// # Warnings
///
/// Migration tables are not currently supported
/// by tree sequence simplification.
/// # Examples
///
/// ```
/// # let mut tables = tskit::TableCollection::new(100.).unwrap();
/// assert!(tables.add_migration((0.5, 100.0),
/// 3,
/// (0, 1),
/// 53.5).is_ok());
/// ```
=> add_migration, self, &mut (*self.as_mut_ptr()).migrations);
migration_table_add_row_with_metadata!(
/// Add a row with optional metadata to the migration table
///
/// # Examples
///
/// See [`metadata`](crate::metadata) for more details about required
/// trait implementations.
/// Those details have been omitted from this example.
///
/// ```
/// # #[cfg(feature = "derive")] {
/// # let mut tables = tskit::TableCollection::new(100.).unwrap();
/// # #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::MigrationMetadata)]
/// # #[serializer("serde_json")]
/// # struct MigrationMetadata {
/// # x: i32,
/// # }
/// let metadata = MigrationMetadata{x: 1};
/// assert!(tables.add_migration_with_metadata((0.5, 100.0),
/// 3,
/// (0, 1),
/// 53.5,
/// &metadata).is_ok());
/// # }
/// ```
///
/// # Warnings
///
/// Migration tables are not currently supported
/// by tree sequence simplification.
=> add_migration_with_metadata, self, &mut (*self.as_mut_ptr()).migrations);
node_table_add_row!(
/// Add a row to the node table
=> add_node, self, &mut (*self.as_mut_ptr()).nodes);
node_table_add_row_with_metadata!(
/// Add a row with optional metadata to the node table
///
/// # Examples
///
/// See [`metadata`](crate::metadata) for more details about required
/// trait implementations.
/// Those details have been omitted from this example.
///
/// ```
/// # #[cfg(feature = "derive")] {
/// # let mut tables = tskit::TableCollection::new(100.).unwrap();
/// # #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::NodeMetadata)]
/// # #[serializer("serde_json")]
/// # struct NodeMetadata {
/// # x: i32,
/// # }
/// let metadata = NodeMetadata{x: 1};
/// assert!(tables.add_node_with_metadata(0, 0.0, -1, -1, &metadata).is_ok());
/// # }
/// ```
=> add_node_with_metadata, self, &mut (*self.as_mut_ptr()).nodes);
site_table_add_row!(
/// Add a row to the site table
=> add_site, self, &mut (*self.as_mut_ptr()).sites);
site_table_add_row_with_metadata!(
/// Add a row with optional metadata to the site table
///
/// # Examples
///
/// See [`metadata`](crate::metadata) for more details about required
/// trait implementations.
/// Those details have been omitted from this example.
///
/// ```
/// # #[cfg(feature = "derive")] {
/// # let mut tables = tskit::TableCollection::new(100.).unwrap();
/// # #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::SiteMetadata)]
/// # #[serializer("serde_json")]
/// # struct SiteMetadata {
/// # x: i32,
/// # }
/// let metadata = SiteMetadata{x: 1};
/// assert!(tables.add_site_with_metadata(tskit::Position::from(111.0),
/// Some(&[111]),
/// &metadata).is_ok());
/// # }
/// ```
=> add_site_with_metadata, self, &mut (*self.as_mut_ptr()).sites);
mutation_table_add_row!(
/// Add a row to the mutation table.
=> add_mutation, self, &mut (*self.as_mut_ptr()).mutations);
mutation_table_add_row_with_metadata!(
/// Add a row with optional metadata to the mutation table.
///
/// # Examples
///
/// See [`metadata`](crate::metadata) for more details about required
/// trait implementations.
/// Those details have been omitted from this example.
///
/// ```
/// # #[cfg(feature = "derive")] {
/// # let mut tables = tskit::TableCollection::new(100.).unwrap();
/// # #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::MutationMetadata)]
/// # #[serializer("serde_json")]
/// # struct MutationMetadata {
/// # x: i32,
/// # }
/// let metadata = MutationMetadata{x: 1};
/// assert!(tables.add_mutation_with_metadata(0, 0, 0, 100.0, None,
/// &metadata).is_ok());
/// # }
/// ```
=> add_mutation_with_metadata, self, &mut (*self.as_mut_ptr()).mutations);
population_table_add_row!(
/// Add a row to the population_table
///
/// # Examples
///
/// ```
/// # let mut tables = tskit::TableCollection::new(55.0).unwrap();
/// tables.add_population().unwrap();
/// ```
=> add_population, self, &mut (*self.as_mut_ptr()).populations);
population_table_add_row_with_metadata!(
/// Add a row with optional metadata to the population_table
///
/// # Examples
///
/// See [`metadata`](crate::metadata) for more details about required
/// trait implementations.
/// Those details have been omitted from this example.
///
/// ```
/// # #[cfg(feature = "derive")] {
/// # let mut tables = tskit::TableCollection::new(100.).unwrap();
/// # #[derive(serde::Serialize, serde::Deserialize, tskit::metadata::PopulationMetadata)]
/// # #[serializer("serde_json")]
/// # struct PopulationMetadata {
/// # x: i32,
/// # }
/// let metadata = PopulationMetadata{x: 1};
/// assert!(tables.add_population_with_metadata(&metadata).is_ok());
/// # }
=> add_population_with_metadata, self, &mut (*self.as_mut_ptr()).populations);
/// Build the "input" and "output"
/// indexes for the edge table.
///
/// # Note
///
/// The `C API` call behind this takes a `flags` argument
/// that is currently unused. A future release may break `API`
/// here if the `C` library is updated to use flags.
pub fn build_index(&mut self) -> TskReturnValue {
let rv = unsafe { ll_bindings::tsk_table_collection_build_index(self.as_mut_ptr(), 0) };
handle_tsk_return_value!(rv)
}
/// Return `true` if tables are indexed.
pub fn is_indexed(&self) -> bool {
unsafe { ll_bindings::tsk_table_collection_has_index(self.as_ptr(), 0) }
}
/// If `self.is_indexed()` is `true`, return a non-owning
/// slice containing the edge insertion order.
/// Otherwise, return `None`.
pub fn edge_insertion_order(&self) -> Option<&[EdgeId]> {
if self.is_indexed() {
Some(unsafe {
std::slice::from_raw_parts(
(*self.as_ptr()).indexes.edge_insertion_order as *const EdgeId,
usize::try_from((*self.as_ptr()).indexes.num_edges).ok()?,
)
})
} else {
None
}
}
/// If `self.is_indexed()` is `true`, return a non-owning
/// slice containing the edge removal order.
/// Otherwise, return `None`.
pub fn edge_removal_order(&self) -> Option<&[EdgeId]> {
if self.is_indexed() {
Some(unsafe {
std::slice::from_raw_parts(
(*self.as_ptr()).indexes.edge_removal_order as *const EdgeId,
usize::try_from((*self.as_ptr()).indexes.num_edges).ok()?,
)
})
} else {
None
}
}
/// Sort the tables.
/// The [``bookmark``](crate::types::Bookmark) can
/// be used to affect where sorting starts from for each table.
///
/// # Details
///
/// See [`full_sort`](crate::TableCollection::full_sort)
/// for more details about which tables are sorted.
pub fn sort<O: Into<TableSortOptions>>(
&mut self,
start: &Bookmark,
options: O,
) -> TskReturnValue {
let rv = unsafe {
ll_bindings::tsk_table_collection_sort(
self.as_mut_ptr(),
&start.offsets,
options.into().bits(),
)
};
handle_tsk_return_value!(rv)
}
/// Fully sort all tables.
/// Implemented via a call to [``sort``](crate::TableCollection::sort).
///
/// # Details
///
/// This function only sorts the tables that have a strict sortedness
/// requirement according to the `tskit` [data
/// model](https://tskit.dev/tskit/docs/stable/data-model.html).
///
/// These tables are:
///
/// * edges
/// * mutations
/// * sites
///
/// For some use cases it is desirable to have the individual table
/// sorted so that parents appear before offspring. See
/// [``topological_sort_individuals``](crate::TableCollection::topological_sort_individuals).
pub fn full_sort<O: Into<TableSortOptions>>(&mut self, options: O) -> TskReturnValue {
let b = Bookmark::new();
self.sort(&b, options)
}
/// Sorts the individual table in place, so that parents come before children,
/// and the parent column is remapped as required. Node references to individuals
/// are also updated.
///
/// This function is needed because neither [``sort``](crate::TableCollection::sort) nor
/// [``full_sort``](crate::TableCollection::full_sort) sorts
/// the individual table!
///
/// # Examples
///
/// ```
/// // Parent comes AFTER the child
/// let mut tables = tskit::TableCollection::new(1.0).unwrap();
/// let i0 = tables.add_individual(0, None, &[1]).unwrap();
/// assert_eq!(i0, 0);
/// let i1 = tables.add_individual(0, None, None).unwrap();
/// assert_eq!(i1, 1);
/// let n0 = tables.add_node(0, 0.0, -1, i1).unwrap();
/// assert_eq!(n0, 0);
/// let n1 = tables.add_node(0, 1.0, -1, i0).unwrap();
/// assert_eq!(n1, 1);
///
/// // Testing for valid individual order will Err:
/// match tables.check_integrity(tskit::TableIntegrityCheckFlags::CHECK_INDIVIDUAL_ORDERING) {
/// Ok(_) => panic!("expected Err"),
/// Err(_) => (),
/// };
///
/// // The standard sort doesn't fix the Err...:
/// tables.full_sort(tskit::TableSortOptions::default()).unwrap();
/// match tables.check_integrity(tskit::TableIntegrityCheckFlags::CHECK_INDIVIDUAL_ORDERING) {
/// Ok(_) => panic!("expected Err"),
/// Err(_) => (),
/// };
///
/// // ... so we need to intentionally sort the individuals.
/// let _ = tables.topological_sort_individuals(tskit::IndividualTableSortOptions::default()).unwrap();
/// tables.check_integrity(tskit::TableIntegrityCheckFlags::CHECK_INDIVIDUAL_ORDERING).unwrap();
/// ```
///
/// # Errors
///
/// Will return an error code if the underlying `C` function returns an error.
pub fn topological_sort_individuals<O: Into<IndividualTableSortOptions>>(
&mut self,
options: O,
) -> TskReturnValue {
let rv = unsafe {
ll_bindings::tsk_table_collection_individual_topological_sort(
self.as_mut_ptr(),
options.into().bits(),
)
};
handle_tsk_return_value!(rv)
}
/// Dump the table collection to file.
///
/// # Panics
///
/// This function allocates a `CString` to pass the file name to the C API.
/// A panic will occur if the system runs out of memory.
pub fn dump<O: Into<TableOutputOptions>>(&self, filename: &str, options: O) -> TskReturnValue {
let c_str = std::ffi::CString::new(filename).map_err(|_| {
TskitError::LibraryError("call to ffi::CString::new failed".to_string())
})?;
let rv = unsafe {
ll_bindings::tsk_table_collection_dump(
self.as_ptr(),
c_str.as_ptr(),
options.into().bits(),
)
};
handle_tsk_return_value!(rv)
}
/// Clear the contents of all tables.
/// Does not release memory.
/// Memory will be released when the object goes out
/// of scope.
pub fn clear<O: Into<TableClearOptions>>(&mut self, options: O) -> TskReturnValue {
let rv = unsafe {
ll_bindings::tsk_table_collection_clear(self.as_mut_ptr(), options.into().bits())
};
handle_tsk_return_value!(rv)
}
/// Free all memory allocated on the C side.
/// Not public b/c not very safe.
#[allow(dead_code)]
fn free(&mut self) -> TskReturnValue {
let rv = unsafe { ll_bindings::tsk_table_collection_free(self.as_mut_ptr()) };
handle_tsk_return_value!(rv)
}
/// Return ``true`` if ``self`` contains the same
/// data as ``other``, and ``false`` otherwise.
pub fn equals<O: Into<TableEqualityOptions>>(
&self,
other: &TableCollection,
options: O,
) -> bool {
unsafe {
ll_bindings::tsk_table_collection_equals(
self.as_ptr(),
other.as_ptr(),
options.into().bits(),
)
}
}
/// Return a "deep" copy of the tables.
pub fn deepcopy(&self) -> Result<TableCollection, TskitError> {
// The output is UNINITIALIZED tables,
// else we leak memory
let mut inner = uninit_table_collection();
let rv = unsafe { ll_bindings::tsk_table_collection_copy(self.as_ptr(), &mut *inner, 0) };
// SAFETY: we just initialized it.
// The C API doesn't free NULL pointers.
handle_tsk_return_value!(rv, unsafe { Self::new_from_mbox(inner)? })
}
/// Return a [`crate::TreeSequence`] based on the tables.
/// This function will raise errors if tables are not sorted,
/// not indexed, or invalid in any way.
pub fn tree_sequence(
self,
flags: TreeSequenceFlags,
) -> Result<crate::TreeSequence, TskitError> {
crate::TreeSequence::new(self, flags)
}
/// Simplify tables in place.
///
/// # Parameters
///
/// * `samples`: a slice containing non-null node ids.
/// The tables are simplified with respect to the ancestry
/// of these nodes.
/// * `options`: A [`SimplificationOptions`] bit field controlling
/// the behavior of simplification.
/// * `idmap`: if `true`, the return value contains a vector equal
/// in length to the input node table. For each input node,
/// this vector either contains the node's new index or [`NodeId::NULL`]
/// if the input node is not part of the simplified history.
pub fn simplify<N: Into<NodeId>, O: Into<SimplificationOptions>>(
&mut self,
samples: &[N],
options: O,
idmap: bool,
) -> Result<Option<&[NodeId]>, TskitError> {
if idmap {
self.idmap.resize(
usize::try_from(self.views.nodes().num_rows())?,
NodeId::NULL,
);
}
let rv = unsafe {
ll_bindings::tsk_table_collection_simplify(
self.as_mut_ptr(),
samples.as_ptr().cast::<tsk_id_t>(),
samples.len() as tsk_size_t,
options.into().bits(),
match idmap {
true => self.idmap.as_mut_ptr().cast::<tsk_id_t>(),
false => std::ptr::null_mut(),
},
)
};
handle_tsk_return_value!(
rv,
match idmap {
true => Some(&self.idmap),
false => None,
}
)
}