Struct tskit::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 a copy of the TableCollection. The result is a “deep” copy of the tables.

Errors

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

source

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

Create an iterator over trees.

Parameters
Errors
Examples
// You must include streaming_iterator as a dependency
// and import this type.
use streaming_iterator::StreamingIterator;
// Import this to allow .next_back() for reverse
// iteration over trees.
use streaming_iterator::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 liftimes

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 streaming_iterator::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 samples_to_vec(&self) -> Vec<NodeId>

👎Deprecated since 0.2.3: Please use TreeSequence::sample_nodes instead

Get the list of samples as a vector.

Panics

Will panic if the number of samples is too large to cast to a valid id.

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
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 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 humantime 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 = humantime::Timestamp::from_str(&timestamp).unwrap();
println!("utc = {}", dt_utc);
source

pub fn edges(&self) -> &EdgeTable

Get reference to the EdgeTable.

source

pub fn individuals(&self) -> &IndividualTable

Get reference to the IndividualTable.

source

pub fn migrations(&self) -> &MigrationTable

Get reference to the MigrationTable.

source

pub fn mutations(&self) -> &MutationTable

Get reference to the MutationTable.

source

pub fn nodes(&self) -> &NodeTable

Get reference to the NodeTable.

source

pub fn populations(&self) -> &PopulationTable

Get reference to the PopulationTable.

source

pub fn sites(&self) -> &SiteTable

Get reference to the SiteTable.

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::TSK_NODE_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::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);
source

pub fn edge_differences_iter( &self ) -> Result<EdgeDifferencesIterator, TskitError>

Build a lending iterator over edge differences.

Errors
  • TskitError if the C back end is unable to allocate needed memory

Trait Implementations§

source§

impl TryFrom<TableCollection> for TreeSequence

§

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 Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

const: unstable · source§

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

Mutably borrows from an owned value. Read more
source§

impl<T> Free for T

source§

unsafe default fn free(ptr_ref: NonNull<T>)

Drops the content pointed by this pointer and frees it. Read more
source§

impl<T> From<T> for T

const: unstable · source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

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

const: unstable · 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 Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
const: unstable · source§

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

Performs the conversion.
source§

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

§

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

The type returned in the event of a conversion error.
const: unstable · source§

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

Performs the conversion.