Skip to main content

TreeSequence

Struct TreeSequence 

Source
pub struct TreeSequence { /* private fields */ }
Expand description

A tree sequence.

This is a thin wrapper around the C type tsk_treeseq_t.

When created from a TableCollection, the input tables are moved into the TreeSequence object.

§Examples

let mut tables = tskit::TableCollection::new(1000.).unwrap();
tables.add_node(0, 1.0, tskit::PopulationId::NULL, tskit::IndividualId::NULL).unwrap();
tables.add_node(0, 0.0, tskit::PopulationId::NULL, tskit::IndividualId::NULL).unwrap();
tables.add_node(0, 0.0, tskit::PopulationId::NULL, tskit::IndividualId::NULL).unwrap();
tables.add_edge(0., 1000., 0, 1).unwrap();
tables.add_edge(0., 1000., 0, 2).unwrap();

// index
tables.build_index();

// tables gets moved into our treeseq variable:
let treeseq = tables.tree_sequence(tskit::TreeSequenceFlags::default()).unwrap();
assert_eq!(treeseq.nodes().num_rows(), 3);
assert_eq!(treeseq.edges().num_rows(), 2);

This type does not provide access to mutable tables.



assert_eq!(treeseq.nodes_mut().num_rows(), 3);

Implementations§

Source§

impl TreeSequence

Source

pub fn new<F: Into<TreeSequenceFlags>>( tables: TableCollection, flags: F, ) -> Result<Self, TskitError>

Create a tree sequence from a TableCollection. In general, TableCollection::tree_sequence may be preferred. The table collection is moved/consumed.

§Parameters
§Errors
§Examples
let mut tables = tskit::TableCollection::new(1000.).unwrap();
tables.build_index();
let tree_sequence = tskit::TreeSequence::try_from(tables).unwrap();

The following may be preferred to the previous example, and more closely mimics the Python tskit interface:

let mut tables = tskit::TableCollection::new(1000.).unwrap();
tables.build_index();
let tree_sequence = tables.tree_sequence(tskit::TreeSequenceFlags::default()).unwrap();

The following raises an error because the tables are not indexed:

let mut tables = tskit::TableCollection::new(1000.).unwrap();
let tree_sequence = tskit::TreeSequence::try_from(tables).unwrap();
§Note

This function makes no extra copies of the tables. There is, however, a temporary allocation of an empty table collection in order to convince rust that we are safely handling all memory.

Source

pub fn as_ptr(&self) -> *const tsk_treeseq_t

Pointer to the low-level C type.

Source

pub fn as_mut_ptr(&mut self) -> *mut tsk_treeseq_t

Mutable pointer to the low-level C type.

Source

pub fn dump<O: Into<TableOutputOptions>>( &self, filename: &str, options: O, ) -> TskReturnValue

Dump the tree sequence to file.

§Note
  • options is currently not used. Set to default value. This behavior may change in a future release, which could break API.
§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.

Source

pub fn load(filename: impl AsRef<str>) -> Result<Self, TskitError>

Load from a file.

This function calls TableCollection::new_from_file with TreeSequenceFlags::default.

Source

pub fn dump_tables(self) -> Result<TableCollection, TskitError>

Obtain the underlying TableCollection.

§Errors

TskitError will be raised if the underlying C library returns an error code.

Source

pub fn tree_iterator<'ts, F: Into<TreeFlags>>( &'ts self, flags: F, ) -> Result<Tree<'ts>, TskitError>

Create an iterator over trees.

§Parameters
§Errors
§Examples
use tskit::StreamingIterator;
// Import this to allow .next_back() for reverse
// iteration over trees.
use tskit::DoubleEndedStreamingIterator;

let mut tables = tskit::TableCollection::new(1000.).unwrap();
tables.build_index();
let tree_sequence = tables.tree_sequence(tskit::TreeSequenceFlags::default()).unwrap();
let mut tree_iterator = tree_sequence.tree_iterator(tskit::TreeFlags::default()).unwrap();
while let Some(tree) = tree_iterator.next() {
}
§Coupled lifetimes

A Tree’s lifetime is tied to that of its tree sequence:

let tree_sequence = tables.tree_sequence(tskit::TreeSequenceFlags::default()).unwrap();
let mut tree_iterator = tree_sequence.tree_iterator(tskit::TreeFlags::default()).unwrap();
drop(tree_sequence);
while let Some(tree) = tree_iterator.next() { // compile fail.
}
§Warning

The following code results in an infinite loop. Be sure to note the difference from the previous example.

use tskit::StreamingIterator;

let mut tables = tskit::TableCollection::new(1000.).unwrap();
tables.build_index();
let tree_sequence = tables.tree_sequence(tskit::TreeSequenceFlags::default()).unwrap();
while let Some(tree) = tree_sequence.tree_iterator(tskit::TreeFlags::default()).unwrap().next() {
}
Source

pub fn tree_iterator_at_position<'ts, F: Into<TreeFlags>, P: Into<Position>>( &'ts self, flags: F, at: P, ) -> Result<Tree<'ts>, TskitError>

Create an iterator over trees starting at a specific position.

See TreeSequence::tree_iterator for details

§Errors
Source

pub fn tree_iterator_at_index<'ts, F: Into<TreeFlags>>( &'ts self, flags: F, at: i32, ) -> Result<Tree<'ts>, TskitError>

Create an iterator over trees starting at a specific tree index.

See TreeSequence::tree_iterator for details

§Errors
Source

pub fn sample_nodes(&self) -> &[NodeId]

Get the list of sample nodes as a slice.

Source

pub fn num_trees(&self) -> SizeType

Get the number of trees.

Source

pub fn kc_distance( &self, other: &TreeSequence, lambda: f64, ) -> Result<f64, TskitError>

Calculate the average Kendall-Colijn (K-C) distance between pairs of trees whose intervals overlap.

§Note
§Parameters
  • lambda specifies the relative weight of topology and branch length. If lambda is 0, we only consider topology. If lambda is 1, we only consider branch lengths.
Source

pub fn num_samples(&self) -> SizeType

Source

pub fn simplify<O: Into<SimplificationOptions>>( &self, samples: &[NodeId], options: O, idmap: bool, ) -> Result<(Self, Option<Vec<NodeId>>), TskitError>

Simplify tables and return a new tree sequence.

§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.
Source

pub fn keep_intervals<P>( self, intervals: impl Iterator<Item = (P, P)>, ) -> Result<Option<TableCollection>, TskitError>
where P: Into<Position>,

Truncate the TreeSequence to specified genome intervals.

§Return value
  • Ok(None): when truncation leads to empty edge table.
  • Ok(Some(TableCollection)): when trunction is successfully performed and results in non-empty edge table. The tables are sorted.
  • Error(TskitError): Any errors from the C API propagate. An TskitError::RangeError will occur when intervals are not sorted.
§Notes
  • There is no option to simplify the output value. Do so manually if desired. Encapsulate the procedure if necessary.
§Example
 let intervals = [(0.0, 10.0), (90.0, 100.0)].into_iter();
 let mut tables = trees.keep_intervals(intervals).unwrap().unwrap();
 // Conversion back to tree sequence requires the usual steps
 tables.simplify(&tables.samples_as_vector(), tskit::SimplificationOptions::default(), false).unwrap();
 tables.build_index().unwrap();
 let trees = tables.tree_sequence(tskit::TreeSequenceFlags::default()).unwrap();

Note that no new provenance will be appended.

Source

pub fn add_provenance( &mut self, record: &str, ) -> Result<ProvenanceId, TskitError>

Available on crate feature provenance only.

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 chrono crate.

§Parameters
  • record: the provenance record
§Examples
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);
use core::str::FromStr;
let dt_utc = chrono::DateTime::<chrono::Utc>::from_str(&timestamp).unwrap();
println!("utc = {}", dt_utc);
Source

pub fn edge_differences_iter<'ts>(&'ts self) -> EdgeDifferencesIterator<'ts>

Build an iterator over edge differences.

Source

pub fn tables(&self) -> &TableCollection

Reference to the underlying table collection.

§Examples
let mut tables = tskit::TableCollection::new(1000.).unwrap();
tables.add_node(tskit::NodeFlags::default(),0.0, -1, -1).unwrap();
tables.build_index();
let tcopy = tables.deepcopy().unwrap();
let tree_sequence = tskit::TreeSequence::try_from(tcopy).unwrap();
assert_eq!(tables.equals(tree_sequence.tables(), 0), true);
Source

pub fn edges(&self) -> &EdgeTable

Get reference to the EdgeTable.

Source

pub fn nodes(&self) -> &NodeTable

Get reference to the NodeTable.

Source

pub fn sites(&self) -> &SiteTable

Get reference to the SiteTable.

Source

pub fn migrations(&self) -> &MigrationTable

Get reference to the MigrationTable.

Source

pub fn mutations(&self) -> &MutationTable

Source

pub fn individuals(&self) -> &IndividualTable

Get reference to the IndividualTable.

Source

pub fn populations(&self) -> &PopulationTable

Get reference to the PopulationTable.

Source

pub fn provenances(&self) -> &ProvenanceTable

Available on crate feature provenance only.

Get reference to the ProvenanceTable

Source

pub fn individuals_iter(&self) -> impl Iterator<Item = IndividualTableRow> + '_

Return an iterator over the individuals.

Source

pub fn nodes_iter(&self) -> impl Iterator<Item = NodeTableRow> + '_

Return an iterator over the nodes.

Source

pub fn edges_iter(&self) -> impl Iterator<Item = EdgeTableRow> + '_

Return an iterator over the edges.

Source

pub fn migrations_iter(&self) -> impl Iterator<Item = MigrationTableRow> + '_

Return an iterator over the migrations.

Source

pub fn mutations_iter(&self) -> impl Iterator<Item = MutationTableRow> + '_

Return an iterator over the mutations.

Source

pub fn populations_iter(&self) -> impl Iterator<Item = PopulationTableRow> + '_

Return an iterator over the populations.

Source

pub fn sites_iter(&self) -> impl Iterator<Item = SiteTableRow> + '_

Return an iterator over the sites.

Source

pub fn provenances_iter(&self) -> impl Iterator<Item = ProvenanceTableRow> + '_

Available on crate feature provenance only.

Return an iterator over provenances

Source

pub fn samples_as_vector(&self) -> Vec<NodeId>

Obtain a vector containing the indexes (“ids”) of all nodes for which crate::NodeFlags::is_sample is true.

The provided implementation dispatches to crate::NodeTable::samples_as_vector.

Source

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 each crate::node_table::NodeTableRow. If f returns true, 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::NodeFlags::new_sample(), 0.0, tskit::PopulationId::NULL,
    tskit::IndividualId::NULL)
    .unwrap();
tables
    .add_node(tskit::NodeFlags::new_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);

Trait Implementations§

Source§

impl TryFrom<TableCollection> for TreeSequence

Source§

type Error = TskitError

The type returned in the event of a conversion error.
Source§

fn try_from(value: TableCollection) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl Send for TreeSequence

Source§

impl Sync for TreeSequence

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.